Structure over Function

From WikiContent

(Difference between revisions)
Jump to: navigation, search

Revision as of 11:32, 4 February 2009

When learning to program, the function of a piece of code is the most important thing to get right after the syntax of the programming language is mastered. Many non-professionals are easily satisfied with code that (somehow) works. Do not stop there.

This early satisfaction with function can be bad. Code needs to be clean to allow smooth evolution. Cleanliness means good structure. Good and bad structure exist at many levels: the amount and order of statements in a loop or conditional; the nesting of such control structures; the statements within a function; the functions within a module or class; the relationship between one piece of code to another; the partitioning and dependencies between subsystems.

Bad structure can occur at all levels, but good structure starts from the ground up. Keep your program code clean and understandable from the statement level up. Consider your code as not "working" unless it is actually working in a way that you and other professionals can easily understand.

There is a well-known cognitive capacity for short-term memory: seven plus or minus two items, meaning that it is easy to grasp between five to nine different things at once but not more. If you need to comprehend more things at once, you either need to concentrate very hard or, usually, your brain starts to group elements implicitly to keep some coherent picture of the whole.

Try to keep your code organized and use this five-to-nine elements at a given level of abstraction as a guideline to judge when better structure is needed. Other principles apply as well. After the size, the number of relationships should be minimized. Notice that there are not only explicit but often also implicit relationships. Understand and manage the number of relationships. Loosen coupling as much as it makes sense. On all levels of abstraction. Refactor your code to keep its structure within understandable boundaries.

by Peter Sommerlad

This work is licensed under a Creative Commons Attribution 3

Back to 97 Things Every Programmer Should Know home page

Personal tools