Programming Proverbs 5: Construct the program in logical units

This is the fifth of a series of posts based on the book Programming Proverbs by Henry Ledgard. The index for the series is an earlier post and discussion of the list as a whole is taking place in the comments there. Comments on this "proverb" are of course very welcome here.

To many Construct the program in logical units seems pretty logical (no pun intended). After all what is the alternative - illogical units? But at the time the book was written huge monolithic programs were common place. A lot of beginners still code the same way today though. The way to understand this proverb is the understand that by "logical units" what is meant is a lot of units that are logically complete and relatively independent.

A logical unit handles a set of logic, instructions for a single  purpose, that is small and easy to understand. The standard I have heard is that a unit should fit on one page of paper. Some would say one screen. Traditionally a sheet of computer paper back in the line printer days was 66 lines. The traditional screen held 24 lines. Today of course with screens coming in all sorts of sizes and fonts allowing us to get a lot on a piece of paper these sorts of arbitrary line counts don't make much sense.

Think about is as the amount of code one can look at and keep in ones head at one time. Could you, after spending a small amount of time reviewing the code, reproduce it from memory? If not it is clearly too long. To really understand and debug (or better yet make sure there are no bugs before actually testing it) you have to be able to get it really deeply into you head.

A logical unit should do one thing and do it really well. It should be easy to understand so that if it needs to be changed or debugged someone new can look at it and understand it in totality. The last thing one wants to do is guess what is going to happen. Not a problem in a reasonably sized logical unit.

 

Technorati tags: programming proverbs