Simplifying Conditionals

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.


Filed in: Laravel Tutorials


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Mid / Sen. Software Engineer
Clearwater, FL
ShineOn
Remote PHP / Laravel Developer
Remote
SpringboardVR
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
Senior Laravel Developer
Leidseplein, Amsterdam
Orderchamp.com
PHP Developer
Remote
X-Team
Senior Laravel Developer (Canada and India)
London, Ontario, Canada
Factory Bucket Inc.
Laravel, PHP, PostgreSQL, Neo4J Developer
Pune, India (intern in Denver, CO)
Life AI