Oct 20, 2010

Dammit Janet! Write those small classes.

This blog entry is inspired by a C++ framework I’m working with (but my suggestions apply equally well for C# and even Java I imagine). One part of the framework deals with frequencies. Unfortunately, it is littered with magic numbers and code like this someFrequency*1e3 or someFrequency*1e6. The point of the magic numbers is obvious but still strikes me as something that shouldn’t make it into production code. Two constants  KHZ_TO_HZ and MHZ_TO_HZ  would make the code easier to read and maintain but that really isn’t enough.  The point is that littering all these conversions throughout the code is completely unnecessary and one of the things object oriented programming was designed to solve. This code needs a very small and simple Frequency class.

When confronted with this as a new user

double some_freq = sampling_freq * 1e3;

I immediately have the following questions: What units is sampling_freq in? What units does FrameworkCall() expect the parameter to be in. Off I go searching the code to find the answer. If instead they had written a simple frequency class the code would look like this:

Frequency some_freq (sampling_freq, fuKHz);
FrameworkCall(some_freq.FreqInHz() );

Now it’s immediately obvious that sampling_freq is in KHz and that FrameworkCall () requires a value in Hz.  Even better if FrameworkCall() just takes a Frequency object, I don’t even need to know what units it will ultimately deal with and that’s the point of encapsulation.

With the Frequency class there will NEVER be a need to write an additional line of code to convert between frequency units. The class does nothing more than take whatever value you pass in and store it internally in HZ. Then it has getter methods that return whatever units you request.  In my version I have constructors that take either double or decimal and I support Hz, KHz and MHz. I could easily extend this class for other units in the future if required. Internal to the class are NO magic numbers. Even though it will probably never be looked at, the conversions are all done with named constants.

So if you find yourself converting frequencies, or time, or lengths or just about any unit based value, consider if writing a small wrapper class wouldn’t make your code more readable.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.