Refactoring Series - Part 002 - Return Wrappers as Method Responses
Hello again!
This is the second article of the refactor series.
In the first article, we have seen how returning a class is better than primitive data types.
Today we have an interesting case, let's get started!
We have the GetBoardPins method that takes the board identifier and returns a list of Board Pins as follows.
What are the Board Pins? this picture will help you.
The method implementation is pretty simple, it reads data from the persistence layer and maps the data models to the domain models.
What are the drawbacks of the method?
Many classes in this project use the GetBoardPins method. They read, filter, and process the board pin list that is returned as the method response.
领英推荐
In my humble opinion, returning a list of a class has weaknesses as follows:
Refactor Time!
To enhance the code, I decided to return a class that wraps the BoardPin list.
The reason behind my choice is that the client classes should be simple and stupid, all they have to do is call the corresponding method in the wrapper class.
The wrapper class should be as follows.
Explanation:
This refactor decreases the client classes' responsibilities. They do not have to contain complex logic for filtering, processing, and manipulating data. The BoardPinWrapper class becomes responsible for handling the domain rules, which makes our code encapsulated.
In the next article, we will use the decorator pattern in the refactor task. Stay tuned!