Stop Using Setters PDF
Stop Using Setters PDF
You have 2 free stories left this month. Sign up and get an extra one for free.
1 class Person {
2 private int age;
3 private String firstName;
4 private String lastName;
5 // getters and setters...
6 }
7
8 Person employee = new Person();
9 employee.setAge(25);
10 employee.setFirstName("Michael");
11 employee.setLastName("Brown");
This approach seems quite elegant, but let’s think about it. Firstly, we
instantiate an empty object which has nothing inside it. After that we
assign required values step by step. What if we forgot to assign the first
name or the age? That means that future executions would handle an
incomplete object. More than that, setters presence means that object is
mutable and can be modified by anyone at any time. Let’s see another
example.
Perhaps this argument might be not convincing enough. So, let’s see
another example. Suppose we have a map of employees with their
payment rates.
That happens because new Jack’s hash-code is not equal to the one that
is containing on the map. So, the keys are considered different. There is
a hack that can fix this situation, but it deserves another story.
implementation returns the same value even if you changed some field
values. Thanks tw-abhi for pointing!
By the way, I have also seen people using setters with dependency
injection in frameworks like Spring. Check this out.
1 @Component
2 class ParentService {
3 ...
4 @Autowired
5 public void setChildService(ChildService childService) {
6 this.childService = childService;
7 }
8 }
9
10 @Component
11 class MyService {
12 private ParentService parentService;
13 ...
14 public void corruptTheRuntime() {
15 parentService.setChildService(null);
16 }
17 }
Anyway, what can we do about it? Well, the easiest thing is passing all the
required values to the constructor.
1 class Person {
2 private final int age;
3 private final String firstName;
4 private final String lastName;
5
6 public Person(int age, String firstName, String lastName) {
7 this.age = age;
8 this.firstName = firstName;
9 this.lastName = lastName;
10 }
11 // getters...
12 }
13
14 Person mary = new Person(25, "Mary", "Watson");
Do you see that all properties are final now? It is very important. It
means that values can be assigned only once within the constructor
scope. Immutability assures us of the object’s constant state. We can pass Top highlight
“But what if needed default values?”. Well, Java doesn’t support default
argument values, but we can define multiple constructors with some
parameters omitted. Or we can use Builder-pattern. We can implement it
ourselves, but I prefer to use the Lombok library.
1 @Getter
2 @AllArgsContrustor
3 @Builder
4 class ReallyHugeClass {
5 private final int param1;
6 private final int param2;
7 ...
8 private final int param10;
9 }
10
11 // Too many arguments. Hard to read and maintain.
12 ReallyHugeClass hugeness = new ReallyHugeClass(1, 32, 12, ..., 231);
13 // Much better now
14 ReallyHugeClass otherHugeness = ReallyHugeClass.builder()
15 .param1(1)
16 .param2(32)
17 .param3(12)
18 ...
19 .param10(231);
Conclusion
I hope that I convinced you that setters usage is not a good practice.
There are some situations when we have to use setters. For example, if
one library provides us with such API. But don’t use them in your
projects. It’s not worth it. Thank you for reading!
Resources
Reflection API
Builder-pattern
Lombok
277 claps
WRIT T EN BY
Linux user tries My Top 20 VS Code Tricky Java Interview 5 T hings T hat Are Hard
Windows, in 2020 Extensions Questions To Grasp When You
Dominik Tarnowski in Level Up Neo Hao Jun in Level Up Manusha Chethiyawardhana in Start Programming
Coding Coding Level Up Coding Daan in Level Up Coding
5 Lessons I’ve Learned 4 JavaScript Tricks You SOLID Principles — 3 Habits T hat Will Help
on How to Structure Should Know Simpli ed with You Become a Top
Code Anupam Chugh in Level Up Illustrations Developer
Daan in Level Up Coding Coding Animesh Gaitonde in Level Up Manish Jain in Level Up Coding
Coding