Simple Code

Writing clean and neat code is a culture of good programmers. And it comes together with simple code. However simple code is not always good.

Let’s take a look at a PHP code below.

$order = ($order > 0 && $order <= $stock) ? $order : ($order < 1 ? 1 : $stock);

Getting crazy? Computers might not.

In case you don’t get it: it’s a logic to force the order quantity to be at least 1 and not more than the stock quantity available.

The code looks simple, compact, and technically might run a little faster. But is it easy to understand? I might take a minute to understand after a week of not touching it. It is a chance for certain code to be buggy.

Good programmers write code which humans easy to understand. Like, very easy. Simple code doesn’t make sense to say it “simple” just because of its small amount of length or the number of lines it takes place in your workplace.

We can write the code above a way better by creating a special function and simplify the logic where possible.

function forceIntToRange(int $num, int $min, int $max): int {
    if ($min > $max) {
        throw new Exception('Minimum value exceeds maximum value.');
    if ($num < $min) {
        return $min;
    if ($num > $max) {
        return $max;
    return $num;


$order = forceIntToRange($order, 1, $stock);

The code becomes self-explanatory and less confusing.

I would recommend you Better Programming for more programming articles. There are many tips and tricks that I found useful.