I have a question regarding the number of lines of code in a method. Mosh mentioned that having more than 10 lines of code in a method is generally considered bad practice and suggested that we should aim to reduce it. I understand this perspective.
In the “Java Advanced - Exceptions” section of his course (7th section), which can be found here: Course Link, he demonstrates using try and catch blocks. Even with a simple file read operation, the code ends up being around 12-15 lines.
Given this, how can we effectively reduce the number of lines of code while still handling exceptions properly?
That thinking comes from the book Clean Code by Robert Martin.
For me personally, I try to make my functions do one thing and one thing only. Once it starts to do more than 1 thing, that’s when the literal lines of code in a function drastically go up and I would have to refactor the function and break it down into multiple smaller functions. The thing is, you normally wouldn’t want to “pre-optimize” your code before you know it is a good solution to the problem you are solving. Solve the problem first AND THEN go back and optimize your code for better readability and performance.
There are a few ways how to reduce the number of lines in the example linked above. The most straightforward way would be to put individual blocks into dedicated functions:
var reader = new FileReader(...);
try {
doSomething(reader);
}
catch (IOException e) {
handleIOException(e);
}
finally {
finalizeReader(reader);
}
Going even further, you could make reader a member variable. This is how you can get to the number of lines in terms of Clean Code and Robert Martin.
From experience, it is generally more important to write code that is clean - meaning that the intent of the code is clear - than trying to adhere to some arbitrary code metrics. 8-10 lines of code per function/method is only a rough measure and should not be taken dogmatically. Sometimes I simply do not have the time/budget, or the right idea how to get the code into an “ideal” shape. On some occasions it is even not possible to meaningfully reduce the code to the specified measure. A canonical example is when parsing user input or deserializing data, where error handling is an essential part of the business logic and cannot be “hidden” in some way.