How to write clever code

Entry no. 16971_

First, you start with something simple…

In order to start writing code as cleverly as we can, we first need a basic concept to work from. In the case of this example, we’ll be writing a simple function which evaluates a parameter and returns a value based on that parameter (with a default return value option). Short and to the point.

function doStuff($data) {  
  if ($data == 'val1') {
    $result = 'Value One';
  } elseif ($data == 'val2') {
    $result = 'Value Two';
  } else {
    $result = 'Unknown Value';
  }
  return $result;
}

…and you make it better

Obviously, this just won’t do… If we’re going to establish our credibility as a programmer, we are duty-bound to find some clever trick to make our code stand out among the crowd… Luckily, we know one such trick!

function convoluteStuff($data) {
  switch(true) {
    case $data == 'val1':
      $result = 'Value One';
    break;
    case $data == 'val2':
      $result = 'Value Two';
    break;
    default:
      $result = 'Unknown Value';
    break;  
  }  
  return $result;
}

MOAR CLEVERER!!!

While the above example does, indeed, show off our innate ability to add unnecessary complexity to even the simplest tasks (I mean, who likes “if” statements, anyway?), it doesn’t go far enough. It lacks a certain elegance, so to speak.

We need to really tout our abilities, here… Our code needs to be so clever, that we can puff out our chests and elevate our noses at those who don’t immediately grasp its function.

function cleverStuff($data) { 
  return $data == 'val1' ? 'Value One' : ($data == 'val2' ? 'Value Two' : 'Unknown Value');
}

Now this… THIS is clever code! Notice how we abandoned the structural breakup of indentations altogether and went straight to using convoluted ternary combinations? This is the work of a genius! The fact that you can't simply glance at it to understand what it's doing is the key. After all, the idea of coding is to make your code so obnoxious that anyone who has to maintain it after you curses you with plague and pestilence, right?