Saturday, January 31, 2015

IMHO: Why C++ is broken

Recently I had the privilege to be part of a team of very strong programmers. Everyone in this small team has many years of experience in writing code for systems that are critical in performance, stability, maintenance.
A part of the product that I was in charge of, had to store information in a database. To store the information in the DB I had to serialize it, and for that I used Tomer Filiba serializing template for C++ called construct++. From the construct++ I see a small crack in the language, the implementation of the serializing is brilliant, but the code itself is ugly in a way that only C++ (and maybe Perl) can make you write. Code that is so ugly that only Bjarne Stroustrup can love. This is not Tomer's fault, it's 100% C++ to blame. But if one don’t find this kind of syntax to be discouraging from using the language, take a look at the lambda functions of C++11. For example:
auto func = [] () { cout << “Hello world”; };
You put it into a template and you got yourself every type of brackets in one line of code… Ugh...
But ugly syntax is nothing to be afraid off. A simple example of where the language is really broken could be derived from using both Templates and Forward declarations in the same code.

  1. Using templates. Note that Template definition must be done completely from the header file.
  2. Forward declaration. Two classes are using each others methods, for example DB of cars and owners data, if a car class needs to ask a person class about weight, and person needs to ask about the size of the car. In that case, the implementation has to be done in the CPP file, while the each header will have a forward declaration of the other class.

If the two classes are both templates and referring each other, they can’t be in the header file nor can they be in the CPP file . One might say this is a bad design, but in my opinion it’s possible to find a good case where this kind of design is required.
Anyhow, the entire C++ implementation of templates has a wrong attitude for the problem. Templates came to introduce simple compile time code generator to the language. Templates is a poor implementation of a code generator for C++, that is just a bit aware of the code. This is a perfect example of how code generator should never be implemented. Not only is this code generator unreadable, it also imposes new restrictions on your code, which makes none code generated code to be less effective.
Of Course I’m not the first person to complain about C++. Most notable is Linus here: http://harmful.cat-v.org/software/c++/linus which I can’t agree more with.
As for the bad syntax: http://stackoverflow.com/questions/4295681/evil-samples-of-subtly-broken-c-code

Cheers,
Assaf