Too short routines?

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++) {

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 probable 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


Despite what you might think sometimes is better to have long routines (more than 100 lines of code). 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.


I always try to create good code but if I don’t see a way to make a routine better, even if it’s long, I move onto the next problem. Anyway, in my experience, most of the times you can improve the readibility of your code by creating smaller routines. To finish let me show you the following piece of code used by Steve to illustrate what I’m trying to say:

if ( node <> NULL ) then
  while ( <> NULL ) do
    node =
    leafName =
  end while
  leafName = ""
end if

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