Someone on Twitter got all exasperated that there is an isEven() function in Javascript to compute whether a number is an even number. After all it is equivalent to the simple expression of ((n % 2) == 0); why would they not use this? Well, already this simple example contains most of what you need to know about software design and programming decisions.
Lowering intellectual burden by reducing impedance mismatch. isEven() is easier to type (and not get wrong) and easier to understand than using the modulo expression. By being closer to what you want to say, your code gets better and you make less mistakes.
Encapsulation / information hiding. By wrapping a function with a clear name around a more complex expression, you are separating the implementation of what you want to do from those who need it done. In fact, the implementation of isEven() appears to be not(isOdd()) rather than the modulo expression. Conceptually, this doesn’t matter.
Trade-offs in system design / multiple perspectives. Separating abstraction (interface) from implementation is a well-known design principle. Still, it can have performance downsides: Clear code that introduces multiple indirections may slow down the system. Hence, there may be situations when you may want to avoid interface/implementation separation.
Incorrect performance assumptions. Unless you are pretty technical, you can’t entirely predict how your compiler will resolve a call to isEven(). A good compiler will see through the indirections and inline all necessary code. Even though you may be writing isEven() you may be getting the modulo expression right in place, ensuring that there is no performance difference.
Machismo is not a good guide. There are enough challenges in software development. Insisting that everyone be able to break down things to bit operators is not going to be helpful.
Leave a Reply