Robert’s Rules of Coders: #4 Make Functions Short
Posted by robkraft on August 18, 2015
Functions are easier to understand and thus easier to maintain when they are short. You can often make functions shorter by finding patterns in a large function and extracting those lines of code comprising the pattern into a separate function and calling the separate function as shown below.
Note: The FormatForOutput function is not shown because I believe you can figure out what it does.
But even when you have a long function with no lines of code that are duplicated, you can often make the code more readable and easier to maintain by separating the code into functions. Consider this example:
Note: The 4 new functions are not shown because I believe you can figure out what they do.
Most developers will be able to understand the 2nd example better than the first. But there is another big benefit that applies in a lot of languages. Let’s assume that an error occurs with a message of “Object variable is null”. In the first example, the error message might show a call stack that says our program named Program1 called the method MainCodeBlock and this error occurred within MainCodeBlock.
Call Stack from First Example:
But which line of code within MainCodeBlock? We don’t know and it could have been caused by many of the lines. However, if the same error occurs in the second example, our call stack would look like:
Call Stack from Second Example:
In the second example, we have narrowed down the problem to the SavePriceToDatabase method and have only a few lines of code to consider as the source of the error. This is another benefit of smaller functions.
Finally, for those of you that write unit tests as most good programmers should, you have functions neatly wrapped up and ready to be called by those unit tests.
In summary, short functions provide these benefits:
- They organize your code, making it easier to understand and maintain.
- They make it easier to pinpoint bugs when you have a call stack.
- They make it easier for you to write unit tests for your code.
Go to Robert’s Rules of Coders for more.