The programmers who wanted this journal asked me to write it in C rather than C++. Although I usually prefer C++ there was no compelling reason that C++ was needed. To my surprise, I rather enjoyed writing it in straight C and in fact, I am pretty sure the end result is a lot less complex than it would have been in C++.
Don't get me wrong. I am still a fan of OO but the attitude that anything OO is apriori better than pure procedural is a crock of poo. Programming in C forces you to be economical. There is no fancy data structures, templates or virtual functions. There is no Boost or meta-programming. You basically get arrays, macros and some straightforward libraries for threading, I/O and string manipulation. And for many more problems than you might expect, this is all you need.
In C (well written C anyway), you can almost always look at a piece of code and see by inspection exactly what will happen. In OO languages, with virtual functions, this is rarely the case. When you see p->f() in C++ you need to consider p's type and all classes derived from it to imagine everything that might happen. This often incurs a high cognitive load on maintainers of the code. Of course, with function pointers you can create equally obscure C, but you need to work harder in C so you only do that when there is a good reason. C forces you to keep your eye on the ball.
Now, in defense of C++, I have to say that programming in C++ has actually prepared me to be a better C programmer. For example, I treated all my structs as if they were private and wrote interfaces so users of my API never needed to know the internal workings of theses structs. In fact, most of my structs were hidden in private headers or in the .c files themselves. Most of my implementation functions were statics and hence private. This gave me the flexibility to change the internals without breaking user code. OO taught me to think this way. OO also taught me to think about writing code that can be unit tested and to write the tests right after the interfaces were specified but before the implementation. I brought this discipline to C as well.
The one thing truly lacking in C is exceptions. I have to say that exception handling and RAII are two of C++'s strengths. However, with discipline, you can do without these as well.
So if you ever find yourself forced back into a ancient language like C, don't fret. Take the concepts you learned in more modern languages and think about how you can uses the spirit of those concepts to write better code. You just might enjoy going retro!
No comments:
Post a Comment