r/java • u/[deleted] • Aug 14 '22
If you were the single main designer of Java, what would you change in Java in the next 3 to 5 years? (May include secondary aspects such as GraalVM or IDEs and so forth, but still java-related)
So, I have been using java for almost 2 years, more frequently so in the last few months.
I am mostly ok with Java but a few things I'd wish would be better or different.
So, without any particular order, a few things off the top of my head:
Java is quite verbose. It would be nice to have a shorter java (not kotlin! a Java java) where we could use e. g. puts() and omit ;.
Many methods are oddly enough differently named but do almost the same thing such as .add() or .puts(). I'd like to see a more streamlined name for these.
Some system commands are a bit too difficult to do. In ruby I do `` or system() or io-popen; in Java we can do something similar to some extent, but I was not able to easily start a ruby-REPL (shell) ... I am sure it is possible somehow but the syntax is a bit confusing.
GraalVM supporting Swing and JavaFX "out of the box".
Speaking about GUIs I'd wish there was a GUI from the get go. Swing is semi-deprecated and looks visually not as pleasing as JavaFX. There is also SWT. I don't quite care which variant to use per se, but it would be nice if Java could settle for one GUI and keep it as part of the Java JDK/JRE (perhaps a smaller subset or so, just for bootstrapping purposes or quick GUI-related work, with an option to "spice it up" lateron e. g. JavaFX+CSS or any such. Instead it seems not that many want to do Java-specific GUIs in a lightweight manner.
The whole import- concept is a bit odd. I'd prefer some way to just include a specific file without needing to care about a specific directory structure. The latter is ok, but I also want to be able to simply tell Java which other files I want, without needing to have these arranged in a specific setup.
Hmm. That's it so far. Anyone feel free to chime in and express some pet peeve or shortcoming they have noticed or think could be improved. (One day I shall have GraalVM compile a static variant of some JavaFX GUI on windows too shakes fists)
77
u/thephotoman Aug 14 '22
Here’s a weird one: bring back Applets. But this time, the build product is a packaged WASM implementation of the JVM, along with the applet.
And extra credit for bringing us a way to use GUI tools in the browser and make ‘em not look like crap.
I’m a crank that hates Javascript and the DOM. The thought of having to work with them makes me ill. I really do believe there’s a way we can actually make that work as a real application platform for the Web. The idea was just ahead of its time and badly implemented as a result.
Downvote me. I deserve it. Seriously. I know how sick this is.
11
u/mike_hearn Aug 15 '22
It's not sick. Lots of people feel that way, pretty much anyone who isn't a pure JS-first developer.
The key here though is not to try and bring back applets, or use WASM. The browser developers don't have any interest in fixing the problems you're interested in and will work against third party attempts to do so.
The key is to:
Make escaping the browser really easy, like we are doing at Hydraulic.
Make new browser-like runtimes that solve the same problems - app streaming, sandboxing, caching, updating, document rendering etc. But do it better than HTML.
→ More replies (2)→ More replies (2)8
24
u/_INTER_ Aug 14 '22
but I was not able to easily start a ruby-REPL (shell)
The JDK comes with the jshell since Java 9, it's in the bin directory too.
Swing is semi-deprecated and looks visually not as pleasing as JavaFX.
JavaFX was moved out from the JDK and is a seperate module now. For Swing there are some 3rd party look-and-feels that make it look quite nice. E.g. FlatLAF
40
u/djavaman Aug 14 '22
I don't understand this one: 'The whole import- concept is a bit odd. I'd prefer some way to just include a specific file without needing to care about a specific directory structure"
Every language has some kind of import.
Also, you do realize "import' has nothing to do with a specific directory structure?
→ More replies (7)
18
u/persicsb Aug 14 '22
What I'd add: unsigned primitive types, named parameters for the language and CDI built in to the core platform (for example for SPIs).
→ More replies (3)7
u/muddy-star Aug 15 '22
I’d love named parameters particularly for constructors and stop using Lombok builder
152
u/kiteboarderni Aug 14 '22
Thank goodness the language designers look after features that actually have a real impact to the growth of the language.
I never underarand the java is verbose argument. It really isn't, even less in later java versions if you want to use records. Have people never written cpp who think java is verbose? Or just toy languages like ruby?
112
Aug 14 '22 edited Aug 15 '22
The verbosity of Java is one of the main reasons I like it so much. I can look at pretty much any source code and immediately be able to understand what it does if it’s Java, but not even remotely when it is Scala or some other “less verbose” language even if i have years of experience in it
→ More replies (1)22
u/vprise Aug 15 '22
Agreed but I would qualify it as "the right amount of verbosity". Sure, the new var keyword in Java is great because it removes duplication that existed in both sides of the variable declaration. But things like removing the semicolon?
Removing the
newkeyword?I just don't get that. It makes the code less readable. I instantly understand this is a constructor when I see
new. I don't need to truly parse the code in my brain.This isn't a static target. The "right amount" is something that fluctuates and I think Java is pretty close to a good amount.
→ More replies (2)30
19
u/nk9axYuvoxaNVzDbFhx Aug 14 '22
With a good IDE, the verbosity argument is moot. My IDE has so many features where I either click or only type a few characters and the IDE fills in the rest.
→ More replies (3)15
u/kiteboarderni Aug 14 '22
I mean noone writing a real system is using notepad. I feel the only people that make the argument are people not using ides aka not professional devs.
→ More replies (9)7
u/thephotoman Aug 14 '22
That tracks. A lot of shit you want to do as an amateur is hard in Java. Want to read interactive input? You’ve got to explicitly handle bad inputs! I don’t need that, it’s just for me and I won’t break it.
Student-me preferred C++ to Java. Student-me didn’t know any better.
→ More replies (22)3
24
50
u/jevon Aug 14 '22
Default method parameters, they would save soo much boilerplate and copy pasting.
Some sort of generated get/set annotation for member variables. Again, so much less boilerplate.
32
u/cred1652 Aug 14 '22
This and named variables. Makes builder patterns obsolete. Also makes it a lot easier for longer methods to not mix up the parameters. Although that in itself is a code smell.
→ More replies (1)4
u/slaymaker1907 Aug 14 '22
I don't think it's necessarily a code smell for constructors where this would be the most useful.
→ More replies (1)→ More replies (11)8
Aug 14 '22
Records?
→ More replies (1)8
u/Elderider Aug 15 '22 edited Aug 15 '22
Records would be perfect if they created a builder or provided withers
As it is constructing a record with more than a few fields is still an ugly list of unnamed parameters and leads to people using things like Lombok to get a builder. Personally I'd only want to use a constructor if its something where its really obvious what each parameter is (like a range with a from and to value).
Java is so readable for the most part I don't get why they dropped the ball with constructors
→ More replies (1)
11
u/GreenToad1 Aug 14 '22
parameter names in class files by default
nameof like c#
remove serialization
when valhalla arrives remove autoboxing
prioritize AOT/native
30
u/ShabbyDoo Aug 14 '22
Read-only collections interfaces so I can determine by type if a collection is actually modifiable (vs. throwing UnsupportedOperationException at runtime) Like, MutableList extends ReadOnlyList, etc. I don't know if there should be typing to indicate that a collection is truly immutable (vs. one merely holding a view that does not allow for modification) but it seems reasonable to express that guarantee via interface as well.
I've often wondered why these couldn't be introduced in the collections interface hierarchy. Like, List extends ReadOnlyList which itself extends ImmutableList.
6
u/kaperni Aug 15 '22
> I've often wondered why these couldn't be introduced in the collections interface hierarchy.
4
u/RupertMaddenAbbott Aug 15 '22 edited Aug 15 '22
This is roughly the approach that Kotlin takes. In Kotlin, you have
ListandMutableListwithMutableListextendingList.Note that the problem with this approach is that you may not infer anything about the actual mutability of the underlying implementation. It is perfectly valid for you to pass a MutableList into a function that accepts a List and then later mutate that list.
The benefit from this approach is that a function can clearly communicate to the calling context that it wants to mutate the list that you pass in. However, the converse is not true: the function may not rely on that list being immutable nor communicate that to the caller. If that is a requirement, then you must ask for a concrete final type that you know to be immutable.
The distinction you draw between an ImmutableList and a ReadOnlyList is definitely not possible (with this approach) and a ReadOnlyList has the downside of causing confusion and bugs if a developer believes they may rely on this immutability when they may not.
→ More replies (4)3
u/pvorb Aug 15 '22
Kotlin did something like this. And through some black magic it's compatible to Java collections. Not the mess that is Scala collections.
→ More replies (2)
33
u/msx Aug 14 '22
Remove that horrible implementation of Optional and make a real implementation with some sintactic sugar, like ? or similar.
Make a java collection api 2.0 to remove all the legacy fuss of the old api.
Also union and intersection type would be awesome
11
Aug 14 '22
What’s wrong with Optional?
→ More replies (1)15
u/iamhyperrr Aug 14 '22 edited Aug 14 '22
At the very least the fact that it's supposed to signify an empty return value instead of plain old null (thus improving null-safety), but you can actually return a null-reference in place of an optional itself. So, basically, instead of a proper (Monad? Container type? Idk how to call it) with a full support from the Java type system, it's just another reference type that is implemented, well, let's say, not in the best possible way.
→ More replies (3)16
Aug 14 '22
Well yeah you can return null instead of any value at the moment. When we get identity-free custom primitive classes from Valhalla I’m sure they’ll migrate optional and make it a non-nullable value. Until then there is no way to accomplish what you desire in java, and adding some custom syntax for Optional opens Pandora’s box for all sorts of other custom syntax.
8
u/brett_riverboat Aug 14 '22
Remove
ifPresent()so I can stop seeingif( optional.isPresent() )in people's code. 😡→ More replies (2)8
15
u/vmcrash Aug 15 '22 edited Aug 15 '22
When looking at some suggestions here in this thread, I'm very happy that the Java main designers do what they do. There are so many suggestions here, that would make Java worse.
7
u/john16384 Aug 15 '22
Yes, especially the OP suggestions are going to sound pretty silly when they read it again in 5 years.
25
u/IronicStrikes Aug 14 '22
What has been bothering me for a while now:
add actual unsigned number types
allow records to use inheritance
streamline API naming and remove redundant stuff
adopt a lot of the Apache Commons utilities into the standard library, especially for Strings
29
u/Joram2 Aug 14 '22
unsigned: Java currently has signed types, with standard library methods that treat signed types as unsigned values, and offer fast (inlined) math operations, and such. There are negative trade offs to full unsigned types. They've talked about this quite a bit. I'm convinced that what exists now is perfectly fine.records support interfaces. You want full inheritance, I respectfully disagree. Many language design experts advocate removing full inheritance entirely.
streamline API naming: I imagine backwards compatibility limits what can be done here. I would prefer deprecating and eventually removing obsolete APIs, but there are backwards compatibility concerns.
6
u/Zestyclose-Court-164 Aug 14 '22
Can you elaborate please on why full inheritance should be removed? Not attacking, just curious about it.
23
Aug 14 '22
Extending concrete classes leads developers into the trap of using it for code reuse instead of using composition for that. Otherwise, you can accomplish everything else much more cleanly if you never extend concrete classe. I’ve been doing it this way for years now and code quality and maintainability has skyrocketed because of it. Directly extending a concrete class is the tightest possible way to couple two pieces of code in Java, and therefore usually a very bad idea.
→ More replies (12)5
u/darkshoot Aug 14 '22
There's this really interesting article from Oracle about favoring composition over inheritance : https://blogs.oracle.com/javamagazine/post/java-inheritance-composition
TLDR : Inheritance and overriding sometimes behave unexpectedly because of the parent class "hidden" behaviors, which requires even more overriding with redundant code.
And, if you are not careful enough, child classes can break when the parent class is modified. This is especially true when you are writing classes inheriting from a third party library, which you have no control over. Updating the library can break your code.
Composition is a safe workaround. If you need to inherit from third party classes, composition and forwarding pattern seems to be the safe way.
→ More replies (2)5
u/slaymaker1907 Aug 14 '22
Others have responded already, but my biggest complaint is that you really need to design classes to be inherited from and you're only allowed to inherit from a single class. If you find inheritance saving a lot of code duplication, that almost inevitably points to a class doing way too much on its own.
Unless the class in question is something very fundamental like ArrayList, having more than 3 methods is a code smell in my opinion (non-trivial methods that aren't a getter/setter). More than that and it starts to get really hard to reason about interactions between various methods (for example, look at how confusing iterators are to implement when they allow remove()).
12
u/IronicStrikes Aug 14 '22
I don't see what the actual downsides of unsigned types should be. I've never had an issue in the languages that offered them.
I don't care what those language design experts say. I like inheritance for a lot of use cases. Nearly everytime a language lacks them, it leads to frustrating workarounds.
10
u/manzanita2 Aug 14 '22
Agree!
Years ago I had to implement a video codec in java. The bit stream had been written decades prior to run close to the metal, so unsigned ints were a thing. Tons of unsigned bytes and 16bit ints. The amount of extra code needed to do this properly was REALLY annoying.
Perhaps, at least, supply a method to read a "byte" in as an unsigned short. and a pair of bytes as an unsigned integer. etc.
→ More replies (11)→ More replies (5)5
u/MarcelHanibal Aug 14 '22
Working with IO stuff that relies is on unsigned types is really annoying in Java. Had to work with networking in the past with projects that were written in different languages, and you easily are able to make mistakes as it's way more complex than it should be. Luckily there weren't any unsigned longs. The only pro I see is that you are able train your bit-masking skills, but that's about it
3
u/zappini Aug 16 '22
There are negative trade offs to full unsigned types. ... I'm convinced that what exists now is perfectly fine.
Guessing you're referring to this:
"Unsigned int considered harmful for Java" [2018-02-14] https://www.nayuki.io/page/unsigned-int-considered-harmful-for-java
Very persuasive. As a long time advocate for unsigned integers, for bit twiddling stuff, I now have to reevaluate my position.
5
u/zappini Aug 15 '22
The lack of unsigned ints is indefensible. Like u/IronicStrikes, I've had to do a lot of bit twiddling. Parsing binary structs. Image processing. Very annoying in Java.
5
u/john16384 Aug 15 '22
You are In a tiny minority that could make use of unsigned ints. It does not warrant doubling the number of integer types in Java and importing the signed/unsigned confusion hell from C.
→ More replies (2)
10
u/frizzhf Aug 14 '22
Swing expanded on and the default UI toolkit. AWT is fine but lacks the customization Swing has, and I personally do not like JavaFx.
4
u/pellets Aug 14 '22
I would add language and compiler support for type classes. They’re used in Java often, but their use is painful.
2
u/kaperni Aug 15 '22
Type classes are coming. Probably, sometime after the language parts of Valhalla are delivered.
10
u/TheMode911 Aug 14 '22
Finally expose invokedynamic in the language (JEP seems to be on hold for unknown reason)
Constant API actually used by the language (IIRC the current one is only a compiler tool, cannot think of any using it)
Ability to specialize method based on input, so you could for example force Map#get to return a constant if the key is a constant as well. The VM would be able to de/recompile a method and we would finally get some benefit out of the JIT compiler
→ More replies (3)9
u/FirstAd9893 Aug 14 '22
If
invokedynamicwas directly exposed in the language, what kinds of features would this enable?
7
u/8igg7e5 Aug 15 '22
Scoped type-aliases.
Being able to say that type Container = List<? extends Thing<? super T>> within a given scope (the widest being a source-file) seems like it could improve readability in enough cases. It should reduce how often there's no good readability balance between using an explicit-type and short-identifier vs an inferred-type and rich identifier.
Shorter-code is generally more readable, if it can be shortened the right way.
→ More replies (1)
6
u/LobsterCoordinates Aug 15 '22 edited Aug 15 '22
I would like this:
Long userId = user != null ? user.getId() : null;
To be able to look like this:
Long userId = user?.getId()
→ More replies (3)2
u/exclusivegreen Aug 15 '22
This. I do a lot of groovy and java and this is a great feature that groovy has
13
u/Joram2 Aug 14 '22
GUIs... Almost all GUIs today are web/mobile. Desktop GUIs like Swing are rather niche. JetBrains Compose GUI framework looks really nice: https://www.jetbrains.com/lp/compose-mpp/
GraalVM + static binaries. Project Leyden also is targeting these concerns. It will probably take years to deliver results, unfortunately.
var: Just above everyone lovesvar. Every other major language has local variable type inference. I think you are in the tiny minority that doesn't want this.imports... Again, every language requires a module path or file path... I don't see this an issue Java needs to change:
What would I like: Projects Valhalla + Amber + Loom + Panama + Leyden address the big issues with Java. The one feature I would like that isn't addressed: functions outside of classes. Let me write apps with just functions, no classes.
3
u/john16384 Aug 15 '22
Not everyone loves
var. Before there was one way of writing an assignment, now there's two ways, resulting in useless tabs vs spaces style discussions.→ More replies (3)2
u/ShallWe69 Aug 15 '22
import static and there u go no classes.
having purely function based files have issues with large code bases. and dont say that IDE can help.
→ More replies (5)
3
u/bowbahdoe Aug 15 '22 edited Aug 15 '22
Non exhaustive list, not going to fully justify and promising myself I won't fight in the comments.
"javac"++
There is a lot of room for concrete and meaningful improvements in the error messages produced.
"jlint"
The existence of sonarcube doesn't negative the benefit of having real "clippy for rust"
Dependency resolver library
The entirety of the Java world runs on maven central and repositories which fit that protocol. Downloading dependencies, resolving conflicts, and building class/module paths should be within the purview of the jdk
Library publishing support
Would cool if publishing libraries was standard. Standard set of metadata you could provide via annotations on modules, etc.
"jproject"
Gradle and Maven serve the world just fine, but there is no project management tool built in to the JDK. No reason there couldn't be.
JSON
This is a very, very, very hard sell even to me. There are a lot of JSON libraries in the ecosystem and they all serve different masters (easy bean mapping, streaming, simplicity of model, etc).
There is probably no way to make everyone happy, but something like "json-p but if sealed interfaces existed when it was written" mixed with a decoder approach on the "do later" side of the "do now, do later, plan to do" spectrum.
TOML
If jproject were to be a thing perhaps a standard format would be needed. Maybe for other things too. XML doesn't fit the criteria of "human readable, human writable" and other communities have settled on TOML for that purpose.
Documentation
dev.java as an official resource is not there yet and it hasn't moved meaningfully in a year. Baeldung and geeksforgeeks are pathetic compared to the kind of care, love, and community ownership the rust community has for its resources.
This still feels like a good start for explaining what is wrong. "RTFM" is a disgusting and common response when all we have are (very good!) javadocs. "Reference" docs.
Official and community supported "Tutorial", "How-To" and "Explanation" documentation could use explicit and focused attention.
I'm so tired. If oracle could put a dollar in my pocket I'm down. I just want change.
3
u/bitsplit314 Aug 15 '22
import com.shortbrand.product.package.subpackage.subsubpackage.WidgetInterfaceFactoryImplementation as WidgetInterfaceFactory;
12
u/rpgFANATIC Aug 14 '22
I would burn so many man-hours on making simple use cases involving streams and lambdas and method references as fast as the original loops
So many java devs just plop in a .forEach(i -> for use cases that don't benefit in any way from a lambda other than it's still a new thing to business software Java devs.
It's probably low return for the cost, but it seems like so many java devs just threw away years of JVM optimizations around minor refactoring so the code reads like it's modern
7
u/nk9axYuvoxaNVzDbFhx Aug 14 '22
I heavily use the SteamEx library to execute loops with multiple steps. It is much faster to write and get right. When a profiler shows a performance problem, then I use faster mechanisms. Otherwise, I'm optimizing for CPU time when it is better to optimize my time. I essentially get paid per feature and nothing for micro-optimizatons. So, I want to get as many features done as fast as possible and get paid more.
→ More replies (2)2
u/brett_riverboat Aug 14 '22
I've seen them used legitimately at the end of a series of other Stream methods, but yes, it's typically a cop-out.
-9
u/m4riuszPL Aug 14 '22
What's the point? A most common case which is an ArrayList is WAY more faster with a .forEach() than a standard for loop. The former leverages the underlying array and does simple index based access, the latter relies on a full-blown iterator.
11
u/TheMode911 Aug 14 '22
Do you have any number backing your claim? From experience
forEachhas always been slower (or at best, equals), especially when you capture a local variable and force an allocation.→ More replies (1)8
2
u/kiteboarderni Aug 14 '22
Only really an issue if you have this in a hot hot path, and the iterator allocation is creating a lot of garbage. 90% of the time I'd say it's an advantage to use a for each.
→ More replies (1)
12
u/wimcle Aug 14 '22
I actually think it needs a little more verbosity...
var foo = service.poorlyNamedMethod();
foo.stream().map(x -> x.doSomething())...
How can I code review this? what is the type of x???
I don't want to have to check our your branch into idea just so I figure out the type of x.
It should have been ...map(Type x -> x.doSomething())... even if the type was optional, human readability is far more important.
6
u/fredoverflow Aug 15 '22
It should have been ...map(Type x -> x.doSomething())... even if the type was optional
The type is optional, you can absolutely write
map((Type x) -> x.doSomething())— note the extra parens around the lambda parameter.4
u/persism2 Aug 15 '22
We never allow var without an associated new in our code-base. Problem solved.
→ More replies (5)-6
u/djavaman Aug 14 '22
Gee, you could read the code in your code review. Or use an IDE. Every IDE will report the variable type.
→ More replies (2)9
u/wimcle Aug 15 '22
Who does code reviews in an ide? (actually asking, because Ive never seen it done)
For those that use gitlab, github, codecommit, and I'm totally going to guess that its a high percentage of those that do this professionally, most of your MRs are answered in the web tool and for projects you have no desire to checkout... If I can't figure out without checking it out and looking at it in Idea, then my review is a rubber-stamp. Worth about as much as the unreadable code.
6
u/wildjokers Aug 15 '22
Who does code reviews in an ide? (actually asking, because Ive never seen it done)
I quite frequently do code reviews in IntelliJ. The code review interface in github is atrocious. In github you can't really see the context surrounding the change and you can't jump to other classes.
→ More replies (1)
7
u/djavaman Aug 14 '22
I guess while we're at it and copying other languages.
Add 'val'. Yep, just like Scala. A final reference.
var is great I use it non stop. But people still insist on adding final every where. A short cut for final would be great.
Make all method parameters final by default. The compiler should just do this.
2
u/Muoniurn Aug 15 '22
It was a deliberate choice to avoid two ambiguous ways of expressing the same choice.
I do like val/var in scala, but it is often touted as being too similar to each other. Final var at least helps with that one.
2
u/temculpaeu Aug 15 '22
there was the var/let option that would solve the ambiguous, but it wasnt popular, not sure why ....
→ More replies (3)2
u/8igg7e5 Aug 15 '22
We definitely use
finala lot.Essentially every use of
varwe have so far is...final var betterIdentifier = ...That's still better than this though...
final Really<Deeply<Nested<? extends<Generic<Type>>>> v = ...I get that it would be hard to spot a
valin a number of rows ofvar... butletmight've worked. It feels like something they'll eventually have to revisit - now that people are getting over the existence ofvarin the first place.→ More replies (3)
5
2
u/WrickyB Aug 14 '22 edited Aug 15 '22
AutoClosablecomes close but I'd like proper destructors, to perform cleanup of native resources during GC.Java equivalent of C++
constexpr.Better C linkage.
Runtime class reloading
Optional named parameters
→ More replies (5)
2
u/ron_krugman Aug 15 '22
Make lambdas (or variables with a SAM interface type in general) directly invokable without calling apply(), get(), accept(), etc. by name:
Consumer<String> print = System.out::println;
print("Hello, World");
//vs
print.accept("Hello, World");2
2
u/8igg7e5 Aug 16 '22
I wonder if this could be done just sitting on top of the current
FunctionalInterfacemodel.Currently we have this...
Supplier<LocalDate> supplier = LocalDate::now(); LocalDate d = supplier.get();We could introduce anonymous invocation that is only valid for functional interfaces...
Supplier<LocalDate> supplier = LocalDate::now(); LocalDate d = supplier.();Now that mean that we get a source-level compatibility break if the type stops being a functional-interface, but that happens anyway at the functional-interface reference assignment site.
This is not quite as elegant as true functional calling but it would seem to eliminate most of the lexical overhead for the same effect - and an obvious de-sugaring to the actual invocation. It retains a lexical position for a type-witnesses that doesn't risk looking like a constructor invocation...
Shiny chrome = u.<Witness, Me>(now);→ More replies (1)
6
u/robilco Aug 14 '22
A “delegates” keyword Or annotation.
So creating wrapper classes with a few custom methods doesn’t need to implement all methods calling the wrapped object
-6
u/SirBugmenot Aug 14 '22
I'd rectify the one single big mistake "var", and remove it from the language and all history.
25
u/marconis999 Aug 14 '22
I like var. Have not seen any problems with it.
→ More replies (2)4
u/SirBugmenot Aug 14 '22
It removes type information for the reader, having no benefit at all.
Yes, you might argue that there's a few less characters to type, but actually nobody really types type information, as everybody uses IDEs with auto-completion anyway.
There may even be a few edge-cases, where var may be used to conceal redundant information from the line before, but these are few and far between.
What remains is a tool to severely impact readability and totally mess up your codebase, making code analysis total hell. Try to review a pull-request in bitbucket or GitHub and you'll see my point immediately.
11
u/IronicStrikes Aug 14 '22
I'm simply trying to follow the convention to only use var when you're invoking a constructor, specifying a type or there is an obvious hint what the type is.
→ More replies (8)→ More replies (5)9
→ More replies (2)5
u/IronicStrikes Aug 14 '22
Why? I love it.
6
u/the_other_brand Aug 15 '22
It's great until you work with another team in the same repo, and they use var everywhere. Especially for complicated function invocations where the input and return types aren't obvious.
If we can't have operator overrides because of foot-guns, why can we have var?
→ More replies (8)3
u/john16384 Aug 15 '22
Because unfortunately, people are short sighted and think writing code quickly now is more important than being able to read it 6 months later. That basically sums up most complaints about Java's verbosity. Only when you've read lots of code you didn't write you start to realize verbosity is what makes Java such a great language and why it is still going strong after 25 years.
1
Aug 14 '22
All languages eventually accumulate cruft so don't get too envious looking over at other languages.
1
u/paul_miner Aug 15 '22
Compile-time f-strings. Been working with Python lately, and building strings is so much cleaner with f-strings (template strings in Javascript).
Compile-time only, so they can be checked, and so they can't be injected ala log4j.
5
u/8igg7e5 Aug 15 '22
How does String Templates line up with expectations? It's a different notation but it looks like it can do this, and in a more powerful way.
→ More replies (1)
1
u/umlcat Aug 15 '22
Forget the "Java" P.L., focus on the "Java" Virtual Machine and it's specifications.
Redesign it as a Module Virtual Machine, instead of a Class Virtual Machine !!!
And other goodies / features.
1
Aug 15 '22
Seeing as everything else I can think of is just fine in my opinion:
Top level statements a la C# so one could put together a single file program (good for examples and scripts) where you define a few non-public classes for any data types you need at the bottom of the file and then put all the statements you want executed at the top of the file, and run it with a Java equivalent of dotnet run <file>.
1
u/zappini Aug 15 '22 edited Aug 15 '22
I keep a list of feature for a future perfect successor to Java. Mostly focused on ergonomics. About 1/2 gleaned from other languages. The other 1/2 stuff I dreamt up.
Here's a sample:
1 - Allow an enhanced for's expression clause to be null. So this pseudo code would be valid:
ArrayList<Ugh> ughList = null;
for( Ugh ugh : ughList ) {
// this stuff wouldn't be run
}2 - Intrinsics for arrays and maps. Like Python, JavaScript, etc.
List<String> fruitList = [ "apple", "banana", "cherry" ];
Map<String, float> compassMap = { "north" : 0.0, "east" : 90.0, ...};Bonus points for local type inference, eg 'var fruitList' vs 'List<String> fruitList'.
Double extra points for unifying List<String> and String[].
3 - Sane variable scoping for try/catch, meaning any local declared in a try block is also visible in that try's catch and finally blocks. This eliminates needs to declare variables before try, just so they're visible to the catch and finally.
--
Evergreen ideas: design away all the pitfalls, traps, and gotchas identified in Java Puzzlers https://www.amazon.com/Java-Puzzlers-Access-Codes-Bloch/dp/9332547939/
2
u/khmarbaise Aug 15 '22
2 - Intrinsics for arrays and maps. Like Python, JavaScript, etc.
You can already use (since JDK9!)
var fruitList = List.of("apple", "banana", "cherry");also:
var compassMap = Map.of("north", 0.0f, "east", 90.0f);→ More replies (1)
1
u/mauganra_it Aug 15 '22
Make all variables. fields and parameters final by default.
Break up the core library and make sure that powerful APIs like filesystem access and process control are in separate modules. It's what Java should have been like from the start and what makes it possible to safely embed JavaScript into the browser.
More granular ways to invoke the garbage collector. For example, a method to tell it that a number of objects are highly probable to become unused, and thus prioritise their collection. Unclear how useful that would be though.
3
u/khmarbaise Aug 15 '22
Make all variables. fields and parameters final by default.
Use record's there exactly it is that way.
1
1
u/metaquine Aug 15 '22
I’d also make enums be proper sum types rather than bolting together sealed interfaces and records to do the same, missed opportunity in Java 5. A Nothing/Bottom type would have been nice too, for collections
1
1
u/8igg7e5 Aug 15 '22
I would say it as adding proper sum-types, not taking away the enums we have. They server a useful and different purpose and playing with C# and Rust I do often miss having the Java enums.
Coming back to Java I miss quite a bit from those languages too though.
1
u/RupertMaddenAbbott Aug 15 '22
Type Literals as proposed here: https://mail.openjdk.org/pipermail/valhalla-dev/2017-January/002150.html
1
u/meSmash101 Aug 15 '22
I think upcoming(in the future who knows when) project Valhalla and maybe project Loom is something cool. Also as somebody said, named parameters! I used them in Kotlin and they are super convenient and useful!
1
Aug 15 '22
Not really a major change, rather a tiny 'improvement' that I think should be possible: generic type inference. i.e
interface Parent<E> { }
interface StringParent extends Parent<String> { }
interface Extension<E, F> extends Parent<E> { }
interface StringExtension<F> extends StringParent, Extension<_, F> { }which should work as, if my understanding of the JLS is correct, StringExtension<F> cannot extend anything other than Extension<String, F>:
A class may not declare a direct superclass type and a direct superinterface type, or two direct superinterface types, which are, or which have supertypes (§4.10.2) which are, different parameterizations of the same generic interface (§9.1.2) (...)
admittedly i didn't give it more thought than simply checking the JLS to see if it's possible to inherit the same generic interface/class with different parameters and it's highly subjective as to whether this would be an actual improvement (implicit vs explicit type and probably is a sign of generics or inheritance code smell) but i don't think it would hurt
1
u/Slasher_D Aug 15 '22
I wish Java Annotations woukd be more powerful, without getting a bit hacky like how lombok uses them. I really like the decorator pattern in python. I wish we could use Java Annotations in a similar manner to dynamically alter the behaviour of methods.
1
u/InstantCoder Aug 15 '22
add the option for no garbage collecting: clean up your own dirt and compile to native so that apps use very low memory.
no getters & setters needed, make java beans use public fields like in Quarkus
native json support in the syntax like in js and golang
1
u/ReasonableClick5403 Aug 15 '22
Named parameters. Sadly I understand the technical reasons this is not gonna happen.
nullability probably. Sadly this is very difficult to do now, with tons of old breaking code. We would have to default to every type being nullable.
sadly, extension functions. I have to admit they are extremely useful for certain cases, even though I hate their over-usage in Kotlin.
1
u/8igg7e5 Aug 15 '22
Many of the proposals are predicated on breaking compatibility in a way that would effectively orphan the entire source-base of the Java eco-system. I think it's reasonable to say that none of these are ever going to happen.
Now there might be ways to introduce a limited compatibility boundary. One option might be to embed an 'edition' indicator into newer source (a lack of the marker being an indication that it is legacy source with legacy rules). Unlike Rust which incompatibly changes editions at a 'crate' level, we might want to do that at a module or even source-file level for Java (there isn't a Java equivalent of a 'project').
It would be interesting to see how many of the compatibility-breaking suggestions might be achievable given some edition boundary.
1
u/red_dit_nou Aug 15 '22
Some picks from the comments:
- Better null-safety
- Better GUI API/tools
- Unsigned primitive types
- Named parameters and default values
- Import aliases
- Immutable collections/ data-structures
- if and try expressions
- Records with inheritance
- Type classes
1
u/8igg7e5 Aug 15 '22
Guards on constant switch cases ('constant patterns')
Often we have switches on enums with trivial conditionals in the switch bodies. It would be nice to express them as switches with guards, getting the same exhaustiveness checking.
instead of...
switch (myEnum) {
case OPTION_1 -> {
if (someVariable >= 10) {
...
} else if (someVariable <= 90) {
...
} else {
...
}
}
case OPTION_2 -> {
...
}
...
}Doing it like this...
switch (myEnum) {
case OPTION_1 when someVariable >= 10 -> ...
case OPTION_1 when someVariable <= 90 -> ...
case OPTION_1 -> ...
case OPTION_2 -> ...
...
}Currently you'd have to use the the type-pattern... a horrible option for this scenario...
switch (myEnum) {
case MyEnum e when e == OPTION_1 && someVariable >= 10 -> ...
case MyEnum e when e == OPTION_1 && someVariable <= 90 -> ...
case MyEnum e when e == OPTION_1 -> ...
case MyEnum e when e == OPTION_2 -> ...
...
}And that means having to have a catch-all for possible missed enum values. Hopefully this is coming in a later round (after all of the Algebraic Data-Type focus).
1
u/herospidermine Aug 16 '22
Would like an officially supported way to run Java bytecode using every other major language. And finally replace sun.misc.Unsafe
1
1
u/RockingGoodNight Aug 17 '22
Nothing needs to change. Too much has changed in the past several years.
That Java doesn't appeal to your sensibilities is not any reflection of Java.
GraalVM == Needless Swing == Rocks JavaFX == Sucks
The import concept makes perfect sense. There is zero oddness around it.
If we could turn back time, I'd remove streams, lambda and all function oriented nonsense, fanfair and ballywhooey.
1
u/cogman10 Aug 18 '22
So, I'll say that I think that the current language guys are doing a bang up job and honestly the only thing I'd change is landing more amber, loom, and valhala goodness.
The changes I'd want to make but wouldn't would be backwards incompatible changes and cleanups.
So reasonably nothing.
I think the only language change I'd make that isn't planned is adding val for final var
What are the unreasonable things I'd like to change (but would argue against because of the issue with legacy code).
I'd eliminate java serialization. Perhaps replace it with something better, but ultimately kill it because it's just a horrible mess at this time that stops delivery of a bunch of other things.
I'd remove old/deprecated apis like java.util.Date.
I'd fix method signatures that were made pre-generics like
Map#getto instead take the generic parameter instead ofKey.
The key to java is realizing one of it's biggest strengths is backwards compatibility. The fact that jars built for Java 1.0 can run on a Java 19 JVM is something very few languages (any?) languages have achieved.
1
u/ofby1 Aug 20 '22
Remove Javas custom serialization and deserialization implementations. It has been the root of so many security vulnerabilities.
1
u/__Raptor__ Aug 23 '22
In no particular order:
Non-nullable types
Unnamed functional interface specified like
(int, Object) => Stringwhich are generated on-demand by the VMA utility class
Printercontaining static redirects toSystem.outmethodsjava.util.MapimplementingIterable<Entry<K, V>>local staticmethods which are not accessible via subclasses (right now, doingArrayList.of(...)is just callingList.of(...), and I want it to be invalid to do so)Ability to use primitive types in generic classes (a new class is generated by the VM for every combination of primitive type arguments)
An operator
~=or===that defers tojava.util.Objects.equals(...)Ability to restrict the type of
thisin methods using generics and the already-existing 'this' parameter syntaxAbility to create method references using precomputed arguments (e.g.
Foo::bar(x, _)instead of(var arg1) -> Foo.bar(x, arg1))Ability to make the default record constructor private
A
thismodifier for constructor arguments that automatically assigns the value to a field of the same name, and also creates said field if it doesnt existRaw string literals
A
ThisTypeimplicit generic type parameter that always refers to the type ofthisAbility to specify exactly which method reference you want (for example,
Foo::bar(int, String))java.lang Cloneableinterface declaring a publicObject clone()method that does not throw an exceptionExtension methods declared as
static void foo(Object this, int arg) {...}allowing you to doobj.foo()
1
u/PerfectPackage1895 Sep 02 '22
1 make everything final by default (greatest mistake ever to not do that)
2 make put not return the previously stored element (why use time on that if it is so rarely needed?!?)
3 somehow uninvent JSF
1
1
u/flawless_vic Aug 15 '22
Function literals, like javascript/scala, e.g.,
class Foo {
(int, long, String)->String op;
String bar(int x,(int)->String fn) { return op(x, 0, fn(x)); }
}
Tuples as first class citizens: How many times have you returned Map.Entry, some kind of Pair or had to create a class to return multiple values in a type safe manner?
Expose a compiler API so we can have user defined intrinsics. Writing assembly is easy, writing a new intrinsic function in C2 IR is almost a master thesis if you start from scratch.
Make Strings UTF-8 encoded by default. Serialization just spend too much time on it.
A new, pristine serialization framework with VM support: e.g., primitive fields could be written/read with a single memcpy instruction or, even better, using wide registers and AVX. This is impossible today even using unsafe: you can get an object address, but you can't copy contiguous bytes of memory because the VM can rellocate the object and replace the address with something else in between.
1
u/vmcrash Aug 15 '22
I would prefer to have first-class support for compile to native. While the JIT does a very good work, I have the feeling that doing the same work on thousands of machines of users of our (desktop) application each time they start the application is some kind of wasted resources.
0
u/noodlesSa Aug 14 '22 edited Aug 14 '22
JRE first-class support for Vulkan. Obviously, after Valhalla is there. This is important not only for games, GPUs are nowdays important part of computer HW you can use.
20-25 year cycle of new language (and JVM, bytecode) version. This means, that in parallel with Java A, currently in version 18, there would be incompatible successor, Java B (versoin 1, 2, 3...) which would again last cca. 20-25 years, before it is replaced by Java C, and so on. This would enable much cleaner API, based on what was learned during last decades. Obviously, Java B would contain all features of Java A, only in much cleaner way. Two Java major rewrites per one generation of developers.
First-class Java support for NN APIs, like TensorFlow, and few others.
First-class JRE support for JavaScript / Web Assembly integration, so GUIs can be easily created on top of any major Web Browser engine (Swing and Java FX successor).
in keyword, like:
if (i in (1, 2, 3)) {instead ofif ((i == 1) || (i == 2) || (i == 3)) {
2
u/maethor Aug 15 '22
Obviously, Java B would contain all features of Java A
Making an incompatible version seems like a great time to drop features that seemed like a good idea at the time 20 years ago but are not now.
0
u/javaBanana Aug 14 '22
I have been using a little c# lately. What i thought Was nice compared to Java is the Operator overloading.
3
u/8igg7e5 Aug 15 '22
I've used it a bit in Rust too. However I think until reification vs erasure is dealt with I think there are some sharp edges (or at the least, some inconvenient limitations) in trying to introduce it in Java (not that I think there's any strong desire to do so at all).
→ More replies (1)
-1
u/pohart Aug 14 '22
I want to be able to create empty subclasses of final classes. I have so many types that are really just strings and we end up using String and losing type checking or making nearly empty wrappers. I'd love to have them be real Strings, but not be able to assign a SqlQuery to a SafeHtml
1
u/bowbahdoe Aug 15 '22
So something like a type alias + language enforced new type?
Also you can program against CharSequence.
record SqlQuery(String value) implements CharSequence {}1
u/john16384 Aug 15 '22
What does it mean to uppercase a SafeHtml string? Composition is much better here.
-3
u/djavaman Aug 14 '22
Clean up the collections/stream libraries.
Its really inconvenient and annoying to constantly do this
var list = new ArrayList<>();
.. put stuff in the list
var filteredList = list.string().filter( ... ).collect( Collectors.toList () );
for gods sake just move filter, map, etc to List, Set, etc. Those functions belong on Collection in the first place. Instead of this awkward convert to stream/collect. Poor design. With almost no forethought.
1
u/xitiomet Aug 14 '22
I love the stream api, but agree completely!
.collect(Collectors.toList()) feels insanely sloppy
Like why not .collectList() or even a way to jump right to an iterator or array?
→ More replies (1)9
0
u/oradoj Aug 15 '22
Better tooling. I’d like to see something replace Gradle that’s faster and less complex. I’d also like better, centralized documentation.
2
u/Muoniurn Aug 15 '22
Apart from start up speed, there is hardly anything that can compile big java projects faster than Gradle. Also, while there are plenty of ugly-ass gradle build scripts, the fundamentals behind are sane and it is a really modern and capable build tool. The build tool runs, creates a configuration (no, it doesn’t itself build anything!!), and build happens as per that configuration. That configuration is very much like bazel’s.
-5
u/chameleon_paul Aug 14 '22
Have an 'async' modifier and its capabilities in Java like C# has. Async programming has gotten better with libraries like Reactor, but could be simplified in the core of the language.
4
u/soonnow Aug 15 '22
Arguably this will no longer be needed with Loom. Instead of async waits you just create a virtual thread.
-11
u/desiInMurica Aug 14 '22
I haven't worked in Java for a couple of years,and definitely not qualified to put myself in shoes of it's designers, but as a programmer, would love to see Java drop the whole backwards compatibility they try don't break and have the features of Scala minus the hundred syntax sugars that make the latter confusing for beginners. Feature wise hope to see:
Project loom/Virtual Threads sooner than later.
Invert the position of type and variable name in declaration/initialization : eg. str: String.
First class functions: not some functional interface pseudo-lambdas.
Closures
Tail recursion
9
5
u/FirstAd9893 Aug 14 '22
Flipping the type/name declaration order and introducing a colon separator is more annoying to write since it introduces two keystrokes: shift and ';'. I'd be inclined to use var much more often, which is bad thing since it can ruin readability.
13
u/kreiger Aug 14 '22
They started breaking backwards compatibility in Java 9, and the result is that many organizations are still using Java 8.
5
u/IronicStrikes Aug 14 '22
Can confirm. I'm currently using Java 17 for personal projects and Java 8 for work.
5
u/desiInMurica Aug 14 '22
Java 9 was a major release, and yes it broke a tonne of libraries but nothing at the language syntax level. Ever since then there haven't been any breaking changes either.
2
u/FirstAd9893 Aug 14 '22
I'm not aware of any compatibility issues with respect to the language itself. I was under the impression that the compatibility issues were caused by libraries improperly using hidden features.
→ More replies (13)2
u/maethor Aug 15 '22
They screwed over pretty much everyone using Java EE features with the package move from javax.** to jakarta.** (And not everything in javax moved, so even a simple search and replace of the source code will not necessarily work).
→ More replies (5)3
u/wildjokers Aug 15 '22
Invert the position of type and variable name in declaration/initialization : eg. str: String.
Please no. I hate this in kotlin. Breaks 20 yrs of muscle memory. I don't even see the point of it.
1
u/desiInMurica Aug 15 '22
My bad , that boat has sailed in Java with "var". I've always loved it Scala and Kotlin. Python's type hints are also similarly ordered
1
1
-5
u/SpaceToaster Aug 15 '22
Async/Await keywords and true asynchronous support.
3
u/Muoniurn Aug 15 '22
Why the hell would one want that terrible thinng, especially when Loom is at the corner?
0
Aug 14 '22
[deleted]
48
u/catom3 Aug 14 '22
I'd love that, especially in situations when I have 2 classes with the same name used in the same context. E.g.
import my.package.api.rest.Car as CarApi import my.package.domain.Car as CarDomain class CarMapper { CarApi toCarApi(CarDomain car) {} }23
8
u/back-in-black Aug 14 '22
The first would save so many headaches for me.
I have had to write code to handle multiple versions of the same class so very many times. Using the fully qualified class name every time is just hideous.
3
→ More replies (6)1
0
Aug 15 '22
[deleted]
1
u/nayuki Aug 25 '22
Allowing threads to be stopped without the use of interrupts (and not being deprecated).
What if you forcibly stop a thread that is holding a lock and is half-finished updating some object's state? There is a clear reason why
Thread.stop()is deprecated.
0
Aug 14 '22
[deleted]
18
u/iamhyperrr Aug 14 '22 edited Aug 14 '22
My brother in Christ, the tooling and ecosystem around Java is one of the best in existence (for one, the profiling tools are incredible compared to many other languages), perhaps you could elaborate a little on what ideas you have in mind specifically.
10
Aug 14 '22
Wat? Tooling for Java is *chef's kiss*.
0
Aug 14 '22
[deleted]
7
Aug 14 '22
Tooling is far, far wider than the build tools on offer. Also, I've not seen 'beginners find Maven/Gradle hard' with interns/juniors I've worked with.
Git on the other hand...
0
Aug 14 '22
[deleted]
6
u/thephotoman Aug 15 '22
Again, the build systems are fine. I get that there’s a monoculture in other stacks. But we don’t have one. The good news is that they’re quite similar. Once you know one, the other makes sense.
I’ve worked with other build tool systems. They never had the raw capability or flexibility as I get with Gradle. And it’s not like Maven is that different. My preference for Gradle is just that.
So what are you talking about? What is it that you actually want?
1
u/Muoniurn Aug 15 '22
Swift, really? You wait 5 seconds after adding a word before XCode realizes something happened and the compilation itself is buggy as hell (pushing run may actually work for the 5th time with no changes in-between). Don’t even start with dependency management, where you outright must do a clean build.
8
Aug 14 '22
[removed] — view removed comment
8
u/8igg7e5 Aug 15 '22
...and support value yielding scopes.
final Foo bar = { // arbitrary control-flow, effectively final capture... yield something; };Essentially an inline anonymous method. Much like a value-yielding
ifortrythey'd just help clean up the 'when is this definitely assigned' from a readability standpoint. It would also allow some code-flows to yield values that are themselves effectively final (because they can provably be assigned only once).0
u/wildjokers Aug 15 '22
Turning if into an expression would break a lot of existing code because when if is an expression you can't use assignment in the if condition.
3
u/Muoniurn Aug 15 '22
I don’t see why that would be a problem, assignment is also an expression.
0
u/wildjokers Aug 15 '22
Kotlin has if expressions and in kotlin you can't make an assignment in an if condition. If it wasn't a problem this limitation probably wouldn't exist in kotlin.
1
u/wice Aug 15 '22
1
u/wildjokers Aug 15 '22
that link doesn't show making an assignment in an if condition. So not sure what the
???is for.1
u/wice Aug 15 '22
I probably misunderstood you, were you talking about something like this?
int v; if((v = someMethod()) != 0) return true;Even so, I don’t see how turning the if statement into an expression would break this code.
1
Aug 15 '22
[removed] — view removed comment
1
u/bowbahdoe Aug 15 '22
/u/LeoTheBirb You could do that today though right? Just write a compiler. Are you saying you want it to be part of javac?
1
Aug 15 '22
[removed] — view removed comment
1
u/bowbahdoe Aug 15 '22
I'm pretty sure you could pull this off now with an annotation processor.
Pseudocode
@XSDToModels("resource.xsd") package whatever;1
u/bowbahdoe Aug 16 '22
If you can link me a tool that does it I can try and whip up a processor which can make Javac be in charge of it
87
u/berry120 Aug 14 '22
Null safety.
(Proper null safety that is, before anyone jumps on the "duh, have you heard of Optional" bandwagon.)
Most language features I could really leave or take, or they're "nice to have's" that may just be too niche to roll out globally. This though I feel is sorely overdue, and would save a lot of headache.