Simple Code
Writing clean and readable code is kind of a good habit every programmer should have. Usually, clean code also tends to be simple. But don’t be mistaken—not everything that looks simple is automatically good.
Take a look at this PHP code example:
$order = ($order > 0 && $order <= $stock) ? $order : ($order < 1 ? 1 : $stock);
Looks concise? Yes. Easy to understand? Hmm… not necessarily.
If you’re confused, that’s totally normal. This code is actually trying to ensure that the order quantity is at least 1 and no more than the available stock. But still, reading it takes effort—especially if you haven’t looked at it in a while.
The problem is, code like this is prone to becoming a source of bugs. Sure, it’s short, but it’s not reader-friendly. And believe me, the main reader isn’t the computer—it’s your coworkers (or your future self two weeks from now).
A good programmer isn’t the one who writes the shortest code, but the one who writes the most understandable code. So, don’t be too quick to take pride in your one-liner code—it’s not always a good thing.
The solution? We can make the logic clearer with a more human-friendly approach. For example, using a function like this:
private function forceIntToRange(int $num, int $min, int $max): int
{
if ($min > $max) {
throw new InvalidArgumentException('Minimum value exceeds maximum value.');
}
if ($num < $min) {
return $min;
}
if ($num > $max) {
return $max;
}
return $num;
}
...
$order = forceIntToRange($order, 1, $stock);
Now, the intent is much clearer: we just want to make sure the value stays within a reasonable range. Easy to read, easy to debug, and if something goes wrong, we know where to look.
If you’re interested in digging deeper into how to write cleaner and more sensible code, feel free to check out Better Programming. There’s a ton of great insights and tips to help you become a more solid programmer.