In PHP we have tons of bad constructs/functions that don’t actually
help newcomers on writing good code: the
SWITCH/CASE statement is one
of those that I hate the most, although very few developers rely on
The statement is pretty straightfoward
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
and is intended to make multiple IFs more readable.
It may seem useful, but at first you should recognize that multiple IFs are already a bad smell, so, from the beginning there is something with a code trying to make them look nicer.
The Strategy pattern, one of my favourites, is a simple but powerful way to avoid writing procedural code that relies on IFs.
The main concept is that you should contextualize the application’s workflow at runtime, deciding which steps (methods) to run based on data which is external to the method itself.
1 2 3 4 5 6 7 8 9 10 11
In this way we are able to isolate and keep clean the implementations of the methods, thus the logic behind the application.
This means that we only need to implement submethods:
1 2 3 4 5 6 7
If this doesn’t seem important to you, consider this scenario:
you are shipping a library with the
SWITCH/CASE in the first example;
what would happen if another developer using that library would only
like to edit the logic when a
catastrophe message is received?
Yes, he would need to override the entire
loosing the possibility to benefit of future software updates
for that specific method.