Jesse Schutt has a new tutorial on the Zaengle blog on Simplifying Conditional Expressions:
As I’ve been reading through Refactoring by Martin Fowler, I’ve found it helpful to rewrite some of the examples from the book in PHP in order to cement the concepts into my mind. While Martin’s examples are primarily in Java, I’ve found an overwhelming majority of the concepts apply to PHP, which is where I spend most of my programming time.
In today’s article, I will attempt to rework the Simplifying Conditional Expressions (pp. 237-270) section into a handful of PHP-based examples.
He works through the following refactoring techniques:
- Decompose Conditional
- Consolidate Conditional Expression
- Consolidate Duplicate Conditional Fragment
- Replace Nested Conditional with Guard Clause
and concludes with why simplifying conditionals is important:
Our goal in simplifying conditional expressions should be to make the code read easier for humans, not for computers. Ideally, you should be able to glance at a conditional, see which is the happy path through the method, and quickly identify when and where deviations should occur.