Closed bglamadrid closed 2 years ago
Summary
Quoting myself commenting in PR #150
What I did in tests that involved lots of Pojo manipulation was to create separate methods to construct these Pojos (
createPersonWithId
,createPersonWithoutId
), so I could just refer to a instance for a specific purpose in a single line.However I am coming to realize that a better solution exists. There is a design pattern called
Builder
that can help us create these Pojos in a much cleaner way.Indeed, a
Builder
for each Pojo in this project would do wonders. Here's a great article that explains the design pattern, its use case and how it ends up looking like. The basic idea is to refactor all uses of Pojo constructors and setters out of tests into a class specialized in creating Pojos.And here's my take on this. Methods for these Builders should be chainable by returning the Builder themselves on each call except
build()
or related methods.Expected outcome
To be able to create Pojo classes using a clean, uncluttered API similar to
Pojo instance = new PojoBuilder().withName("name").withId(1).build();
These chain calls could be refactored down to separate methods and would still be readable.
Considered alternatives
Defining methods to separate creation logic. Which proved to aid little in improving code readability.
At best, it took lines away from test methods. At worst, it just appended them to the end of the test class.
Is it ok we annotate those pojo's w/ @builder since we are using lombok?
@NyorJa damn... I'm defeated now. I didn't know Lombok provided such an annotation!
Totally YES.
Summary
Quoting myself commenting in PR #150
Indeed, a
Builder
for each Pojo in this project would do wonders. Here's a great article that explains the design pattern, its use case and how it ends up looking like. The basic idea is to refactor all uses of Pojo constructors and setters out of tests into a class specialized in creating Pojos.And here's my take on this. Methods for these Builders should be chainable by returning the Builder themselves on each call except
build()
or related methods.Expected outcome
To be able to create Pojo classes using a clean, uncluttered API similar to
These chain calls could be refactored down to separate methods (Director methods?) to be reused and they would still be readable.
Considered alternatives
Defining methods to separate creation logic. Which proved to aid little in improving code readability.
At best, it took lines away from test methods. At worst, it just appended them to the end of the test class.