In the example below, I have a Person class and class B that holds a reference to a Person.
Person has a public foo1 method that can alter its state (it's a mutable object).
Suppose clients of class B want to know the salary, name and email of person object. Should I rewrite the getters from Person class in class B (without providing a getPerson method)? Or maybe getPerson is enough, as people will be able to call getSalary, getEmail and getName on it?
Knowing that Person is mutable, we should ask if we want clients of B to modify that person by calling foo1. We may decide to rewrite Person' getters in B or return a clone of that Person object, so that Person in class B won't be modified.
What about a simpler example, if Person was immutable (there would be no foo1 method in this case)? In B, should I have getPerson (which returns a clone, just in case Person will become mutable at a later point), or rewrite all Person's getters?
class Person{
private String name;
private int salary;
private String email;
//other private fields
public void foo1(){
//modify some fields here
}
public int getSalary(){
return salary;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
}
class B{
private Person person;
public Person getPerson(){
return person;
}
}