Why continue to use getters with immutable objects?

后端 未结 8 1558
感情败类
感情败类 2021-01-07 23:22

Using immutable objects has become more and more common, even when the program at hand is never meant to be ran in parallel. And yet we still use getters, which require 3 li

8条回答
  •  [愿得一人]
    2021-01-07 23:44

    Joshua Bloch, in Effective Java (2nd Edition) "Item 14: In public classes, use accessor methods, not public fields," has the following to say about exposing immutable fields:

    While it’s never a good idea for a public class to expose fields directly, it is less harmful if the fields are immutable. You can’t change the representation of such a class without changing its API, and you can’t take auxiliary actions when a field is read, but you can enforce invariants.

    and summarizes the chapter with:

    In summary, public classes should never expose mutable fields. It is less harmful, though still questionable, for public classes to expose immutable fields.

提交回复
热议问题