Index


Overview


A helper method is just a name for any method you add to a class to help other methods do their work.

Some programming styles might favor long functions but in the OO approach we aim for short clear methods. Therefore, while coding, when a method starts to get too long, we would consider partitioning/splitting the logic between multiple methods.

Example Problem


Let's say we have been given a spec to write a method named "print". The method receives three parameters which are all strings.
The parameters tells us if we should print a header, detals, and footer, respectively.

For each parameter, if the value is "1", "T", "true", "Y", "yes" (case insensitive) then that means true. Otherwise false.

The params are not booleans because the spec says this information is coming from a variety of sources.

We put our head down and begin coding and this is our first cut.
public void printTry1(String option1String,
						String option2String,
						String option3String)  {
	if (option1String.equals("1")
		|| option1String.equalsIgnoreCase("Y")
		|| option1String.equalsIgnoreCase("Yes")
		|| option1String.equalsIgnoreCase("T")
		|| option1String.equalsIgnoreCase("TRUE"))
			printHeader();
	if (option2String.equals("1")
		|| option2String.equalsIgnoreCase("Y")
		|| option2String.equalsIgnoreCase("Yes")
		|| option2String.equalsIgnoreCase("T")
		|| option2String.equalsIgnoreCase("TRUE"))
			printDetails();
	if (option3String.equals("1")
		|| option3String.equalsIgnoreCase("Y")
		|| option3String.equalsIgnoreCase("Yes")
		|| option3String.equalsIgnoreCase("T")
		|| option3String.equalsIgnoreCase("TRUE"))
			printFooter();
}
Code review does not go so good. We're told the method is way too complex.

We use our imagination. This would be ideal if we had booleans as this code sample demonstrates.
public void printImagined(boolean option1,
							boolean option2,
							boolean option3)  {
	if (option1)
		printHeader();
	if (option2)
		printDetails();
	if (option3)
		printFooter();
}
We can see that the complexity is the String adds a lot of complexity compared to a boolean.

  • So we decide to move that logic out into a helper method and call it "conformOption".
  • By partitioning the logic if we now look at our "print" method, it is effectively the simple "ideal" code we hoped for.
public void 
2
print(String option1String, String option2String, String option3String) { if (conformOption(option1String)) printHeader(); if (conformOption(option2String)) printDetails(); if (conformOption(option3String)) printFooter(); } private boolean
1
conformOption(String option)
{ List<String> trueStrings; trueStrings = Arrays.asList("y", "t", "yes", "true", "1"); for (String trueString: trueStrings) if (option.equalsIgnoreCase(trueString)) return true; return false; }