While I am writing this blog, I am also working full time. As I write the blog, my own ideas clarify against my experiences. This is one such evolutionary realization.
I am not sure whether I wrote earlier:
In ideal programming, decisions belong either to the top of the class hierarchy or at the leaf.
“if” statements come in two flavors: the “existential if” and the “value if”.
The existential if statements reflect hard realities of computation. “Whether the file pointer was NULL” or “Whether the malloc succeeded” or “Whether the password matched”. There is hardly anything one can do in the “else if” or “else” parts of this condition. These statements are the least attractive candidates to be pushed into a “switch-case” structures.
The value if statements are different. “Whether current temperature is within limits”, “Whether the passed parameter is an upper case letter”, “Whether this packet is of IPX protocol” and so on. Under normal circumstances, such statements also have a very strong “else if” or “else” parts. These are ideal candidates to convert into “switch-case” statements.
As a matter of fact, a reasonably written C code will have 90% of the control statements as “value if” – and that is where the problem lies. A lot of these decisions are just type decisions – if the value of the variable a is x, the type must be y and z function needs to be called.
That is where OO starts scoring. In a good OO code, type decisions are minimal. The same situation would simply translate into: invoke z method of a. There is no decision to be taken!
This factor is often ignored when embedded systems programmers berate OO as slow because VFT lookup may slow down the program. However, we just now avoided a decision using OO and made the execution *faster*. In my experience, OO avoids a lot of decisions and hence compensates for the standard (and hence optimised) VFT lookup.
In one of the (scripting) OO codes I have written, only one existential if was needed per thousand lines of code – and no value if was ever needed in 20k line of code. The code ran 25% faster than its procedural counterpart. I am yet not factoring in the design flexibility OO brought with itself.