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.

No alt text provided for this image

What are the Board Pins? this picture will help you.

No alt text provided for this image
Board Pins

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:

  1. The same filters/processing logic could be duplicated in multiple client classes.
  2. Maintaining the code is not that easy since many files could be included in the maintenance class.
  3. The client classes define the domain business while it is the domain class' responsibility.
  4. Modifying the code could require implementing the same changes in many files.

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.

No alt text provided for this image

Explanation:

  1. The wrapper class takes by its constructor the list of pins.
  2. The list of pins should not be accessible from outside classes.
  3. All functionalities of the list are within the Wrapper class.

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!

要查看或添加评论,请登录

Tarek Haydar的更多文章

社区洞察

其他会员也浏览了