Java 25 introduces Flexible Constructor Bodies, which allow statements to be placed before an explicit constructor invocation - the super(…) or this(…) call. This enables developers to perform validation logic in the prologue, ensuring that the system avoids the overhead of initializing a superclass or allocating resources for an invalid object.
Move all the validation logic for parameters in a constructor before super(…) or this(…) call.
public class Coffee {
int water;
int milk;
public Coffee(int water, int milk) {
this.water = water;
this.milk = milk;
}
}
public class SmallCoffee extends Coffee {
private static final int MAX_CUP_VOLUME = 100;
int topping;
public SmallCoffee(int water, int milk, String topping) {
super(water, milk); // Noncompliant: constructing before validation
int totalVolume = water + milk;
if (totalVolume > MAX_CUP_VOLUME) {
throw new IllegalArgumentException();
}
this.topping = topping;
}
}
public class SmallCoffee extends Coffee {
private static final int MAX_CUP_VOLUME = 100;
int topping;
public SmallCoffee(int water, int milk, String topping) {
int totalVolume = water + milk;
if (totalVolume > MAX_CUP_VOLUME) {
throw new IllegalArgumentException();
}
super(water, milk); // Compliant: validation before construction
this.topping = topping;
}
}