Simply Understood CodePattern: Simply Understood Code
...at the lowest levels of a program are chunks of code. These are the places that need to be understood to confidently make changes to a program, and ultimately understanding a program thoroughly requires understanding these chunks.
* * *
In many pieces of code the problem of disorientation
is acute. People have no idea what each component of the
code is for and they experience considerable mental stress
as a result.
Suppose you are writing a chunk of code that is not so complex that it requires extensive documentation or else it is not central enough that the bother of writing such documentation is worth the effort, especially if the code is clear enough on its own. How should you approach writing this code?
People need to stare at code in order to understand it well enough to feel secure making changes to it. Spending time switching from window to window or scrolling up and down to see all the relevant portions of a code fragment takes attention away from understanding the code and gaining confidence to modify it.
People can more readily understand things that they can read in their natural text reading order; for Western culture this is generally left to right, top to bottom.
If code cannot be confidently understood, it will be accidentally broken.
Therefore, Arrange the important parts of the code so it fits on one page. Make that code understandable to a person reading it from top to bottom. Do not require the code to be repeatedly scanned in order to understand how data is used and how control moves about.
* * *
This pattern can be achieved by using the following
patterns: LocalVariablesDefinedAndUsedOnOnePage,
which tries to keep local variables on one page; AssignVariablesOnce, which tries to minimize code
scanning by
having variables changed just once; LocalVariablesReassignedAboveTheirUses, which tries to make a
variable's value apparent before its value is used while
scanning from top to bottom; MakeLoopsApparent, which
helps people understand parts of a program that are
non-linear while retaining the ability to scan them
linearly; and Use FunctionsForLoops, which packages
complex loop structure involving several state variables
into chunks, each of which can be easily understood.
-- RichardGabriel
See also WellFactoredCode for some discussion about how to stop routines getting too big. There are some patterns there, waiting to be mined. MethodObject? -- DaveHarris
Let's not forget to make it readable (to humans) with MeaningfulComments and MeaningfulNames; it's nice if the structure flows, too (ReadsLikeProse). -- AustinDavid
If the code isn't simply understood, later programmers will probably RewriteCodeFromScratch. -- DanielLowe
''Once you lose the culture that produce the code, it almost always will be a RewriteCodeFromScratch.''
* SelfDocumentingCode
EditText of this page
(last edited August 21, 2007)
or FindPage with title or text search