Debugging

Is Clever Code OK?

“Clever code” is a term that you may have heard before, accompanied by sighs and groans from other developers. Often, people seem to think of clever code as annoying, and perhaps even harmful. In this article, I’m going to give a brief overview of what clever code is, why it’s often avoided, and how it can be turned into a learning experience.

What is “clever code?”

For most, clever code is code that does not immediately “explain” itself. What that means is that the average developer might see it and have to spend more than a few seconds reading the context around it to understand what it does. Here’s an example in PHP:

$foo = 'bar';
// snip
$value = $foo ?: false;

Considering I’ve been writing PHP for nearly sixteen years, I was bewildered when I first saw this in a co-worker’s code a few weeks ago.

“Pretty nifty, huh?”

You bet! I want to use that in the future, and it is a prime example of clever code–the slang of a programming language.

Opposition to clever code

If you’ve used clever code in the workplace, or in other projects where collaboration is a part of what you do, then you’ve probably run across a decent number of people who don’t like it. Some examples of feedback:

  • “So, why did you do it like this?”
  • “What am I looking at?”
  • “Don’t do that again.”

All very reasonable responses. Clever code is often cited as bringing a disadvantage beyond reading comprehension; it’s also viewed as a source of bugs. Implementing code that is harder to read means it’s more likely that you or a developer working in the same file later are more likely to not read the proper flow of the program. Here’s an example of using PHP’s Bitwise And operator:

// Bitwise And.
$foo = false;
$foo &= false;
$foo &= true;
$foo &= false;

var_dump( $foo ); // int(0)

$foo = false;
$foo &= false;
$foo &= true;

var_dump( $foo ); // int(0)

In the first example, you might expect the outcome of false, or “int(0)”. But the second example is a bit confusing–didn’t that end with setting $foo to true? The Bitwise And operator instead looks at both the left-hand value of “$foo” and the right-hand value when making its assignment; thus, if $foo is false even once, the equation will always look like “$foo = ( 0 * 1 = 0 = false ).” This can be extremely useful, but also incredibly confusing.

Another example of Bitwise confusion comes from the Javascript Bitwise NOT operator:

var a = ["f", "o", "o", "b", "a", "r" ];

if ( a.indexOf( "g" ) > -1 ) {
    console.log( "Typical style" );
}

if ( !!~a.indexOf( "g" ) ) {
    console.log( "Clever style" );
}

Again, we can see that the “tilde” operator, coupled with a double negative “!!”, creates clean code that won’t make sense to the average programmer.

How to be smart and clever

This all leads to what I’d like programmers to start doing when considering clever code: create a learning environment for other developers. I’ve seen clever solutions criticized on StackOverflow, and a particular question about it on the Programmer’s StackExchange asking for advice on how to avoid writing clever code in the first place. 

This, to me, is a great example of how programmers see clever code: it’s a party trick; it’s dangerous; it is to be avoided by “serious” programmers.

On the other hand, I think we can start to turn clever code into a learning experience. Once you recognize clever code, you can start to document it when you use it so others on the project know what you’re doing:

function check_user( $can_go_on ) {
    /**
     * NB, Clever: Using PHP's bitwise And operator.
     * See: http://php.net/manual/en/language.operators.bitwise.php
     */
    if ( ! current_user_can( 'manage_network' ) ) {
        $can_go_on &= false;
    }

    return $can_go_on;
}

function check_screen( $can_go_on ) {
    $screen = get_current_screen();

    if ( ! $screen || 'post' !== $screen->base ) {
        $can_go_on &= false;
    }

    return $can_go_on;
}

add_filter( 'can_we_continue', 'check_user' );
add_filter( 'can_we_continue', 'check_screen' );

$can_go_on = apply_filters( "can_we_continue", true );

In the above example, the ‘check_user’ function is documented to give a clear and distinct “Hey! I’m doing something weird here,” as opposed to the second method ‘check_screen’ which quietly uses the Bitwise And without any discussion. Most any programmer would be forgiven for missing it or thinking it’s a typo, and a scrutinizing lead would almost certainly see it and think “Great–now I have to change this and test everything this filter touches.”

A real world example looks like this:

/**
 * CLEVER CODE ALERT. This shorthand ternary accepts the tested value as the value returned if
 * true, otherwise the else value. NB this does not work in reverse (i.e. $a = $b ? 'value' :; ).
 */
$blog_id = $blog_id ?: get_current_blog_id();

Here’s that nifty shorthand ternary again! This saves some characters and looks pretty neat, but there’s a pretty hefty comment above it to explain what’s going on. The comment alone negates the time saved in not writing out the whole ternary, but for me the point of code like this, and the associated documentation, is to teach and inform others.

As programmers working in an increasingly collaborative world, we should be making strides in documentation–not only to guide other developers through the big ins and outs, but also to illuminate the many tricks and secrets that the language holds.

Happy coding!

Have a comment?

Your email address will not be published. Required fields are marked *