Write shorter routines.

Studies have shown that longer and more complex routines are subject to error and more expensive to maintain.

To avoid these problems, your routines should be simpler and shorter. One way to look at this is to find a tool that measures your code’s cyclomatic complexity. Every function call, every for loop, every if statement and other branching conditionals increase the cyclomatic complexity.

The longer a routine is, the more logic it contains and the harder it is to easily grasp what all it can do. Also, an error can occur at any of the different points, so the more logic it contains, the more error-prone it becomes. A routine with 20 points of logic is needlessly complex, and would require a ton of tests to fully cover.

Refactor your routines to be smaller, so there’s less things to go wrong and the tests are easier to assemble. Also, when new readers examine the code, they’ll be more likely to fully comprehend all of the logic points if there simply aren’t many present.

Some people like to use 10 lines as a guide. Try to keep your routines under ten lines. Comments don’t count as lines in this, so feel free to add comments, as long as they explain why the logic does what it does. Don’t add needless comments that simply echo the code itself.

In some languages, like Ruby on Rails, the convention is to keep routines under five lines. Ideally, a routine should be responsible for doing only one thing. If you follow that ideal, you’ll naturally have shorter routines.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: