Code Abominations

I was “triggered” this past week with some comments on a client’s code.

These are some Abominable Code things that test to set me off of on a whinge when I see them. As with Abominables everywhen, some my be slightly tamed by pulling their teeth and, of course, some bounce which makes the funny to look at instead of scary. They are still Abominables though.

Java script

Ugly Boolean Idiom

const someBoolean = !!someTruthyThing

This is an truly hideous idiom for converting a Truthy value to a Boolean. It does this ugly thing of taking the logical NOT of the logical NOT to get back to the original sense but as a Boolean instead of a Truthy.

For clarity sake, just type the few other characters to make it explicit.

const someBoolean = Boolean(someTruthyThing)

Any Language

Ternary operators

Ternary operators should be removed from every language.

auto resolvedDecision = valueToConsider ? trueOption : falseOption;

For clarity sake, just type the few other characters to make it explicit.

auto resolver = [](auto value)
    {
        if (value)
        {
            return trueOption;
        }
        return falseOption;
    };

auto resolvedDecision = resolver(valueToConsider);

This is one of those that is the hardest to argue to folks. Yeah, in some narrow cases it can be a Toothless Abominable and seems silly to be concerned about. As long as the Abominable stays small and toothless, you might get away with it. Unfortunatedly these things tend to regrow their teeth and get larger over time. Just do away with them.

The arguments for using Ternarys tends to be that it is concise and that it will result in faster or better code generation.

When concise leads to lack of clarity, you should choose clarity.

For any modern (in the last 30 years) compiler (for the compiled languages), the compiler+optimizer will generally result in nearly identical final code for the Ternary version compared to the Explicit version of the code. For languages that are not compiled, you probably do not really care about the tiny performance gains of the concise code. If you do, you should switch to a compiled and optimized langauge. In either case, the clarity of the code will provide more value to you in the long run.

Useless Boolean Conversion

const resolvedDecision = valueToConsider() ? true : false
auto resolvedDecision = valueToConsider() ? true : false;

This combines a Ternary with a different way to get to a Boolean (in Javascript). It will also be seen in other languages where folks do not know or trust the return value of a method. If javascript and related languages with a Truthy, just cast to a Boolean (as above). In other languages, just trust the type system. In either case, if you cannot trust the type system or do not want to cast in place, wrap it in a well-named function to make it clear what you are wanting to happen.

const resolvedDecision = Boolean(valueToConsider())
auto resolvedDecision = valueToConsider();