6.1 Keep It Brief
A big problem with the maintainability of many programs is that their code units are just too long. (By "code unit" I mean a subroutine or the main program.) Once a code unit exceeds the length of what you can view all at once, it becomes harder to maintain. Therefore, consider the number of lines displayed per screen by your editor to be a strong suggestion for the maximum size of a code unit.
Sometimes you can make the case for extending the definition of "code unit." For instance, an exception-handling block may be sufficiently decoupled from the code preceding it that it can be considered a separate code unit for maintainability purposes.
When you're faced with a massive lump of code, break it down into smaller code units. Isolate a section of code that operates on only a few variables, and put it into a subroutine that takes those variables as input and/or output. Find a section of code that is repeated and put it in a subroutine.
You have to be able to invent a plausible name for the subroutine that describes what it is doing. There is little benefit to having a subroutine with a long name that is still so obscure that you can't remember what it does without looking at its source. As you create each subroutine, write documentation for it that describes how to use it. If the documentation takes a long time to write, that's a clue that you haven't picked a good section of code to isolate.
|