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

Guideline RP6: Do not hardcode repetitive entities

Do not enumerate a list in statements (and other typographical atrocities). If you have a list of 63 cities, for example, and you wish to initialize an array, one approach would be to set the first element to "tallahassee", the second to "denver", and so forth, as shown in the example below. The problem with this approach is maintenance. If you need to insert "boise" after "denver", then you have to renumber all the entries from "denver" to the end of the list. Let the compiler (or interpreter) help you whenever it can. Just create an array, language permitting, and give it the list with which to initialize. The language will then do the assignments; you do not have to. So adding a name in the middle is as simple as editing the list in place.

Sharp eyes will further note that the explicit manual assignments vs. the array initializer are not equivalent -- the former starts the indexing from 1, the latter, from 0, which is generally better form.

EXAMPLEPerl
Instead of:
	$cityName[1] = "tallahassee";
	$cityName[2] = "denver";
	$cityName[3] = "chicago";
	$cityName[4] = "san jose";
	$cityName[5] = "san francisco";
	$cityName[6] = "pittsburgh";
	...
Use:
	@cityName = (
		"tallahassee",
		"denver",
		"chicago",
		"san jose",
		"san francisco",
		"pittsburgh",
		...
	);
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