Flexible Code = Expensive Code
March 8th, 2007[ Software Development ]
I got into a conversation today about code bases and building them to be flexible. An overly simplified example is constructors.
Let’s say we’ve got an object for a person called Person.cs. Person has a properties for Name and HairColour. Those properties have sets and gets. So conceivably we could make Person more flexible by adding upwards of 4 constructors:
Person(string Name)
Person(string HairColour)
Person(string Name, string HairColour)
So now you can use the empty constructor and set the properties, or call one of the other three. More flexible to use than having a single empty constructor. Flexible = good?
Sure, but flexible = expensive as well. It’s hard to imagine in this overly simplified example, however, by adding this so called flexibility we’ve increased the number of available code paths. All of which we’re on the hook to develop and support which translates directly into cost, ie cash.
As well, by creating more code paths, we’ve increased our ability to introduce more bugs, and more importantly we’ve made it more challenging to hunt down those bugs. Why? Again, a simple example:
Person me = new Person();
me.Name = “duder”;
// path 2
Person me2 = new Person(“duder”);
Clearly path 1 and path 2 will produce identical results right? Well no, not necessarily. They’re unique code paths. The second constructor could be calling a private variable where Name is stored instead of using the set on the Name property. Someone may have incorrectly added name related logic into the path 2 constructor instead of in the Name set.
Bottom line, the more code paths available, the more expensive it is to build and the more brittle the application becomes. Brittle meaning easier to introduce bugs, harder to find those bugs.
So flexibility in a code base is bad? No, not at all. Flexibility is important when it adds to the overall functionality of the application. It’s great to have all those constructors on Person, however, it does not add any functionality. I guarantee you it’s cheaper to build and support that class with only an empty constructor and it has no less functionality.