Why continue to use getters with immutable objects?

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

    You can have public final fields (to imitate some kind of immutability) but it doesn't mean that referenced objects can't change their state. We still need defensive copy in some cases.

     public class Temp {
        public final List list;
    
        public Temp() {
            this.list = new ArrayList();
            this.list.add(42);
        }
    
       public static void foo() {
          Temp temp = new Temp();
          temp.list = null; // not valid
          temp.list.clear(); //perferctly fine, reference didn't change. 
        }
     }
    

提交回复
热议问题