16 ms·
JEP draft: No longer require super() and this() to appear first in a constructor
- RedShift1 4y agoThis would be awesome. I tend to do a lot of work in the constructor, this would definitely help clean up different kinds of constructors.
- lbriner 4y agoBut that in itself is an anti-pattern isn't it? A Constructor should be the minimal amount of work to create a valid set of object data. Other work should not be hidden in the Constructor otherwise it fails the principle of surprising functionality. As an example of where I have seen this used, your File object could open the file and truncate it in the constructor but this is non-obvious, it would be better to have another method like Init() or perhaps a factory method where calling e.g. File.OpenForWriting() is obvious. I know not everyone has the same requirements but I can't remember a single time where this restriction was a problem for me in C#, the feature sounds like it will encourage worse behaviour.
- RedShift1 4y agoThe work done in the constructor is to ensure you have a working object, so that calls to any of its methods can never end with a null pointer exception or any other exception that can reasonably be prevented/thrown in the constructor. Opening a file and truncating it sounds totally unexpected and I never do such things like touching the filesystem or running queries in a constructor.
- TedDoesntTalk 4y ago[flagged]
- mabbo 4y agoThe linked JEP provides a very well written set of reasons.
- zmmmmm 4y agoit's really annoying when you want to subclass something but do a transformation, logic or validation on the arguments that are to be passed through to the super class, because you can't put any code prior to the this() or super() call to do that. In practice it means people stuff all kinds of awkward expressions inside the this() or super() which get very ugly, or are forced to move these out into ancilliary methods which has other drawbacks.
- RedShift1 4y agoWhy not?
- tadfisher 4y agoYes, and it provides the same safety guarantees as requiring this() or super() to be the first call.
- Vanit 4y agoI haven't written java in a long time, but I remember this requirement being a thorn in the side of many of my subclasses.
- pulse7 4y agoWhy are so many people writing something like "I haven't written java in a long time, but..." on Java related posts on HN? Is this trendy or what?
- matsemann 4y agoYaeh, you end up having to write crazy one-liners to initialize some other object to pass to your super class.
- jayd16 4y agoIt's easier if you just use a factory pattern. That way your constructors stay as simple allocation and the logic to build instances can break out into full methods. Exceptions can stay out of your constructors and it just makes things easier to work with over all.
- rvcdbn 4y agoI think this Java oddity is the main practical motivation for a lot of factory methods. I wonder if we will see fewer after this change.
- jayd16 4y agoIt's really not. Use before full construction is a pitfall in a lot of languages.
- throwaway2037 4y ago"this Java oddity": Doesn't C++ have the same restriction?
- 4y ago
- deleted 4y ago[deleted]
- mabbo 4y agoI enjoy that the JEP process allows for nice little small things like this. This isn't "we should have lambdas" or "Let's rebuild the type system to allow List<int>". But it's still a very common annoyance, and it can be fixed.
- revetkn 4y agoTotally agree, and I also love that so much thought and consideration goes into how the platform gets improved over time. Doing it "right" means taking so many things into account -- many of which are subtle -- and picking the right tradeoffs. Hats off to the people quietly doing the deep work which makes everyone's lives better.
- rvcdbn 4y agoI wish the JEP showed which company was behind it. It has an author but it’s just a username not a full name and doesn’t indicate the company they work for.
- teraflop 4y agoWhy must a company be "behind" this change? 2 minutes of sleuthing seems to suggest that the author of the JEP is a freelance developer who contributes to OpenJDK independently.
- __float 4y agoWhy does there need to be a company affiliation at all? Do you feel this JEP is motivated by a company's interests?
- carimura 4y agoFor motivation and to see who's involved there are a few other places you can go such as amber-dev [1] and his PR's [2]. [1] https://mail.openjdk.org/pipermail/amber-dev/2023-January/thread.html https://mail.openjdk.org/pipermail/amber-dev/2023-January/th... [2] https://github.com/openjdk/jdk/pulls?q=is%3Apr+is%3Aopen+archiecobbs+ https://github.com/openjdk/jdk/pulls?q=is%3Apr+is%3Aopen+arc...
- 4y ago
- pron 4y agoThis JEP draft touches on an interesting tension in language design (and perhaps many other kinds of design) between a desire for rules that aren't unnecessarily restrictive and a desire for rules that are easy to communicate to the user. I.e. there's value in accepting more correct programs but there's also value in easily communicating why a program is rejected, and sometimes there can be tension between the two.
- paddy_m 4y agoCan you expand on this. does this change make it easy to communicate why a program was rejected?
- lmm 4y agoThis change means that some programs won't be rejected when previously they would be.
- rustyminnow 4y agoI think this change would make it harder to explain why a program was rejected, even though it would allow a programmer more flexibility. It's easier to just say "this() must ALWAYS be called first in constructor" and everybody understands... than to try and say "you can call this() after other statements, but not in a try block and not if those statements reference the instance under construction" which will certainly allow you to do more interesting things, but also be more confusing.
- rcme 4y agoGiven that the entire constructor call stack is known at compile time, it should be possible to use static analysis to detect if fields are used before initialization. Swift does this, I believe.
- layer8 4y agoYou can call methods from constructors, including methods overridden in unknown subclasses, or methods in superclasses whose implementation may change later, which complicates things. You can also pass this to foreign code from a constructor, which in turn may call arbitrary methods and/or access fields on the instance.
- georgelyon 4y agoThe way Swift handles this is that you can’t do anything that involves the self pointer before calling super.
- rcme 4y agoSure, the super class can call unknown methods in subclasses in its constructor, but the subclass has knowledge of the super class, so the subclass should fail to compile if it overrides a super class method that access instance variables before they’re initialized.
- layer8 4y agoSuperclass implementations can change later (you can recompile the superclass without having to recompile the subclass), you can’t assume their current implementation will stay the same.
- rcme 4y agoYou could also remove a method from the superclass entirely in such a situation. This would cause an invocation of the removed method to fail if the subclass depended on it. In general you need to recompile the subclass if the superclass changes.
- oweiler 4y agoOne of the many reasons to prefer static factories to constructors.
- mcculley 4y agoHow does that help the implementor of a subclass?
- cratermoon 4y agoOne of the many reasons to prefer composition over inheritance.
- layer8 4y agoAlternatively (in particular for subclassing), it can always be worked around with an intermediate object. For example: Constructor(A a, B b) { … } Constructor(C c, D d) { // A and B can be derived from C and D, and // we want to forward to the (A, B) constructor, // so we use an intermediate object to do the // conversion and provide A and B: this(new Intermediate(c, d)); } private Constructor(Intermediate x) { this(x.a, x.b); } Of course, with the JEP this will become much simpler.
- vips7L 4y agoI personally don't like static factories that much. They have their place, but half the JDK is now `.of` or `.from` or `.newInstance` or `.get`. I'd really like to be able to define a constructor on sealed interfaces: sealed interface Path permits WindowsPath, UnixPath { public Path(String p) { if (isWindows()) { return new WindowsPath(p); } return new UnixPath(p); } } That way user code to construct an object is always the same: var p = new Path(s); Instead of: var p = Paths.get(s);
- layer8 4y agoAn important benefit of static constructor methods is that they allow you to switch class implementations between a final class and an abstract class with private subclasses, without breaking compatibility. With regular constructors, you are prevented from switching to subclass implementations later. Static constructor methods thus decouple client code more from implementation decisions. Another benefit is being able to name different constructors differently. If I were to design a new OO language, I would make it so that constructors always work like that in the first place, from the caller perspective.
- londons_explore 4y agoUndocumented downside: Java becomes a slightly harder language to learn, because now there is one more thing to explain to a beginner: "Where exactly should super() be put in the constructor? At the start, in the middle, or at the end? What are the benefits and downsides of each, and when does it matter? Is there a convention?"
- mcculley 4y agoAs someone who has been using Java since 1.0, I welcome these little improvements but agree that the language is now a mess for a beginner. All of the little rules and corners make sense to someone who learned them gradually. To a beginner, they must seem nonsensical and intimidating.
- londons_explore 4y agoThis is the evolution of nearly any language... It begins simple and easy, and over time more and more features and syntax are added, and it becomes very hard to learn from scratch, which in turn means beginners end up using other simpler languages. I think python is a classic example of this - python 2 was pretty simple. Python 3 just gets more and more complex.
- cratermoon 4y agoThe language formerly known as Perl 6 has entered the chat.
- amoe_ 4y agoYep. Pre-generics, Java was considered a good teaching language because of its simplicity and the ability to hold the entire language in your head. I think it's much more difficult to make that argument now. The same for Python. Moreover, while Python 3's unicode/byte string separation was a crucial step, IMV other features from Python 3 haven't made a big impact on how useful the language is.
- nayuki 4y ago
- garblegarble 4y agoI really wish useful quality of life things like "?." would get added instead of this kind of stuff that really doesn't improve life all that much for most development
- simplotek 4y ago> (...) instead of this kind of stuff that really doesn't improve life all that much for most development There are comments in this very discussion praising this change due to how this stuff really improves their life as a developer. Anyway, can you pass the link to your JEP with a proposal for "?." ?
- jeroenhd 4y agoThe Elvis operator was proposed for Java 7 and hasn't made it back in since. I'm sure you can put in the effort to write a proposal again but I doubt it'd stay up for long. I'm not going to put in the effort of fighting a committee that has probably already made up its mind when I can write Kotlin or C# instead. Maybe Manifold will add the operator somehow. That seems to be the place modern language features that the Java comities don't like end up.
- deleted 4y ago[deleted]
- jeroenhd 4y agoYou and me both. Java programmers don't seem to want it for some reason. However, Java has instead received `Optional` (in the shape of `Optional.ofNullable(variable).map(Clazz::getProperty).map(Clazz2::getProperty).orElseGet( () -> 42 );` rather than `variable?.getProperty()?.getProperty() ?: 42`). I don't know what the JCP EC was thinking going for this approach rather than the much more readable, modern approach, but I can't be too surprised about a language designed by committee refusing such improvements.
- vbezhenar 4y agoThis is useless operator. I can't imagine many places where it could be useful.
- charcircuit 4y agoIt's always bothered me how public A(String s) { this(s.isEmpty()); } is allowed but public A(String s) { boolean helpfulName = s.isEmpty(); this(helpfulName); } isn't
- layer8 4y agoYes, though in that case you can use public A(String s) { this(helpfulName(s)); } with a static method.
- kaidon 4y agobingo - exactly the way to do it in java
- dehrmann 4y agoThere's something to be said for making sure the parent constructor is the first call made. It means any method you call in the current constructor will work correctly or obviously be your fault, not the parent class's. Yes, in your particular case, the compiler could figure out that you're not using "this," but you can only make a compiler so clever.
- cdcarter 4y agoIt's not too hard to make the compiler (or more specifically, the language) know about this. The solution isn't even that clever, you just don't put "this" into scope until the super() call.
- klntsky 4y agoIt's not that simple, because you can't find where super is called in the general case. Consider: `var foo = { bar: super }; foo['b' + 'a' + 'r']();` - you need to evaluate it in order to define scoping. But JS has lexical scoping as a design choice...
- 4y ago
- grishka 4y agoOne more way to bypass this requirement is to add a private static method that returns something you want to pass to super()/this(). And on the subject of Java restrictions that get in the way: if you use a local variable in an anonymous inner class or lambda, it needs to be final. This presents a problem for when you call a method that runs your lambda at some point before it returns and you want to modify some variables from there. The ugly workaround is to declare a final single-element array. It satisfies "needs to be final", but its single element can still be assigned to from anywhere since "final" only applies to the object reference to the array itself.
- deleted 4y ago[deleted]
- layer8 4y ago> One more way to bypass this requirement is to add a private static method This doesn’t work if it requires multiple arguments to be generated with common code, unless you’re okay with effectively running that common code twice, which in turn is problematic when it has side-effects (like logging). See https://news.ycombinator.com/item?id=34482908 https://news.ycombinator.com/item?id=34482908 for an alternative way of solving this.
- vbezhenar 4y agoYes, inability to modify variables from the lambda is extremely frustrating and makes exactly zero sense as compiler can always convert variable to a wrapper object on the heap. I guess this is another improvement for the future. Too bad that Java's future is Lisp's infancy.
- fidgewidge 4y agoBtw Kotlin solves that. You can write to non final variables inside lambdas.
- vbezhenar 4y agoYep, Kotlin solves almost all pain points with Java and presents a good show-case which Java language developers should have followed IMO. Another examples of Java pain points solved in Kotlin which I could remember: top-level functions (which are actually bundled in some "standard" class name. Pretty much syntax sugar but very nice. Auto cast. Like you check variable with instanceof and after this check it's automatically casted to the target type. Java has some weird syntax for this but I don't see why this was necessary at all. More default imports. Why should I qualify java.util. it's pretty much standard. I'm not asking for every java.x package to be auto-imported, but commonly used packages should be. Class properties instead of getter/setter ceremony. Records are alternative approach but I don't find it useful yet. Nullability. Of course that's a hard question and adding nullability to existing type system looks like gargantuan task. What could be done is introduce some java.xxx annotation, let module projects to be not-null by default (so you don't need to create package-info.java in every package just to make it not-null) and make all nullability issues to be warnings from javac. Basically it's already exists but not standard and implementation quality varies. Reified generics. Basically it's a hidden Class<T> clazz argument passed automatically to the function. This is brilliant solution to type erasure problem and it should really have been adopted. I'd vote for all those features to be implemented in Java similarly to their Kotlin implementations.
- wruza 4y agoFor non-java guys like me: this() is used to call one constructor from the other of the same class.
- deleted 4y ago[deleted]
- layer8 4y agoRelatedly, I don’t know if the following has already been fixed in more recent Java versions, but it should: final Foo foo; try { foo = bar(baz); } catch (SomeException ex) { foo = SOME_DEFAULT; } For some reason, the assignment in the catch clause is seen as a reassignment ("variable foo might already have been assigned"). As a workaround, one can factor it out into a separate method and have “return” there instead of “foo =“. This is particularly inconvenient in constructors when you want to assign to a final field.
- deleted 4y ago[deleted]
- SeanLuke 4y ago??? I just tried this on Java 8 and it compiles fine.
- layer8 4y agoSorry, I had slightly misremembered, please see my corrected comment above. The second assignment is seen as a reassignment when the variable or field is final.
- kaashif 4y agoI'm having trouble constructing a specific example that doesn't work, can you provide a minimal example that fails to compile? This compiles fine in Java 11, for example: import java.io.IOException; class Test { int g() throws IOException { throw new RuntimeException("aaa"); } int f() throws IOException { int x; try { x = g(); } catch (IOException e) { x = 3; } return x; } } So the compiler definitely believes that x is initialized because we can return it. Not a Java expert so maybe there's some subtlety I'm missing.
- layer8 4y agoSorry, I had slightly misremembered, please see my corrected comment above. The second assignment is seen as a reassignment when the variable or field is final.
- tubs 4y agoBest part about this is finally being able to avoid the dance of 'oh no the super called an overridden method and kinda-sorta-broke but not fatally, whoopsies'.
- layer8 4y agoYou still have the problem that the super class might not be fully initialized when the overridden method is executed. Calling overridable methods from a constructor is just a bad idea in general.
- deleted 4y ago[deleted]
- tadfisher 4y agoThere's been discussion about making this illegal, or at least emitting a warning. The term—or underlying problem—is "leaking this() in constructors".
- layer8 4y agoTools like FindBugs/SpotBugs and some IDEs have been generating such warnings for many years, this basically exists. What is difficult, however, is if a final method of the same class is called (which should be fine), but that final method in turn calls a non-final method (directly or indirectly). Or if the final method is in a superclass, whose implementation could later change (or could be made non-final). Or if you store a lambda reference to a non-final method in a field (there are valid use cases for that), then call a final method which directly or indirectly invokes that lambda. Unless you want to disallow any non-static method calls from constructors, the necessary language rules would be nontrivial. Making it illegal is difficult, because there is a lot of code relying on this, and there are valid use cases for passing this to foreign code from the constructor, foreign code which might of course invoke anything on the instance.
- usrusr 4y ago
- GlitchMr 4y agoThis particular restriction is mostly arbitrary anyway because `this` and `super` accept arbitrary expressions (including static method calls), so in most cases it's possible to do this, just with much worse syntax. Technically, this does introduce new functionality when extending a class, specifically it's possible to choose a constructor to overload depending on arguments, but in most cases there is usually one constructor that all other constructors use.
- taeric 4y agoIsn't it already possible to choose which constructor to overload?
- sakesun 4y agoThis is another thing make me realized that Delphi was right and Java was wrong back then. (explicit "override" is another thing)
- deleted 4y ago[deleted]
- rtpg 4y agoSeeing this does make me appreciate the "no such thing as a constructor" approach of Rust. Rust, of course, has a totally different object model. OOP classes are really a bit of a triumph of engineering, because they offer a lot of nice ways to build out various complex systems (would rather build out GUIs in a Java-based object model than in a Rust-basd one). And the fact that moving the model "forward" in expressivity is so subtle and starts introducing a lot of asterisks is probably proof that it's some local maximum
- deleted 4y ago[deleted]
- Communitivity 4y agoIt was wrong.
- tsimionescu 4y ago> Another way to write the constructor, that works in current Java, might be to use the Streams API to make sure we are coding to the explicit and implicit design contracts: public FilteredSet(Predicate<? super E> filter, Collection<? extends E> elems) { super(checkElems(elems).stream() .filter(filter) .collect(Collectors.toList()); this.filter = filter; } I think you misunderstood the problem. Assuming you leave the add() method implemented exactly as in the JEP, this will still fail with the same NullPointerException, since super() will still call FilteredSet.add() before this.filter is provided. The only way to avoid it without this JEP is to do something like this: public FilteredSet(Predicate<? super E> filter, Collection<? extends E> elems) { super(elems.size()); //initialize super as an empty HashSet, but with the proper capacity this.filter = filter; this.addAll(elems); //this will call this.add(), but this.filter will now be set } Your description of the contract/purpose of HashSet.add() is also just wrong. The clear intention of the Java standard library designers is that any element added to the set, either by the constructor or later, is added using HashSet.add() - they are explicitly calling that method from the built-in HashSet constructor [0]. Also, it's an obvious design choice, while your proposal is just weird: why would you ever want to duplicate the implementation of adding elements between initialization and later modification? In general, you seem to be arguing for keeping the language more clunky. Why does `7 instanceof int` or `switch(number)` or avoiding a new method definition just to check a variable before calling a constructor hurt the identity of Java in any way? Sure, all of these things could be achieved in various ways before as well, but always in a more clunky way. Many of these JEPs are pure cleanup of bizarre idiosyncrasies of Java - the precise opposite of how C++ is evolving. [0] https://github.com/openjdk/shenandoah/blob/master/src/java.base/share/classes/java/util/HashSet.java https://github.com/openjdk/shenandoah/blob/master/src/java.b... - note that the doc is not very explicit, but it does say that `c` is "the collection whose elements are to be placed into this set", not something like "the collection whose elements will be used to initialize this set".
- specialist 4y agoMeh. What's next? Multiple inheritance?! I'm gonna need a better hypothetical than FilteredSet<E> to assess any benefits. Today, people use factory methods to achieve that result. Or just use a compound statement. Something like (pseudo-codimously): class FilteredSet <E> { public FilteredSet( Predicate<? super E> pred, Collection<? extends E> elems ) { super( elems.apply( pred )); this.pred = pred; } } My hunch (believe but cannot prove) is that Java's current constraint serves to encourage composition over inheritance. Which is The Correct Answer™. My limited anecdata wrt Java's "constructors must invoke super()/this() first" is this complaint arises when porting from C++ to Java. Because the original class hierarchy leans heavily on inheritance for organizing behaviors.
- chopin 4y agoI'd prefer lambdas transporting checked exceptions outside instead of forcing a try-catch inside. It's a pain in the ass for using libraries with checked exceptions.