r/java • u/ZhekaKozlov • Jan 21 '23
JEP draft: No longer require super() and this() to appear first in a constructor
https://openjdk.org/jeps/830078615
u/cyancrisata Jan 21 '23
Yes!! Finally! No more using static private methods to calculate constructor parameters for this/super!
12
u/jevring Jan 21 '23
It isn't often that I need something like this, but I occasionally do, and it would be really nice. I imagine it would come with some restrictions, though, regarding what you can and can't access before the call.
8
u/DasBrain Jan 21 '23
Yes, before the
super()/this()call,thisis not considered to be "definitely assigned", so you can only usethisto set fields.You can't invoke instance methods on it, pass
thisto other methods...
14
u/msx Jan 21 '23
It would be nice. That kind of problem is kinda rare but when it happens is particularly irritating
3
u/Ignice Jan 22 '23
Does anyone know why the limitation was introduced in the first place? The draft indirectly hints it may be safety related.
2
u/cogman10 Jan 23 '23
if A extends B. B has a
protected final Foo foofield initialized in the constructor then ifAdepends on that field in its constructor what should happen?That's mainly the issue resolved.
4
u/sysKin Jan 24 '23 edited Jan 24 '23
That does not quite the answer the question: the JVM already forbids referencing the instance being constructed before this()/super(), and the JEP maintains that rule.
The question is, why code that does not reference
thiswas not allowed.So, for example,
super(Objects.requireNonNull(foo));is allowed, but
var foo2 = Objects.requireNonNull(foo); super(foo2);is not, even if they compile to (pretty much) the same thing.
Now, the JEP does say "the original JVM specification was more restrictive also" but does not go into details why.
3
u/Molossus-Spondee Jan 22 '23
IIRC the "correct" way to error out object construction is needlessly silly so this is good
2
u/lukaseder Jan 23 '23
That is so great. Can't wait to remove hundreds of otherwise useless auxiliary constructors and static methods that were implemented only as a workaround for this limitation.
2
1
u/manifoldjava Jan 22 '23
I wonder how many code generators/analyzers will be screwed by a change like this? I know I've written code that makes heavy assumptions about super() or this() as the first statement in a constructor.
1
-26
Jan 21 '23
If you have complex code in your constructor, you are doing something wrong, and your unit tests will look awful. You should use a builder
17
0
Jan 21 '23
[deleted]
65
u/marvk Jan 21 '23
Calculating a value to pass into the other constructor. It's not needed often, but when you do need it, it's a nice to have.
9
u/semioticmadness Jan 21 '23
You can use static functions to get that, no?
27
u/morhp Jan 21 '23
You can, but it's often not convenient, as you might need to pass multiple parameters to that method or the computation might result in two things that should be passed to different parameters of
super().Which means even if you create a record for the return value of that static method, you now need to call the method twice like this
public MyClass(Foo a, Bar b) { super(staticFun(a, b).resultOne(), staticFun(a, b).resultTwo()); ... }as you cant write a temp variable before the super call.
8
u/DasBrain Jan 21 '23 edited Jan 22 '23
Yes, fun starts here. While not an ideal solution, I'd add an additional constructor:
public MyClass(Foo a, Bar b) { this(a, b, staticFun(a, b)); } private MyClass(Foo a, Bar b, MyFunResult result) { super(result.resultOne(), result.resultTwo()); ... }This gets ugly quickly.
As a side note: Take a look how many private constructors in java.* takes aVoidargument - most of them because you can't add your own code before thesuper()call.1
u/genzkiwi Jan 22 '23
Think they meant a static factory?
2
u/morhp Jan 22 '23
Sure,.that's a possible workaround, but that has its own problems, like you can't create another subclass and then call the static factory instead of the super constructor. Or you might have some reflection-y code that relies on calling constructors.
15
u/wildjokers Jan 21 '23
If you read the JEP it has a “Motivation” section which outlines the use cases and reasoning.
There have definitely been times where I have wanted to massage some value before calling this() or super(). Not something I need a lot but would be handy to have for the times I need it.
20
u/hardwork179 Jan 21 '23
The order in which Java does things is subtly wrong and means that objects can be seen before all their final fields have been initialized. Other languages such as Swift have learnt from this mistake and require you to initialize all final fields (without leaking “this”) before calling the super constructor. Swift’s rules have other problems as they prevent some fields from being final that you might want to be.
4
Jan 21 '23 edited Jan 21 '23
A thousand times this. I find myself in the second described scenario more often than I’d like. Having to resort to other patterns is feasible, doesn’t mean it’s the most elegant.
1
u/cogman10 Jan 23 '23
It's a "pick your poison" problem.
The issue with allowing/forcing super and this to go later is now your base class fields might not be initialized. I believe that is the initial motivation for the restriction.
That said, it's not very often that I want my subclass to reference some field or function in the base class from the constructor.
0
u/john16384 Jan 21 '23
Well, before this JEP, work was done to add a new warning (this-escape), by the same author as this JEP.
I think the warning is useful.
The JEP not so much.
6
u/Worth_Trust_3825 Jan 21 '23
There is a discrepancy between bytecode, and java language when constructor calls happen. In the bytecode there is no such limitation, while java language specifies that it must be first statement in the constructor.
-14
27
Jan 21 '23
[removed] — view removed comment
13
u/mykeesg Jan 21 '23
I'd prefer static methods in this case, that can do these checks for me - like:
class Widget { final LocalDate date; public Widget (LocalDate ld) { date=ld; } public static Widget fromString(String datestr) throws DateTimeParseException { LocalDate ld = LocalDate.parse(datestr); return new Widget(ld); } }The
thisescape still seems like a problem if the variables / methods used in the child try to access anything that is initialized in the base class.8
u/brett_riverboat Jan 21 '23
And if it was 4 params you would've done
public static Widget fromStringAndIntAndIntAndBool ( String datestr, Integer foo, Integer bar, Boolean baz ) throws DateTimeParseExceptioninstead of a multi param constructor?
5
4
u/foreveratom Jan 21 '23
I am with you on this, It seems pointless, introduces more complexity than it removes and all those example are code that would not pass most reviews. There is nothing there that proper usage of static methods won't solve. Pointeless JEP and a waste of time.
19
u/Trant2433 Jan 21 '23
Disagree. The dream of OO programming was that you'd use constructors to instantiate objects. You'd use public methods to interact with them, and everything else was a "black box."
Instead - and this became prominent during the "enterprise" days - most Java libs became a huge tangle of static methods or factories, etc.
At that point, a lot of Java code just ends up like old school C, where it's just static utility methods all the way down. And at that point, why even bother with all the OO language features - they just get in the way.
1
u/foreveratom Jan 21 '23
You don't have to make everything static. In the case we're talking about, it can well be a private method in the enclosing class, hence keeping it a "black box" while solving the non-existing problem this JEP is trying to solve.
There is nothing that prevents using constructors with any sort of parameter. A good example is Number classes; their string based constructors use static methods.
eg:
public class Long { public Long(long value) { ... } public Long(String value) { this(Long.parseLong(value)); } public static long parseLong(String s) { ... } }1
u/dablya Jan 21 '23
I can imagine a large number of "'this' escape" problems that will not be picked up by most reviews.
1
u/DasBrain Jan 21 '23
Static analysis tools can help - if you run it over the parent class.
Basically, don't call methods in your constructor that are not either final or private.
Netbeans seems to do this analysis by default.
23
Jan 21 '23
[removed] — view removed comment
1
u/ItsAllegorical Jan 22 '23
I love using fluid builders. Writing them is a lot less fun, though. Particularly when you want to do a fluid guided builder. It’s so much more work and it’s so easy to do without it that it never makes sense outside of Lombok or @Immutables which wrote it all for you. But it’s nice to have.
108
u/ibevol Jan 21 '23
This would be really nice. Sometimes I need to calculate a value passed in from a constructor, and while it's possible to chain functions, it's far more readable to use some variables in between, which I prefer over having to write comments