This is a post about programming practices and design in general. Even if you’re not a programmer, you should read this and let me know what you think.
Consider these two C++ classes:
class SimpleFrobulotron { public: SimpleFrobulotron(const string &name); string getName(); private: string m_Name; }; class FastFrobulotron { public: FastFrobulotron(const string &name); void getName(string * outName); private: string m_Name; };
The main difference between the two designs is simple: The SimpleFrobulotron is easier to understand and use, but somewhat slower than the FastFrobulotron. For example:
void printFrobulotronNames() { SimpleFrobulotron simple("tweedle dee"); FastFrobulotron fast("tweedle dum"); //display the simple frobulotron's name cout << simple.getName() << endl; //display the fast frobulotron's name string fastName; fast.getName(&fastName); cout << fastName << endl; }
Is FastFrobulotron really that much faster than SimpleFrobulotron? A test on my machine shows that FastFrobulotron runs in 27% of the time that SimpleFrobulotron runs in. So it is clear that there’s a trade off here: Simplicity versus Speed. Code that squeezes every last bit of performance out of the machine is harder to understand. What side of this trade off do you favor, and why?
In this case, I think the answer is obvious: returning a string from a function is much slower than assigning it through a pointer. This is a simple enough optimization that most good programmers should be able to look at the code and understand what’s going on. Therefore it’s best to make use of it. Things can get much more complicated than this simple example, though.
Writing code that does what it’s supposed to do is something most programmers can do (unless you give them the halting problem.) Writing code that’s easy to understand, however, is not. Neither is writing code that is as efficient as possible. The problem is that these two goals (simplicity and efficiency) seem to be at odds with each other. How do you balance between the two?