68 points · by kasperni · 5y ago · 101 comments
Decades later, we're still wondering as we get to more and more complex use cases, why we're stuck with passing the class object to all our generic types just to know who we are. It's really a rare instance where Java gave an engineer's solution when they should have given us something more, like a compile flag, a fork, a GenericArrayList<Something> that would be reifed, anything, rather than excuses about ecosystem, backward compatibility perfection, etc.
I understand why they took that decision, I don't understand how it helps all of us do meaningful generics :(
Another way to state this requirement is: it was not considered acceptable to orphan all the code out there that could have been generified, or make developers choose between generics and retaining the investment they’ve already made in existing code. By making generification a compatible operation, the investment in that code could be retained, rather than invalidated.
It's great to see such care for the users, while at the same time improving the platform to make it one of the top performing ones.
There’s a bunch of ways to do this, but I’ll just leave this one trick here.
Instead of:
List<Integer> x = new ArrayList<Integer>();
write this: List<Integer> x = new ArrayList<Integer>(){};
Now you’ll be able to ask at runtime and determine it is a subclass of List<Integer>.So, instead of doing that, they have decided to devalue Java code in long term, by deliberately making language and runtime less useful. Interesting choice.
It will allow (almost) direct control over data layout. At least make it so that it is cache/prefetch/SIMD friendly.
Here is the JEP: https://openjdk.java.net/jeps/401
I have a List<Integer>. Maybe I want to replace List with something else, call it L.
Can I write L<Integer> in Java? No. Rust? No. C#? No Kotlin? No.
Does Go have generics yet? Once it does, I'm sure it'll be a No as well.
Haskell and Scala got it right.
def process[L[_]](input: L[Int]): Unit = ???
Where `L[_]` could be any type that has a type parameter, e.g. `List[_]`, `Option[_]`, `Future[_]` or `Either[String, *]`. This opens the door to a new level of abstraction where other languages must resort to code generation or similar ad hoc-like solutions. <L> void process(final L<Integer> input) {
}
------------------------------------------
<L> void process(final L<Integer> input) {
^
required: class
found: type parameter L
where L is a type-variable:
L extends Object declared in method <L>process(<any>)For example, there is a typeclass Foldable[F[_]] which provides the ability to "fold" (i.e. recurse over) some type F[_] which takes a type parameter. Then you have typeclass definitions for Foldable[Set], Foldable[List], Foldable[Tree], Foldable[Option], etc.
Then if you have an operation and you want it to work on any collection that can be folded, then you can just define it in terms of a generic type that has a Foldable typeclass. For instance to generically sum a collection of ints, you might do
def sum[F[_] : Foldable](ints: F[Int]): Int = ...
Now you can call sum(List(1,2,3)), sum(Set(1,2,3)), sum(Option(1)), etc...
public <T extends Collection<Integer>> T process(T collectionOfInteger) { return collectionOfInteger; }
And basically your T will be as wide as the interface/class it extends in the generic parameter.
I guess the most Java way to do that would be using Iterable:
public <Z, T extends Iterable<Z>> T process(T iterable) { return iterable; }
public <Z, T extends Iterable<Z>, R> T<R> process(T, Function<Z,R>)
change the type parameter of T<Z> to T<R> and return an instance of T<R>, but the best I can do is return an instance of Iterable<R> because I cannot define T to have a type parameter.
public <Z, T extends Collection<Z>> List<Z> process(T collectionOfInteger) { return collectionOfInteger.stream() .collect(toList()); }
[1] https://cr.openjdk.java.net/~jrose/values/parametric-vm.pdf
And the VM can specialize on any values, not just types.
[0] https://projectlombok.org/ [1] https://github.com/manifold-systems/manifold
For example, if you want to automatically create getters and setters to all private variables, why not make them public in the first place?
I hate when tools mess with IDE. What about guys using Emacs (or any other editor that does not understand Lombok)? I think generating code from IDE is fine as well as having code generated from build system distributed along with code, but having that code generated through magic of annotation processor is not as nice. I also suspect that Lombok messes my IDE on a deeper level but I have not yet a good concrete proof. Recently I am more and more frequently finding situations where Idea messes up understanding correct types of things and it takes for it some time to catch up (and sometimes reloading the file).
On the other hand I love small things like creating builder or logger. Which is to say these can be just as easily generated from a template, no annotation processor needs to be involved.
I think main feature of Java for many years were its IDEs which would allow to run accurate refactorings or always understand who is using particular piece of code, what is exact call hierarchy, etc. I feel loosing that is going to make Java much less useful for me when I try to analyze large project or run huge refactorings.
If you're in an old school "OOP" style java codebase, where each class is its own little island of encapsulated state and behavior, the coupling of the two means that strictly controlling access via getters is usually required.
Even in more "modern" java, where you do most of your programing against plain data, having Lombok attach getters still gives you some quality of Life benefits because you can use method reference rather than anonymous functions for high-order access (e.g. `things.map(MyClass::getName)` rather than `things.map(myclass -> myclass.name)`)
I'm with you on mixed Lombok feelings, though. It's great right up until its not. It fails or doesn't work in really unexpected or weird ways, and is the source endless pain when you've got other annotation based things (like dagger) which then imposes annotation processing order failures.
Because in future I may want to add some validation there, or processing, like sending events on set of a value, etc.
Properties in C# was a genius move that solves it correctly.
https://stackoverflow.com/questions/42644923/eclipse-with-lo...
It is one of those things that does not much useful, but takes away only little bit so there is no reason to fight it too much.
If I would want to use something like Java for a project, I would always pick C# which is a better Java in all aspects.
Java with IntelliJ is awesomely productive. You barely have to type anything beyond new variable / field names, everything else is generated or tab completed. Refactoring is a breeze.
That, times 'worse is better' - it's the language and toolset I already know for the types of things it's good at. I have no doubt C# is comparable or better at most things, but probably not so much so that it is worth switching.
They have a C# IDE (Rider) now, based on IntelliJ. While it was originally the only non-Windows C# IDE, I and others have switched to it from Visual Studio (which is almost as good) even on Windows.
> I have no doubt C# is comparable or better at most things, but probably not so much so that it is worth switching.
I’d say you are right. Now. 10 years or so ago (6/7/8 times) I’d have disagreed, C# avoided many of the mistakes* Java made and was able to become far more pleasurable to use, it took some time for Java to catch up again.
*: Mistakes only in hindsight
Rust is better than C
C# is better than Java
You can talk about tooling, environments, how many people use it, what you can use it for, but when it really boils down to the language there are languages that are better than others while trying to achieve the same.
I mean I use Elixir for other things than Swift or Rust or F#, Elixir is the best language for highly concurrent "message passing" systems. Some features of Elixir that I don't immediately like like it's type system unlock possibilities that no other languages have. But I don't see anything like that in Java, unless I really look around in 1993 and the only competitors are C++ and nobody-uses-it-yet Python.
My little pitch when starting a migration project in a distressed no-type language team is to make them read the code and explain it, while asking about the type of objects they use and show them when they read it's their brain parsing it with high effort. If they de-optimize and just write the types more often, it becomes much clearer longer.
You can type usually in those language but often people want to use the "proper way" as shown in ultra simplistic examples in manuals for sales pitches and end up thinking the right way to code is to write as little as possible (combined with the no-comment belief they have but don't map to "no comment because clear enough code").
That's not the case for Kotlin, that has the full weight of JetBrains behind it.
I guess that's what I see as one of the advantages of Groovy. You can do ultra rapid implementation of something with minimal code and then as it becomes more critical you increase its type safety by adding first Groovy type hints, but further along that curve, convert it fully to Java or another statically typed language. So what you describe as a problem I see as sort of, optimal workflow, and the real problem is being forced to universally choose one or the other in other languages.
If you were trying to write portable C++ code in 1996 you would get it, specially when using each OS specific C++ compiler provided by the platform vendor.
#ifdef _AIX
...
#else ifdef SGI
...
#else ifdef WINDOWS
...
#else // everything else
...
#endif
Shudder.But the other thing that Java had is the library. Compared to C++'s standard library in 1996, it was a revelation.
Things like GC, reflection, runtime loading of code, that were very familiar from more academic languages at the time.
I also did a lot of C# to help on a GUI optimization project (because doing low latency if the GUI freezes every 10 minutes isn't great), and I was really surprised by how good it was so I wouldn't disagree it works nice.
BUT I like that Java works simply in linux, I like that it didn't yet got contaminated by all the crazy constructs from elsewhere (Groovy grr), I love the tradition around the syntax (I can't stand C# quirks sometimes). I do HATE with passion the meaningless generics, and I wish we'd ditch backward compat to steal it all form C++ templates.
I enjoy more than the language syntax itself that is close to most languages I like (Javascript, C#, C++), the team spirit around it. Believe me, it's much easier to use and understand maven (or maybe gradle who starts to get dangerous in real world projects where you can't afford 2 weeks of reverse engineering a madman's build script) than it was nugget, it's easier to use IntelliJ than to receive yet another stupid email from compliance about a Visual Studio license missing, it's nicer to build a jar and run it than to go through all the kinks of exe files... I dunno I may have started from Java and got to C# and done the opposite of your journey, but while I agree C# has superior features in some aspects (but sometimes they chose mess vs safety) I just wasn't convinced it could work for something more critical where you must do things as simple as you can, as clear as you can.
And let's not even start on C++ who's superior in every conceivable way except that it encourage, or doesn't discourage, every team I ever meet to create unbearable messes they can't fix, so focused they are fixing problems we can't even imagine in Java for reasons we can't comprehend our company even accepts to finance :D
- primitives or any custom value types/structs can be used. No need for boxing or method duplication for primitives. - type information available at runtime, no need to pass 'Class<T>' parameters. - type constraint 'new' available, which means it must have a default constructor so you can do 'new T()'. No need to use reflection or pass a constructor parameter. - type constraint 'notnull' available - class-scoped compiler enforced covariance and contravariance, though I think you can get similar results with java's "? extends T" and "? super T" constraints
return new T();
is possible in C#, not in java.
Definitely not pleasant though.
I'm sure it's me but do you use it yourself and why ? Don't you get lost in the indirections in big projects "oh shit where is that thing again that auto inject itself here" ?