Keep It Small
Classes and functions (methods) should be small.
Let's start with functions. Many years ago I read Scott Ambler's book Building Object Applications That Really Work.
Perhaps the greatest thing I learned was the 30-second rule. Very simply it means that if a function cannot be understood
by another developer within 30 seconds, then it is too complex and should be refactored.
Some people advocate for a specific number of lines of code, like a maximum of 30. If I had to do that, I would
go with about 10 lines of code. I favor simplicity. But when push comes to shove, I prefer Scott Ambler's
30-second rule. It's about two related things: readability and maintainability.
If I write a function that is 100 lines of code (I would never do that), but it is so simple that another
developer can understand it in 30 seconds or less, I'm confident that it is both readable and maintainable.
But if it takes that same developer an hour to understand my function, then we can safely say that it is
difficult to read and understand and not easy to modify.
The same can be said about classes. Keep them short and focused on one particular thing.
They say a picture is worth a thousand words. Let's test that out that theory with the photo on the left.
I love IDEs, but they can obscure the size of our files. One can scroll through a file in a matter of seconds.
And the search and navigation capabilities make it easy to find what we are looking for. There is nothing
quite like a physical copy of some code to provide some perspective. In this photo, we have a class that
is approximately 1,400 lines of code. I had to use my driveway to capture the entire thing. The length is approximately
19 feet with about 60 lines of code per page. Go grab a tape measure
and see exactly how long 19 feet is. Now ask yourself one question: how much time
would it take you to fully understand this class?
By the way, that class isn't abnormal. I've seen plenty of classes that are 2,000 lines or longer. In fact,
I once worked on one code base where a single function exceeded 3,000 lines of code.
Another topic that touches on code length is cyclomatic complexity which I discuss in another post.
©
Donald A. Barre. All rights reserved.