Do you want to rid of the long and complicated “If Else”

Hello guys, today we dive into how can we stop using complicated if else and write them in a better way. This is a design pattern but I’ll prefer to explain this design pattern using PHP.

Let’s create a system that has these features:

  • Email verification
  • Fill up detail of the profile as required after registration
  • Authorization
  • Dashboard

What is the problem with that system?

After logging in we should check users if verified their email and filled up their profile. If our users have done these steps, we should decide to redirect it to the dashboard of the authorization.

Let’s create a bad code example:

As you see there is more than one if else. Even we can put there more if else for the define which user will be redirected to which page relevant to their roles but I wanted to keep it simple to ensure that you understand what is the problem.

What is the solution for this?

The solution is “chain of responsibility” design pattern.

What is the Chain of Responsibility design pattern?

Basically, splitting “if else” into classes that is just responsible for doing one check. Afterward, if the request passed the control, the chain continues and sends the client request to another part of the chain.


Until here, we defined an interface to pass a handler class to the setNext function.

Basically that AbstractHandler’s setNext function helps us to define the chain after that chain. The “handle” function helps us to make the chain works. When we call the “handle” function, it checks if there is nextHandler, if it is, it runs it.

Now let’s adapt it to our code

We defined the last handler to run all these chains.

A new version of our code and that’s all.

Thanks for reading till there, I hope I could help you guys :)




Freelancer Full Stack Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store