Home > Articles > Programming

  • Print
  • + Share This
From the author of Cargo Cult Languages

Cargo Cult Languages

Sometimes, cargo cultism reaches all of the way into the language. C++ and Python are both great examples of languages that adopt features from other places, without understanding what they were useful for originally.

C++ classes, for example, are a spectacular example of how to completely miss the point. In an object-oriented language, objects are simple computers that communicate via message passing. They are black boxes and can be swapped out for ones with the same interface without modifying any of the rest of the program.

In C++, objects are instances of classes, and classes are just C structures (occasionally with a hidden field pointing to a vtable, which is an array of function pointers). When you want to use a C++ class, you include the header file which defines it.

If you come from a language that's been designed (as opposed to congealed), then you might expect that the header file contains the interface, and that the implementation is elsewhere. This is not the case. It contains all of the fields of the structure—instance variables, for people familiar with object-oriented languages—including the private ones. Yes, even things that are explicitly not part of the public interface must be present in the header. Why? So that the compiler knows how big the class is when allocating an instance of it. More specifically, to avoid the cost of a load instruction before allocating an instance of a class, and to allow it to be allocated in static storage.

This has the side effect of completely destroying any loose coupling. If you modify a C++ class—even adding or removing a private instance variable or method—then you potentially change the layout and need every single file that uses it to be recompiled. You get neither the data hiding nor the loose coupling that are the two largest benefits of object-oriented programming.

  • + Share This
  • 🔖 Save To Your Account