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:
Unit.java
public class Unit { protected int health; public Unit(int hp) { // Prevents health for being set to 0 or less. if(hp <= 0) throw new IllegalArgumentException("Health must be more than 0."); health = hp; } public void setHealth(int hp) { // Prevents health for being set to 0 or less. // Repeat of the code in the constructor. 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:
Unit.java
public class Unit { protected int health; public Unit(int hp) {// Prevents health for being set to 0 or less. if(hp <= 0) throw new IllegalArgumentException("Health must be more than 0."); health = hp;setHealth(hp); } public void setHealth(int hp) { // Prevents health for being set to 0 or less. // Repeat of the code in the constructor. 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.