Why continue to use getters with immutable objects?

后端 未结 8 1512
感情败类
感情败类 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:58

    It's a OOP practice to encapsulate fields and then expose it only through getters method. If you expose field directly this means that you will have to make it public. Making fields public is not good idea as it exposes inner state of object.

    So making your field/data members public is not a good practice and it violates Encapsulation principle of OOP. Also i would say it's not specific to Immutable objects; this is true for non-immutable objects as well.

    Edit As pointed by @Thilo ; Another reason : Maybe you don't need to expose how a field is stored.

    thanks @Thilo.

提交回复
热议问题