Tuesday, November 8, 2011

Does function size matter?

I just finished the 3rd chapter of Clean Code by Robert C. Martin and I feel like my brain has exploded.

I couldn't resist writing a post about what I've read so far, to see what others thought about it. Even though I'm only at the very beginning of this book, I can tell I'm going to like it.

  • The first chapter talks about what makes code "clean" (according to the author and a number of developers that are considered industry leaders).
  • The second chapter talks about meaningful names, what makes them important, along with some examples. Interesting, but nothing super exciting.
  • The third chapter is all about functions. This is where I had a mini freak out in my head.

The author believes functions should:

  • use descriptive names
  • be small - about 2 or 3 lines each
  • do one thing and do it well
  • only have 1 or 2 arguments passed to them, preferably none
  • have one level of abstraction

This ends up resulting in a LOT of functions. The author argues that if you do this, your code becomes very easy to understand and reads from top to bottom, like a story.

I've never given much thought to the size of my functions before, but 2 or 3 lines seems exceedingly small. I tend to write functions that are 6 - 10 lines.

I've never given ANY thought to the levels of abstraction in my code, in fact, I didn't even know what that was before I read about it. In case anybody else has never heard of this term, the idea behind it is that everything in the function should be at the same level of granularity. Here is a nice definition from Wikipedia and a post on stackoverflow with a good example.

The author argues that it can be confusing if you don't follow this principle because you aren't able to tell whether an expression is an important concept or a detail. Mixing the two in a function is just as bad as falling to be weary of the broken window theory.

If having code that is easy to read and maintain isn't compelling enough for you, and you are programming against the .Net framework, you might be interested to know that Jeffrey Richter, in CLR via C#, points out that code converted to IL is evaluated on a method by method basis. This means that a method isn't evaluated until it is actually needed - this makes your code run faster. Additionally the CLR optimizes the code by "enregistering " variables in the method, but only if it is small enough. Unfortunately Jeffrey doesn't specify what a "small" method actually is.

No comments:

Post a Comment