We start this new series with the pattern called Criteria,
This pattern allows you to build search queries using a common interface,
which makes the code much more modular and flexible.
I have assembled the examples with Typescript but the implementation of said pattern is equally valid for other languages.
Let's see an example where the use of the Criteria pattern can help us.
First of all we are going to create a very simple type to define what is a Client for our domain:
then suppose we have to perform several filters to the following list of clients:
Clients who are over 15 years old:
Now we are going to complicate the query a bit,
imagine that we are asked to obtain the clients whose age is older than 20 and younger than 30 years old,
who are women and your city is Madrid or Barcelona
As we can see, things start to get complicated and it starts to be difficult to maintain and read,
In addition, at the semantic level there is a large margin for improvement,
for this, we will see how we can improve these aspects by applying the Criteria pattern.
We start by creating the interface that will define our Criteria, we will use typescript generics for it
to gain flexibility:
We continue creating a Composite class that implements our Criteria interface, it will also allow us to
maintaining an array of criterias to apply and of course the implementation of the required meetCriteria method
upon implementation, the addCriteria method will allow us to add criteria that will function as AND:
Finally, as I mentioned above, the addCriteria when adding criteria to a list would work implicitly
as an AND therefore we will need to make an implementation to be able to do OR operations:
First of all we will create some queries which will help us in the construction of our filter:
This is where the magic happens since we will be able to mount the filtering to our liking and with much greater semantics,
I am sure that if I give you this code you will know very quickly which filter is being built: