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

Guideline RP2: Do not repeat identical code fragments

Removing whole functions or methods which are exact duplicates of others goes a long way towards improving maintainability of a system. Taking this a bit farther, let's look at duplicate code fragments. If function f has statements B, C, D, E, and F sequentially, while function g has statements L, C, D, M, and N, consider wrapping C and D into a separate function which is then called by both f and g. This could apply to a dozen common statements, a half-dozen, or as little as one statement if it represents a palpable task. So it may not make sense to do this in some cases.

The example below shows the identical code fragments emboldened. We have an overloaded method readFile which takes two different argument types. In each method, once the appropriate BufferedReader is created, the code is then identical. So a much cleaner design is shown in the second part of the example: the common code has been shifted to a private method, and the original methods are reduced to a single line, each calling the now-common method with its own BufferedReader. (One could even make the common method public, offering yet a third way to read a file.)

EXAMPLEJava
Instead of:
	public static String readFile(InputStream stream) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream)));
		StringBuffer myData = new StringBuffer("");
		for (String s = null; (s=reader.readLine()) != null; ) myData.append(s+NL);
		reader.close();
		return myData.toString();
	}

	public static String readFile(String fname) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(fname)));
		StringBuffer myData = new StringBuffer("");
		for (String s = null; (s=reader.readLine()) != null; ) myData.append(s+NL);
		reader.close();
		return myData.toString();
	}
Use:
	public static String readFile(InputStream stream) throws IOException {
		return readFile(new BufferedReader(new InputStreamReader(stream)));
	}

	public static String readFile(String fname) throws IOException {
		return readFile(new BufferedReader(new FileReader(fname)));
	}

	private static String readFile(BufferedReader reader) throws IOException {
		StringBuffer myData = new StringBuffer("");
		for (String s = null; (s=reader.readLine()) != null; ) myData.append(s+NL);
		reader.close();
		return myData.toString();
	}
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