Why make defensive copies in getters inside immutable classes?

前端 未结 7 611
余生分开走
余生分开走 2020-12-08 16:13

This question is about good programming practices and avoiding potential holes.
I read Joshua Bloch\'s Effective Java and here is what I wonder:
Why should I conside

相关标签:
7条回答
  • 2020-12-08 16:57

    1 If you don't make defensive copy, you can just let your object be given out, once given out, no more your class is immutable, caller is free to change the object.

    public class Immutable {
       private List<Object> something;
    
       public List<Object> getSomething(){
          return something; // everything goes for a toss, once caller has this, it can be changed
       }
    }
    

    2 If your field is just private and not final it means you can reinitialize the field, but if your field is final it will be initialized only once and not multiple times and you achieve immutability.

    0 讨论(0)
提交回复
热议问题