Could someone point me to documentation with design guidelines for my setters/getters?
I have legacy code that does some complex logic in the setters (and sometimes getters). This can confuse Hibernate, which call setters/getters freely, seemingly on the assumption that nothing but state underlies these methods.
Example (code below) The setter for the employee's hourly pay does not simply set a field-- it does some minimum-wage logic, which depends on the employee's age, and sets appropriately. This is quite OK for calling from a GUI, but when Hibernate calls it, then (1) we can assume that the value loaded from the DB needs no adjustment and (2) more importantly, the _age field, which is essential to the calculation, may not yet have been set by Hibernate.
Part of the issue here is the mandatory initialization order --and note that the non-default constructor may do initialization not done in the default constructor-- but I have the sense that there is a more fundamental issue here: That certain types of code should never be executed in the setters/getters.
Any general design guidelines?
Joshua
Code:
public class Employee{
public Employee(int age, int hourlyPay){
setAge(age);
setHourlyPay(hourlyPay);
}
public Employee(){
}
private int _age;
private double _hourlyPay;
public int getAge(){
return _age;
}
public void setAge(int age){
_age=age;
}
public double getHourlyPay(){
return _hourlyPay;
}
public void setHourlyPay(double hourlyPay){
double minimumPay = _age > 17 ? 5.0 : 4.0;//could also write getAge() instead of _age
_hourlyPay = Math.max(minimumPay,_hourlyPay);
}
}