Handling multiple conditions OOP way

Many times in our applications we need to handle multiple conditions which most of the times ends as huge ifs. When we can do it fast & dirty it’s good enough but when we want to code clean we don’t really want huge procedural comparison.

So lets break this to smaller pieces.

  • We have 1+ conditions
  • Every condition needs to be satisfied
  • We check these conditions against same object

Conclusion can be

  • We need some type of chaining where we can check multiple conditions
  • We are using AND
  • We need some common interface with method which gets out subject as parameter

Additional requirement in my case was to have it work with Symfony 2 DIC.

So lets create the code. It’s quite simple.


This is our common interface. Method isSatsfiedBy takes our object and returns if check was positive or not.

Next we need our chaining class which handle multiple conditions

And that’s all. Now we can use our new classes.

We leverage OOP and encapsulate each specification in different object. With Dependency Injection we build complex conditions. Specific conditions can be used later to atomic checks it other places of our application. ChainSpecification depends only on SpecificationInterface so it can be pulled from application to external library. It will appear soon on my GitHub.

At the beginning I mentioned Symfony 2 DI Container. All we need to implement specific Specifications and after that we can build chains without additional glue code.

Now we can do complex check in one line.


Leave a Reply