When a getter returns a property, such as returning a List
of other related objects, should that list and it's objects be immutable to prevent code outside of the class, changing the state of those objects, without the main parent object knowing?
For example if a Contact
object, has a getDetails
getter, which returns a List
of ContactDetails
objects, then any code calling that getter:
- can remove
ContactDetail
objects from that list without the Contact
object knowing of it.
- can change each
ContactDetail
object without the Contact
object knowing of it.
So what should we do here? Should we just trust the calling code and return easily mutable objects, or go the hard way and make a immutable class for each mutable class?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…