Refactor Your Conditions to a Method in PHP



Hello devs in this tutorial i will teach you that how you can refactor your php conditions to a method for better readability. Sometimes you know that we need to write many conditions in one if else. But we can refactor it using method.

There are many ways to refactor the code but I would like to talk about this little technique which doesn’t take lot of your thinking and makes your code look readable instantly.

So, see this for example function.

public function placeOrder()
{
  if ($this->customer->allowed && $this->customer->hasPayment() && $this->product->inStock) {
    // Process the order
  }
}

 

Though this code looks fine, there’s a room for improvement in it in terms of refactoring. See the improvements

public function placeOrder()
{
  if ($this->canProcessOrder()) {
    // Process the order
  }
}

private function canProcessOrder()
{
 return $this->customer->allowed && $this->customer->hasPayment() && $this->product->inStock;
}

 

Recommended : When to Choose Composition Over Inheritance in PHP

 

I think this is pretty good than before. Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.