Does Project Lombok contradict the data encapsulation of using a getter and setter?

Viewed 490

Declaring a private variable and accessing it through the public getter/setter method (the encapsulation principle in Java) can be utilised to add custom validations in the setter method.

For Eg: If I put a negative number validation in my setBalance() setter method in Bank Class, I can restrict negative amount deposition in the Bank. That means accidental changes in the fields can be restricted. So if I am using lombok, obviously I don't need to define getter/setter method. What can I possibly do to incorporate the above mentioned validation.
Wouldn't it restrict leveraging the data encapsulation property of Java?

3 Answers

Yes. You are right. So you should use it carefully depending on the context.

If an object is a rich domain object , simply use @Setter to add public setters for all its fields is probably a bad idea as the client can easily set any fields to any values without invoking the proper method which encapsulate all the business logic that should be done. So in the end , the object 's state may be incorrect.

But if the object is just serve as a data container which does not have any business logic (e.g DTO), using @Setter/ @Getter can save you some times and make the codes has less noise.

It doesn't break data encapsulation, it makes it more convenient: simple getters and setters are just noise.

If your code requires something other than a simple get or set then obviously generating them automatically doesn't make sense--but that's an orthogonal issue: you wouldn't be able to do it manually either.

You're conflating restricted access with business logic.

In any case: you might be able to use an AOP system to put guard clauses around automatically-generated functions, but you'd need to enforce the order the processors run in. IMO that's a recipe for confusion and an additional cognitive overhead: keep business logic either explicit, or layered on top of explicit code.

By using @Getter, @Setter, @Data or @Value Lombok is auto-generating a public accessor to your field, if you don't need to expose fields you can use AccessLevel.NONE on @Getter, @Setter.
Encapsulation can be respected using lombok.

I would suggest you to consider data structures and actions that can be performed on them (like validations) as separate concerns. In this way you will be able to modify data and validations separately. To achieve that you can use some framework like spring or aspectj.

If you feel that approach is overkill for your application, you can resort to immutable data structures (@Value) with private constructors and static methods used to create the instance. Those methods will perform the necessary validations.

Another method to add validation on your class could be by using annotations on the getters using hibernate validation.

Related