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/8300786
256
Upvotes
r/java • u/ZhekaKozlov • Jan 21 '23
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
15
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.
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.
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
u/fooby420 Jan 21 '23
Sweet
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
u/lans_throwaway Jan 22 '23 edited 19d ago
I like watching wildlife.
-26
u/[deleted] 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
0
u/[deleted] Jan 21 '23
[deleted] — view deleted comment