Programming philosophy -- factoring

As you're writing a complex piece of software, you have the opportunity to break chunks of code out into separate procedures or functions, or write the code inline. I think programmers tend to do too much inline, and should modularize or factor more.

A few reasons why factoring is good.

Giving a block of code a name and a parameter list is like having a comment that's part of the program structure. It's a chance to say clearly to a future reader what the code they're reading does. It's a way to communicate.

You get a new slate for local variables. A fresh mental stack frame. You can give things shorter names because they'll only be used in a small scope. No guesswork when reading the code about where these values might be used, and less temptation on the part of future maintainers to reuse something that might not be reusable for all time. A chance to avoid future code fragility, breakage. (Think of it as the programming equivalent of defensive driving.)

You get to use a return statement to get out of the code. That makes error checking simpler, easier to follow in the code. Simplifies the code.

Even if there are just one or two lines in the function today, you never know.

Managing complexity is what building maintainable code bases is about. The easier it is to understand the building blocks, the higher you can build your castle.

If you do it well, the calling code can be simpler, it's functionality totally clear. It can almost read like haiku. Real-time code, in order to work, often has to attain that level of simplicity.

And if the problem comes up again, you can just call the function. That makes your code smaller and easier to work on. It's also like solving a puzzle. Satisfying.

But strike a balance. Too much factoring can obscure functionality.

Make sure that the layer you add makes sense in terms of what the software actually does. Introducing an unnecessary layer of abstraction is something a new contributor has to learn, and even you may have to relearn it at some point, as your code base gets huge, you tend to forget how you put it together.


Posted: Wed, 28 Aug 2013 16:29:19 GMT