As with most duplicated code, you can factor it out into a method.
public class Car {
private int fuel;
public Car(int fuel) {
checkFuel(fuel);
this.fuel = fuel;
}
public void setFuel(int fuel) {
checkFuel(fuel);
this.fuel = fuel;
}
private static void checkFuel(int fuel) {
if (fuel < 0) {
throw new IllegalArgumentException("'fuel' argument can't be negative");
}
}
Why not call setFuel
from the constructor? Because calling methods of your instance from within the constructor before you've completely initialized can be a source of errors. Consider: A subclass overrides setFuel
and adds side-effects. More about that in this question and its answers.
Here's another way, also encapsulating it in a method:
public class Car {
private int fuel;
public Car(int fuel) {
this.privateSetFuel(fuel);
}
public void setFuel(int fuel) {
this.privateSetFuel(fuel);
}
private void privateSetFuel(int fuel) {
if (fuel < 0) {
throw new IllegalArgumentException("'fuel' argument can't be negative");
}
this.fuel = fuel;
}
Side note: Notice I added the name of the argument to the exception message.