Page 51 - The Art of Designing Embedded Systems
P. 51
38 THE ART OF DESIGNING EMBEDDED SYSTEMS
Partition with Encapsulation
The OOP advocates correctly and profoundly point out the benefit of
encapsulation, to my mind the most important of the tripartite mantra en-
capsulation, inheritance, and polymorphism.
Above all, encapsulation means binding functions together with the
functions’ data. It means hiding the data so no other part of the program
can monkey with it. All access to the data takes place through function
calls, not through global variables.
Instead of reading a status word, your code calls a status function.
Rather than diddle a hardware port, you insulate the hardware from the
code with a driver.
Encapsulation works equally well in assembly language or in C++
(Figure 3-1). It requires a will to bind data withfunctions rather than any
particular language feature. C++ will not save the firmware world; encap-
sulation, though, is surely part of the solution.
One of the greatest evils in the universe, an evil in part responsible
for global warming, ozone depletion, and male pattern baldness, is the use
of global variables.
What’s wrong with globals? A partial list includes:
Any function, anywhere in the program, can change a global vari-
able at will. This makes finding why a global change is a night-
mare. Without the very best of tools you’ll spend too much time
finding simple bugs; time invested chasing problems will be all out
of proportion to value received.
Globals create tremendous reentrancy problems, as we’ll see in
Chapter 4.
While distance may make the heart grow fonder, it also clouds our
memories. A huge source of bugs is assigning data to variables de-
fined in a remote module with the wrong type, or over- and under-
running buffers as we lose track of their size, or forgetting to
null-terminate strings. If a variable is defined in its referring code,
it’s awfully hard to forget type and size info.
Every firmware standard-backed up by the rigorous checks of code
inspections-must set rules about global use. Though we’d like to ban
them entirely, the truth is that in real-time systems they are sometimes un-
avoidable. Nothing is faster than a global flag; when speed is truly an
issue, a few, a very few, globals may indeed be required. Restrict their use
to only a few critical areas. I feel that defining a global is such a source of
problems that the team leader should approve every one.

