In Java, coders are discouraged from calling setter functions in class constructors. Even though doing so can sometimes reduce the amount of repeated code.
Consider the following class:
public class Unit {
protected int health;
public Unit(int hp) {
if(hp <= 0)
throw new IllegalArgumentException("Health must be more than 0.");
health = hp;
}
public void setHealth(int hp) {
if(hp <= 0)
throw new IllegalArgumentException("Health must be more than 0.");
health = hp;
}
}
Instead of doing the check twice across 2 functions to ensure the incoming hp
value is correct, it might occur to some coders that we can call the setter within the constructor instead, to reduce the amount of repeated code:
public class Unit {
protected int health;
public Unit(int hp) {
if(hp <= 0)
throw new IllegalArgumentException("Health must be more than 0.");
health = hp;
setHealth(hp);
}
public void setHealth(int hp) {
if(hp <= 0)
throw new IllegalArgumentException("Health must be more than 0.");
health = hp;
}
}
This, however, is discouraged, because (according to textbooks) setters like setHealth()
can be overriden by child classes, creating unexpected or buggy behaviour in these child classes.
Continue reading →