Why make defensive copies in getters inside immutable classes?

前端 未结 7 649
余生分开走
余生分开走 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:55

    I slightly modified Tomasz Nurkiewicz answer, to demonstrate why making dateOfBirth final does not defend it from being changed by a client class:

        public class Immutable {
    
            private final String name;
            private final Date dateOfBirth;
    
            public Immutable(String name, Date dateOfBirth) {
                this.name = name;
                this.dateOfBirth = dateOfBirth;
            }
    
            public String getName() { return name;  }
    
            public Date getDateOfBirth() { return dateOfBirth;  }
    
            public static void main(String[] args) {
    
                //create an object
                Immutable imm = new Immutable("John", new Date());
    
                System.out.println(imm.getName() + " " + imm.getDateOfBirth());
    
                //try and modify object's intenal
                String name = imm.getName(); //safe because Integer is immutable
                name = "George";             //has no effect on imm
    
                Date dateOfBirth = imm.getDateOfBirth();
                dateOfBirth.setTime(0);  //we just modified `imm` object
    
                System.out.println(imm.getName() + " " + imm.getDateOfBirth());
            }
        }
    
        **Output:** 
        John Wed Jan 13 11:23:49 IST 2016
        John Thu Jan 01 02:00:00 IST 1970
    

提交回复
热议问题