Is isEven() a bad function to have?

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.

Posted on

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share the Joy

Share on LinkedIn

Share by email

Share on Twitter / X

Share on WhatsApp

Featured Startups

QDAcity makes qualitative research and qualitative data analysis fun and easy.
EDITIVE makes inter- and intra-company document collaboration more effective.

Featured Projects

Making free and open data easy, safe, and reliable to use
Bringing business intelligence to engineering management
Making open source in products easy, safe, and fun to use