1

In my current java project we are considering to use Lombok instead of public fields. My colleagues think, that this will bring better encapsulation.

In contrary to Why use getters and setters/accessors? , in which the benefits of hand written getters and setters are discussed, I'm challanging the fact of using auto-generated, hard-to-customize getters and setters.

Is there any benefit of using this code:

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class MyBean {

    private String firstName;
    private String lastName;

}

Instead of this code? (Which is easier to understand and shorter and has less dependencies?)

public class MyBean {

    public String firstName;
    public String lastName;

}
slartidan
  • 20,403
  • 15
  • 83
  • 131
  • 3
    This is essentially a duplicate of getters/setters vs. public fields. Lombok is just a helper library in between. – Kayaman Mar 29 '18 at 06:12
  • 3
    and just because you use lombok @Setters doesn't mean you can't implement your own if you need them to perform some validation or something of the kind – Stultuske Mar 29 '18 at 06:18
  • @Stultuske You have a point with that... – slartidan Mar 29 '18 at 06:19
  • The "hard to customize getters and setters" part is your own imagination. This is a duplicate, except you don't have the argument of "but it's so cumbersome to write those getters", not that you really have that with IDE generation either, but now you can say the classes look prettier too. – Kayaman Mar 29 '18 at 06:20
  • 1
    Your premise "auto-generated, hard-to-customize" is wrong. Using Lombok, you can generate all the "standard" getters and setters with `@Getter` and `@Setter`, but you can still override any particular getters and setters that require non-standard behaviour, e.g. checks. Thus, IMHO you get the best of both worlds: Clean code, meaningfull getters/setters where you need them, and default getters/setters for everything else so you don't have to adapt client code when it turns out that you need a getter/setter later on. – tobias_k Mar 30 '18 at 21:19
  • When this is a "real" bean, imagine you have public fields, and want to add a proper `PropertyChangeSupport` later. Then you're doomed (or rather, your clients are - you can just change the code, no problem there...) – Marco13 Mar 30 '18 at 22:26

0 Answers0