First time I was using PHP Mess Detector (a PHP Quality Tool), I was very surprise. 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
The ThoughWorks Anthology (written by many well-known programmers like Martin FOWLER). In this
chapter, Jeff BAY define 9 rules to write better software. Avoid else expression is one of them.
Whaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat?!
— one of my colleague when I say ‘Else is unnecessary’
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 response when I talk about this. But you know, every developer write specific
code (in 2016, CRUD are generated). If you don’t, I’m sorry for you!
So, sometimes it’s difficult to avoid this expression. Most of times, it came from another problem:
you don’t know design patterns.
Solution 2: State Pattern
If your code look like this:
First of all, replace this conditions by 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 simply 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:
And this is how does 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 sometime ;-)). Most of time, the first solution is the solution. Take care,
sometimes too much design patterns lead your application to overengineering. First, make sure
it’s relevant and remember: pragmatism over theory.
Oh, by the way, I implement this 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.