The single most hideous line of code I’ve ever seen

Have you ever used a ternary expression inside a condition? I hope not. It seems that whoever wrote the Java drivers for MongoDB didn’t have this much sense.

The offending line of code can be found here: ConnectionStatus.java

It basically goes like this:

try {
    // a bunch of stuff
} catch (Exception e) {
    if (!((_ok) ? true : (Math.random() > 0.1))) {
        // silently ignore error
    }
    else {
        // log error
    }
}

The intent appears to be to log just 10% of errors that result in an “okay” status, while logging all “not okay” errors. However, this condition is utterly unreadable, and I believe this awful implementation actually yields the opposite result.

I’m not even going to talk about how revolting this line of code is. Instead, I will dedicate the rest of my post to trying to figure out its logic. Let’s start by breaking down that ternary statement into something that makes a little more sense.

bool condition;

if(_ok) {
    condition = true;
}
else {
    condition = Math.random() > 0.1;
}

if(!condition) {
    // silently ignore error
}
else {
    // log error
}

Now we can see that “condition” is true if either the “ok” flag is true, or we drew a random number greater than 0.1 (90% chance). Therefore, we can write this:

if(!(_ok || Math.random() > 0.1)) {
    // silently ignore error
}
else {
    // log error
}

Now, applying the negation (using DeMorgan’s law):

if(!_ok && Math.random() <= 0.1) {
    // silently ignore error
}
else {
    // log error
}

So what is the result? We silently ignore 10% of “not-okay” error conditions. We log 90% of “not-okay” errors, and all of the “okay” errors. Is there a chance this was the intended behavior? Sure. Does it make sense? Hell no.

The moral of this story: code review is important.

Published by

Travis Mick

Travis is the chief architect of systems and software at Zeall.us. A background in network security research has fostered in him a passion for values such as digital privacy, net neutrality, and intellectual freedom. In a world where these causes are increasingly important, he aims to both raise awareness of them and further their goals through technology.

Leave a Reply