CleanCode logo
sitemap
SEARCH:
NAVIGATION: first page in sectionprevious pageup one levelnext pagefinal page in section

Guideline RP3: Do not repeat isomorphic code fragments

Taking the idea of duplicate code from identical fragments, consider the issue of code fragments which are isomorphic (i.e. containing similar--though than identical--code, yet mirroring each other in function). Just as described for identical fragments, if there is a sequence of statements which you can point to and say that they perform a particular task, put that sequence into a separate function that you parameterize for any differences. If, for example, you have one function with statements A, B, C, D=x+5, E, F and a second with A, B, C, D=x+10, E, F, then parameterize the function f(param) so that statement D becomes D=x+param, making the sequences truly identical. The example below provides a strong case for even a single line code fragment to be encapsulated.

EXAMPLEPerl
Instead of:
	# print at most first 3 elements of array @a, separated by commas...
	print join(",", (@a)[0..min(2,$#a)], ($#a > 2 ? "..." : ()));
	# ... but store it with virgule separators
	$data = join("/", (@a)[0..min(2,$#a)], ($#a > 2 ? "..." : ()));
Use:
	sub abbrJoin {
		my $sep = shift;
		return join($sep, (@_)[0..min(2,$#_)], ($#_ > 2 ? "..." : ()));
	}
	print abbrJoin("," @a);
	$data = abbrJoin("/", @a);
Valid XHTML 1.0!Valid CSS!Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads
Copyright © 2001-2013 Michael Sorens • Contact usPrivacy Policy
Usage governed by Mozilla Public License 1.1 and CleanCode Courtesy License
CleanCode -- The Website for Clean DesignRevised 2013.06.30