Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Don't Return References To Mutable Objects

Don't Return References To Mutable Objects

Java Programming Tricks

Don't return references to mutable objects:

 Especially for simple classes, it is common to supply accessor functions 
 for all data fields. 
 
 class Employee 
 
 { public Employee(String n, double s, Day 
 
 {   name = n; 
 
     salary = s; 
 
     hireDay = d"' 
 
 } 
 
 public String getName() 
 
 { return name; 
 
 } 
 
 public double getSalary() 
 
 { return salary; 
 
 } 
 
 public Day getDay() // WRONG! 
 
 { return hireDay; 
 
 }
 
 private String name; 
 
 private double salary; 
 
 private Day hireDay; 
 
 }
 
 Tip 
 
 Never return a reference to a mutable object. Consider the following. 
 
 Employee harry = new Employee("Harry Hacker", 35000, new Day(1996, 10, 1,l)); 
 
 Day d = harry.getDay(); 
 
 d.setYear(1997); // oops--now changed Harry's hire day 
 
 Remedy: Return a clone of the field: 
 
 public Day getDay() // OK 
 
 { return hireDay.clone (); 
 
 }
 

Sitemap : Partners