I think as developers we tend to create complexity if we don’t think carefully about every line of code we are typing. Systems tend to be complex and managing that complexity is one of the main task we have.

Routines are great, they are one of the best ways to encapsulate algorithms and make your code more readable. Sometimes we think routines are too short, but actually the usually are too long. Reading Clean Code I realized Uncle Bob creates very short routines and all of them have a meaningful name.

Correlation between length of a routine and its name

Usually the longer a routine is the harder is to name it. When you do something like this:

for (var i=0;i<array.length;i++) {
  show(i);
}

It’s very easy to come up with a name like showAllElements(array). But if you are processing a lot of input parameters (like in a web service) and cleaning the input a good name will be harder to find.

Apart from that with small routines you’ll find your bugs easier and the reuse of that little algorithm is more likable since it’s already encapsulated and ready to be used again.

In the book Code Complete a lot of studies are shown without a clear conclusion but when the author is listing all the valid reasons to create a routine you get the idea that most small routines can achieve that. These are some of them:

  • Reduce complexity

  • Make a section of code readable

  • Improve portability

  • Simplify complicated boolean tests

Exceptions

Steve Mcconnell says in Code Complete that to ensure all routines are small is not a valid reason to create a routine:

In fact, some jobs are performed better in a single large routine.

Conclusion

In my experience, most of the time you can improve the readability of your code by creating smaller routines. To finish let me show you the following piece of code used by Steve to illustrate how using short routines can improve readability:

if ( node <> NULL ) then
  while ( node.next <> NULL ) do
    node = node.next
    leafName = node.name
  end while
else
  leafName = ""
end if

He points out that this code should be encapsulated in a routine like GetLeafName(node).