Understand why you should avoid else in your code.

Paulo Real
6 min readApr 4, 2023

--

It seems almost unnecessary to avoid using `else` since it is usually very present in our code. But I’ll explain why this small change in your code style can impact the result of your code interestingly.

A paradigm shift

First, I need to quickly comment on the paradigm shift that this small change in your code routine can bring you.

A paradigm shift is a chance to get out of our comfort zone and start doing something routine in a completely different and occasionally better way.

So, before getting into the technical part of the thing, imagine looking at your code and thinking, Man, how can I do this without using else?
I guarantee that just this little internal argument will help you rewrite that code without else and serve you as a beautiful example that we can continuously improve our work.

Now finally, let’s talk about code…

Less code

The less code we write, the less code our colleagues and ourselves need to review, right?

— Wait a minute, you’re telling me that by avoiding using else in my codebase, I’ll write less code?

That’s right. It seems too simple, and it is! By implementing this strategy, you can write less code. Let’s see the first example:

public function isPositive($amount)
{
if($amount > 0) {
$result = true;
} else {
$result = false;
}

return $result;
}

Now let’s see without the else:

public function isPositive($amount)
{​
if($amount > 0) {
return true;
}

return false;
}

This little example seems good enough to start with.

The difference seems small if you consider the number of lines in this first example. But we can see that the instance without else is cleaner than the first one.

To illustrate this point, let’s consider a piece of code with several conditions and see how it looks in the next section.

Complexity

I’ll quote here a metric called cyclomatic complexity, which calculates your method’s complexity (soon, I’ll write about it and post it here). The number of decision points of the analyzed method determines this complexity. These are the decision points: if, while, for, and case. This metric aims to measure the number of paths the software can follow.

Okay, but why are we talking about this?
Because the more else the more complex the code… got it?

Let’s see, as an example, a method that checks the access availability of a user given their activation status and the time limit for using the application:

if ($user) {
if (date('H') > 22) {
if ($user->active) {
$hasAccess = true;
} else {
$hasAccess = false;
}
} else {
$hasAccess = false;
}
} else {
$hasAccess = false;
}

Now without else:

$hasAccess = true;

if (!$user && !$user?->active) {
$hasAccess = false;
}

if (date('H') > 22) {
$hasAccess = false;
}

Now tell me, this refactored example is much easier to understand without the else, right? Did you notice that we can write less code and achieve the same result?

And I don’t even mean just the total lines of code, but also the elimination of the “Hadouken effect” in the code:

The obvious point I still need to mention is that less complex code makes it easier to understand, so a code review and future maintenance become more straightforward.

Another consideration in this topic is the impact on unit testing. For example, minimizing if-else statements can reduce code complexity and the required unit tests for a given code. In addition, with fewer conditional paths to consider, the testing process becomes more efficient and effective.

A code more “SOLID”

The fact that you abandon the excessive use of else can give you more vision for a more assertive use of the SOLID principles, especially the single responsibility principle.

Imagine a class where you receive data from a financial transaction that accepts three different main types of payment: credit card, bank transfer, or mobile payment. In this class, you need to calculate the fee for this service according to the payment type, with the card being a percentage and the others a fixed amount, and return the total amount minus the fee charged.

We can do it in different ways, right? Using if-else is a way to go, and also, there is our good and old friend switch-case, or match if we are using PHP v8.0+.

For this example, let’s consider theese fees:
Credit card: 5%
Bank transfer: $2,50
Mobile Payment: free of charge
Other methods: $3,75

class Transaction
{
public function calculateFee($transaction)
{
if ($transaction->method == 'creditCard') {
$fee = $transaction->amount * 0.05;
} elseif ($transaction->method == 'bankTransfer') {
$fee = 2.5;
} elseif ($transaction->method == 'mobilePayment') {
$fee = 0;
} else {
$fee = 3.75;
}

return [
'fee' => $fee,
'total' => $transaction->amount - $fee,
];
}
}

Now let’s apply some SOLID and remove the if-else statement. This time the whole amount of lines will not be fewer, but it will be much more interesting to read and improve when we need to:

class Transaction
{
public function calculateFee($transaction)
{
$method = $this->getMethod($transaction->method);

return [
'fee' => $this->$method($transaction->amount),
'total' => $this->calcTotal($transaction->amount, $fee),
];
}

protected function getMethod($method)
{​
if (method_exists($this, $method)) {
return $method;
}

return 'default';
}

protected function creditCard($amount)
{​
return $amount * 0.5;
}

protected function bankTransfer($amount)
{​
return 2.5;
}

protected function mobilePayment($amount)
{
return 0;
}

protected function default($amount)
{
return 3.5;
}

protected function calcTotal($amount, $fee)
{
return $amount - $fee;
}
}

We have a lot of relevant points about this example, but I’ll keep the focus on using else, and in another article, I’ll talk more about SOLID, okay?

Note that the class, even though it was a little more extensive than the previous example, was very simplified, and easy to edit any part when needed.

Imagine if, in addition to the main rate, it would be necessary to calculate a new rate and interest if the payment method used is a credit card, or if we just added some more payments methods, we can resolve with a few new lines, and with a higher level of security since it will not be necessary to change existing methods.

Precision

Did you notice that we created the variable in all the refactoring examples before the if statement? This technique is a good code practice behavior as it can avoid bugs because if we make a mistake in our conditional, the variable with a default value already exists.

Imagine if we need to calculate an additional interest besides the default rate fee in the payment example. In one of the condition clauses, we forget to add the variable with the calculation. In the least problematic scenario, we will have a PHP NOTICE: Undefined variable error, and in the worst scenario, we will miss charging interest on the payment.

Now imagine if a variable is left blank in an authentication method, and we give unrestricted access to a harmful user.

And even if the team has a good code review culture and an exclusive QA to test all PRs, it’s worth making our code as assertive as possible.

Performance

So far, we have discussed the importance of code style and how it impacts the readability and maintainability of our code.

The truth is that there is no significant difference in machine performance between both code styles, and the absence or presence of “else” statements in our code have no significant impact on machine performance.

However, I can emphasize human performance here, as discussed above.

By reducing code complexity and improving code readability, we make it easier for developers to understand and modify the codebase, leading to the better long-term performance of the project as a whole. In contrast, a not improved designed and overly complex codebase can delay development progress, increase the probability of bugs, and make maintenance a nightmare.

Consequently, prioritizing code readability and maintainability can optimize human performance and ultimately achieve a more efficient and effective project outcome.

To use else or not to use, that is the question!

I’m not talking about eliminating else from your workflow forever, but here’s my challenge: avoid “else” whenever possible.

In conclusion, it’s worth emphasizing that everything I’ve shared in this article is personal opinions based on years of experience. I understand that we devs tend to have strong personal preferences regarding code styles, so feel free to disagree and comment about it.

After everything we’ve talked about, what’s your opinion? If you already use this practice or decide to follow it, tell me what you think, okay?

Thanks, and see you next time 🖖

--

--