The first time I was using PHP Mess Detector (a PHP Quality Tool), I was very surprised. Because,
when I type an Else expression, it raises an error which it said: “An if expression with an
else branch is never necessary”. What the f***, I have never seen something like this before.
Indeed, this principle came from Jeff BAY in Object Calisthenics, an exercise-chapter from The
ThoughWorks Anthology (written by many well-known programmers like Martin FOWLER). In this
chapter, Jeff BAY defined 9 rules for writing better software. “Avoid else expression” is one of
them.
Let’s see how we can write code without the traditional “else”.
Solution 1: reorder your code
Ok, given you have a function like this:
The first step, is to replace $name variable by a return statement.
And because, we’re not beasts, we should inverse condition (avoid finish your function with
pseudo-exceptions).
And tadaaaa! else condition disappears!
Ok, you’re kind but this example is very easy. Trust me, I write specific code and I can’t drop
else! — one of my colleague
That was my colleague’s answer when I mentioned this. But you know, every developer writes specific
code (in 2016, CRUD were generated). If you don’t, I’m sorry for you!
So, sometimes it’s difficult to avoid this expression. Most of the time, it came from another
problem: design patterns misknowledge.
Solution 2: State Pattern
If your code look like this:
First of all, replace these conditions with a switch statement. It’s pretty much the same, but a
little bit more readable.
And then, you should use the State Pattern.
Now I can move my car like this, without switch/else/elseif condition!
Nb: Instead of creating an AbstractCarState, you can implement the CarStateInterface for all of
your XXXCarState.
Solution 3: Strategy Pattern
Sometimes, you have to check the object’s instance before doing something.
Now you can use it like this:
Solution 4: NullObject Pattern
In this solution, examples come from
Dominik Liebler Github repository
Sometimes need to check if an object isn’t null before doing something. Like that:
This is how NullObject Pattern works:
This is how it works:
As far as I’m concerned, I prefer this pattern when he’s combined with patterns like
Factory.
Conclusion
I apply this principle every day. And now 90% of my if blocks, does not contain any else expression!
(yeah, I am lazy sometimes ;-)). Most of the time, the first solution is the solution. Take care,
sometimes too many design patterns lead your application to over-engineering. First, make sure
it’s relevant and remember: pragmatism over theory.
Oh, by the way, I implement these patterns
in a Github repository. You can take a look, it’s
fully tested!
About the author
Hey, I'm Maxence Poutord, a passionate software engineer. In my
day-to-day job, I'm working as a senior front-end engineer at Orderfox.
When I'm not working, you can find me travelling the world or cooking.