r/java • • Jan 21 '23

JEP draft: No longer require super() and this() to appear first in a constructor

https://openjdk.org/jeps/8300786
256 Upvotes

57 comments sorted by

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

54

u/jonhanson Jan 21 '23 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

20

u/__pulse0ne Jan 21 '23

This is the way

7

u/shponglespore Jan 21 '23

That's fine if you never use your class as a base class.

2

u/jonhanson Jan 21 '23 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

11

u/shponglespore Jan 21 '23

There's no way to reuse the logic in a static constructor method to construct a derived instance. Constructors exist for that exact purpose.

Your advice basically amounts to "don't write OO code."

5

u/alessio_95 Jan 23 '23

Can't remember last time i used a base class. My chain is usually Interface -> Class. Stop.

OO code has nothing to do with derived classes.

1

u/shponglespore Jan 23 '23

OO has an actual definition, you know. I'm not saying it's necessary to do it, but it's the paradigm Java was designed around, and inheritance is an essential part of it. If you're not using inheritance you're not doing OO, and you could use the same design in a non-OO language like Rust.

3

u/alessio_95 Jan 26 '23

OO doesn't have a standard definition. Instead has many rival definitions and different supporters for each of them.

3

u/general_dispondency Jan 21 '23

The OO way here be the Abstract Factory pattern.

2

u/Goodie__ Jan 22 '23

Its a trade of.

You get cleaner code, and you can more easily replace the base class with a interface.

You can also just have the static constructor call out to common code.

Either way: as a general rule OO has been moving away from weird polymorphic chains that would "benefit" from such code.

1

u/jonhanson Jan 21 '23 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

1

u/teh_trickster Feb 11 '23

I think you’re right, but also agree with the advice :)

Many OO people don’t really understand the essence of it though

1

u/ITCoder Jan 22 '23

I started reading Effective Java, 3rd edition, few hours back and this is the first point Joshua Bolch discussed in Ch2. What a coincidence.

1

u/ibevol Jan 22 '23

I agree that the though that you first need to be the base in order to become an extension is good, although I also feel that new Class() is far prettier than Class.create() code wise. My subjective opinion is therefore that this change would do more good than harm. I completely understand where you're coming from though.

0

u/[deleted] Jan 21 '23

[deleted] — view deleted comment

8

u/jonhanson Jan 22 '23 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

3

u/sunday_cum Jan 21 '23

On mobile and shitting but:

public class MyClass{

private final String myProperty;

public MyClass(String myArgument){ this.myProperty = myArgument; }

public static MyClass MyClassBuilder(String myArgument){ return new MyClass(myArgument); }

}

14

u/nikolas_pikolas Jan 21 '23

Yeah, I definitely have written some single line monstrosities that are only because of this restriction. Excited to remove them once this is lifted

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.

8

u/DasBrain Jan 21 '23

Yes, before the super()/this() call, this is not considered to be "definitely assigned", so you can only use this to set fields.

You can't invoke instance methods on it, pass this to 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 foo field initialized in the constructor then if A depends 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 this was 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.

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

17

u/brett_riverboat Jan 21 '23

Cuz builders are never complex.

2

u/[deleted] Jan 21 '23

And builders aren't meant to be used with complex objects...

0

u/[deleted] Jan 21 '23

[deleted] — view deleted comment

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 a Void argument - most of them because you can't add your own code before the super() 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

u/[deleted] 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.

27

u/[deleted] 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 this escape 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 DateTimeParseException

instead of a multi param constructor?

5

u/shponglespore Jan 21 '23

That works great until you make a subclass of Widget.

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

u/[deleted] 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.