I have read several OOP books where there is an emphasis on rule for defining classes which has focused set of responsibilities. In a number of applications that I have worked , most of the times this is being adhered to. However I see a lot of cases where a lot of logic is being dumped into a single method making it difficult to comprehend / unit test. What are the best practices that needs to be followed while defining methods?
As an example let's look at the following method:
public static void printDetails() {
System.out.println("Current time: " + LocalTime.now());
System.out.println("Current date: " + LocalDate.now());
System.out.println("Available processors: " + Runtime.getRuntime().availableProcessors());
System.out.println("Max memory: " + Runtime.getRuntime().maxMemory());
System.out.println("Free memory: " + Runtime.getRuntime().freeMemory());
}
After some refactoring we have more readable and maintainable version:
public static void printDetails() {
printDateTimeDetails();
printProcessorDetails();
printMemoryDetails();
}
It is easier to read. And what is more important - it is easier to test. When you read the body of this method you clearly understand it's purpose. If you need more details you can simply look deeper in the code and see what every method does.
public static void printProcessorDetails() {
System.out.println("Available processors: " + getAvailableProcessors());
}
public static int getAvailableProcessors() {
return Runtime.getRuntime().availableProcessors();
}
public static void printMemoryDetails() {
System.out.println("Max memory: " + getMaxMemory());
System.out.println("Free memory: " + getFreeMemory());
}
public static long getFreeMemory() {
return Runtime.getRuntime().freeMemory();
}
public static long getMaxMemory() {
return Runtime.getRuntime().maxMemory();
}
private static void printDateTimeDetails() {
System.out.println("Current time: " + LocalTime.now());
System.out.println("Current date: " + LocalDate.now());
}
And also such code is reusable.
The Boy Scouts have a rule: "Always leave the campground cleaner than you found it." Actually the original form of that rule, written by Robert Stephenson Smyth Baden-Powell, the father of scouting, was "Try and leave this world a little better than you found it."
Of course all of this in my opinion.