CodeSOD: Constantly Magic

Here's one you've seen before. Somebody Fran works with heard that magic numbers were bad, and that you should use constants, so they did this:

const ZERO = 0, ONE = 1, TWO = 2, THREE = 3;

This snippet was repeated nearly twenty times through the codebase. That's bad and silly, of course, but it actually gets worse. Because how were these constants used?

Well, frequently, there were checks like collection.length > ZERO. That's silly, but not offensive, I suppose. But, this codebase also used arrays to represent objects, frequently, where each index of the array was a different field. The result was code like:

const customerId = custRec[ZERO]; //CUSTOMER_ID const customerName = custRec[ONE]; //CUSTOMER_NAME

This too, was spammed nearly twenty times through the code base. And what's beautiful about it, at least by the standards of bad code, is just how forcefully it rejects the entire purpose behind the "no magic numbers" rule. These constants could have been named for the fields they represent, which still would have been annoying, but it wouldn't have been this level of invention. We require a comment because our code is unreadable without it, we require constants because they're supposed to make our code readable. The mismatch is pure art.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.