DEV Community

Cover image for Closure as a strategy pattern
Phi Nguyen
Phi Nguyen

Posted on

Closure as a strategy pattern

Recently I have a complicated task (and interesting too) and I've resolved it with closure, let's see how I do that.
(In case you didn't know about closure, I recommend this link)

So, let's talk about the task. Imagine that we have a table that shows data get from a database. It has a search bar, a pagination, and sort buttons on every column so, on every change event, we have to fetch new data. Everything is fine till now. It's just a normal table on a modern website now.

And here is the hard part. Even though we just have one table, but based on the previous action of the user (some criteria), we have to fetch data in different ways.

To get more clear about the task, let see the following example:

table task

In the example, we have a table that shows a list of cars. The list is fetched based on the user's action before (called outer criteria) combined which criteria of itself (search, paging, sort) (called inner criteria).

Basically, we can implement a table component that checks all criteria from outer and inner then make a request to the backend. But, I think, it isn't a good solution. Because, in this case, we just have 2 simple actions but in real life, we have more than 2 as well as more complicated.

So, my solution is using closure like strategy pattern. In simple words, the strategy pattern says a context can choose/select function at runtime. In our case is fetching data.

Then how to implement that?
It's very easy, instead of sending action criteria to the table component, we will send it a function, a closure function. And It will call that function to get a list of cars. A simple implementation as following:

That's it. This approach makes functions easier to manage and extendable.

How do you think about this? Do you have any approach to this task?

Top comments (0)