A flexible constructor body is a constructor that allows the use of instructions before the super base constructor calls. In the past, Java did not allow the use of any instructions before super, so developers needed to use some tricky workarounds to make this possible, such as encapsulating the logic in a method that performs tasks like validations. After that, the parameter is returned. This is inelegant and not a natural way to make this happen.
class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
class Accountant extends Person {
public Accountant(String name) {
super(parameterNameLogic(name)); // This is tricky because you are not able to use any code before super.
}
private static String parameterNameLogic(String name) { // This kind of method will cause additional stack frames in any exceptions that occur, and the method should be static.
if (name == null || name.length() > 30) { // Simple logic executed in a separate method; imagine if the method had more than one parameter, would we need to create more than one method?
throw new IllegalArgumentException("Invalid name");
}
return name;
}
}
In Java 24, we are now able to use statements above the super base constructor call, which allows us to avoid the use of these parameterLogic methods.
class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
class Accountant extends Person {
public Accountant(String name) {
if (name == null || name.length() > 30) { // Simple logic and code
throw new IllegalArgumentException("Invalid name"); // The exception occurs in the right place, and even the stack traces will generate the right stack trace.
}
super(name); // Name will be assigned without any tricky method.
}
}
We need to look at the above carefully, because it is not just about being able to have code before super; it is about creating the possibility of having two flows for initialization data. Now we have a pre-super and post-super constructor call. This means that all the calls before super are made when the object is in a larval state (not completely initialized), and the post-super constructor calls are executed after the object’s larval state is complete.
In short (why?), we now have the power to modify the complete flow of object construction. This was more or less restricted in previous Java versions, and should be handled with care.
No comments:
Post a Comment