There’s no way that the older Java enums belong at the same tier as C++ enum classes. Java enums have all of the advantages of enum classes but you can also define methods on them, which is a big improvement in expressiveness.
Not mentioned in the video, but I think Java enums should lose some points for the Billion Dollar Mistake. It breaks the basic premise of an enum - that values of that type can only be one of the listed options. In Java, an enum can be one of the listed options... or it can be null.
They can still deserve to have points docked until it's fixed.
I think my absolute favourite his how Java wound up with an Optional<T> that can still result in NPEs. Hopefully that's a piece of the ladder they need to climb out of the billion dollar mistake hole.
There’s no way that the older Java enums belong at the same tier as C++ enum classes. Java enums have all of the advantages of enum classes but you can also define methods on them, which is a big improvement in expressiveness.
Amen.
I made a comment HERE explaining exactly how Java enums get access to benefits that both Rust and Swift (and really, most of the other languages) don't get.
We got robbed. Java should have gotten 1st place on this list. Or at the very least, should have been S-tier.
Same for Kotlin. (Paraphrasing) "There are enum classes, but maybe you want a sealed class with an external 'when' condition on the type." No, how about an enum with a function and no conditional.
Rust and Swift enums are so good that they've basically become a single preference issue for language choice. I know "muh tagged unions" at this point but it majorly influences the way I do development when I have them, perhaps more than any other feature. They give you the perfect ontology for what inherence was supposed to be: Dog is a variant of Animal, but doesn't know about the Animal abstraction. It's a sort of ad hoc inheritance.
Also despite all the Apple haters, Swift is a really good language damnit! It feels precisely designed for that "high level but not dynamic" language that Go, Java, Kotlin, C#, etc are all trying to fill. It's a pleasure to work with and I find SwiftUI to be the most fun I have doing UI development.
Also despite all the Apple haters, Swift is a really good language damnit!
I've never actually used Swift but the things I hear about it are generally good! I never picked it up because I just interpreted it as another Apple thing for Apple's walled garden, which I'm outside, hence the expectation is that they think that I and my usecases are irrelevant.
Had a similar relationship with C# for a long while too, but that seems to have escaped that self-imposed containment. MS also seems to be much more interested in general availability these days than Apple, which seems only concerned with their own paying customers. And while that is easily understandable, it also means that their stuff is much less likely to become widespread.
Because no matter how nice of a language Swift is, if the expectation is that Apple treats their own platforms as Tier 1 and everything else as Tier 9001, then the rest of us just aren't going to bother when other, also very nice languages, are easily available.
The bit about Rust/Swift enums is so true, though. It's just a very good abstraction, as are most successful adaptations of functional programming concepts into imperative languages.
I wonder when the first imperative language with GADTs gonna come out, though. All prerequisites are there lol.
hmm, I see what you mean and it is a point of annoyance, but typically what I end up doing in cases like these is make update_window a method of UiWindow.
So instead of
fn update_window(window: &Ui::Window) ->
it would be more like
impl Window{
pub fn update_window(&self) ->
}
Like one use-case I had was, I had a cache-layer that stored some hot-data that was getting cycled in and out fast. We had a meta-data field in the model that we represented as an enum called MetaData, and then whenever we needed to add a different variant of the MetaData for data consistency/serde, we would add a variant to MetaData. Then, depending on the business logic, it would call the inner method. So something like this (heavy psuedo-coding + handwaving + obfuscating actual use-case)
Swift base language is good because it was designed holistically. Two major problems are 1) compilation and iteration is still insanely slow for mega large apps, and 2) Apple still keeps bolting on ad hoc changes to the language. The "swift language group is open source" is a complete meme, because you always see Apple employees in the forum propose new evolution features and brute force approve them. Entire swift concurrency bolt on was a complete mess of a transition, because it wasn't designed as holistically as the base language
Yeah the build system ergonomics are pretty bad. Hot reloading for iOS f.ex not being an in-built library is pretty crazy. React Native has better tooling than native iOS in a lot of ways.
You forgot to mention the biggest issue. If you are doing any serious Swift work (some of the Vapor projects excluded), you are basically forced to use Xcode, and I argue it’s one of the worst pieces of software made (I am a professional iOS engineer so I spend a lot of time with it).
There’s some LSP support which is great and I love to see it, but for quick Ui iteration you’re mostly still stuck with Xcode, and most larger codebases at large corporations don’t support LSP (either due to their own weird tooling and build system ad hocs like Bazel or due to company policy etc)
I think a lot of people who dislike Apple like Swift or can acknowledge it's a good language. The problem is that it doesn't have market penetration outside of Apple.
Do you use Xcode then or how is swift development outside of it? The language seems kind of nice, only dabbled a bit in it. But compile times seems at the level of rust.
Most ML languages have great support for enums (which is actually a misnomer, good enums are discriminated unions and pattern matching). Elixir/Ocaml/F#/Elm etc
I mean, if we go into functional languages, then ADTs are, like, the lowest common denominator, considering the kind of utterly delightful invariants you can encode with GADTs or, say, dependent types (I am naturally biased, though, since the programming language I use at work is Idris 2 of all things lol)
And you're right: we were not out to win over the Lisp programmers; we were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp. Aren't you happy?
but I think we can paraphrase it about Rust as dragging C++ programmers about halfway to something in the ML family. And I think at least the Rust users are pretty happy about that.
Enum is actually a great name for the purpose it tries to achieve, i.e. to grab the attention of the average C family language dev and get them to understand discriminated unions as a generalization of a familiar concept.
Not sure I understand the question. "Enum" is an overloaded term. Technically, it's short for "enumeration" so basically C enums. But when people talk about enums in general, like in this video, they are talking about tagged unions, untagged unions and enums in the sense I just mentioned
a union is generally defining a set of "types". It has a higher cardinality than an enum which is basically an ordered set of values.
Basically an enum would be an union where all the types are subtypes and hold a single value (singletons). In fact it's a bit more involved since values are urelements and not sets themselves.
But basically a union is a bit more general than an enum. It is also not ordered in general.
Too bad they didn't include PHP. It has a enum native type and also does modern stuff like throwing an error on a match (switch) for an enum with missing values, etc.
But the error is at runtime right? While still a step up from no warning at all, not getting the warning at compile time is still a significant drawback
Yes, I mean, all of these checks are at runtime being PHP. But most people use some tool for static analysis and this is a normal case to check in being a native type to the language. I guess other languages in this list fall into this type of check too, for example Python, the difference is that you have to opt in for the check in Python to analyse and complain about not having a switch checking all values while in PHP this is enforced. I think we are looking for compiled runtime checks, only the compiled S tiers language would be the best ones like Rust.
Modern Python offloads most of the type safety to third party type-checkers, and (at least some of) these do check for exhaustiveness when matching on enums.
Is what I said wrong? You may not like that Python does it (I don't like that Python does it - my main beef is that there are many different third party type-checkers, each behaving slightly different at the even-slightly-edgy edge cases), but are you arguing that this is not their policy?
Third party tools should not be considered when discussing language pros and cons. If it is not part of the language it is not universally enforced/available, so it does not count.
Yeah, it's a bit of a problem that we use the word enum to describe rather different concepts.
In languages like Rust and I suppose Swift, they're really ADTs, like declaring a new datatype with data in Haskell. It's still possible to imagine an alternative universe where Rust omitted struct and used data rather than enum as the keyword for the thing it uses enum for today.
Python's actual enums relate more to the old C-style enums; people wanting ADTs should rather look into something like declaring separate dataclasses and then a type alias for the union.
As in, where in Haskell we'd go
data Foo = A { a :: Int, b :: String }
| B { x :: FilePath, y :: Bar }
and in Rust
enum Foo {
A {
a: isize,
b: String,
},
B {
x: PathBuf,
y: Bar,
},
}
in Python the closest is AFAIK something like
@dataclass
class A:
a: int
b: str
@dataclass
class B:
x: Path
y: Bar
type Foo = A | B
and where it actually becomes possible to do stuff like
match something_that_returns_foo():
case A(a, b): ...
case B(x, y): ...
Before watching the video -- Java (or a JVM language) better be the top of the list.
After watching the video -- 3rd place (losing only to Rust and Swift) isn't terrible, but there is some nuance here that I think the video failed to mention.
For starters, the video made it seem like the reason why Rust and Swift have better enums than Java are for 2 reasons.
Enum types can be an "alias" for a String or a number, while still retaining type safety at compile time.
I think that both of these points have both costs and benefits. And thus, isn't worth pushing Rust and Swift up a tier above Java.
In Java, our enums are homogenous -- no discriminated unions. As the video mentioned, we have an entirely different feature for when we want to model discriminated unions -- we call them sealed types.
There is a very specific reason why we separated that into 2 features, and didn't just jam them into 1 -- performance.
In both Rust and Swift, the second that your enum contains any sort of mutable state, you turn from the flat value into the discriminated union, and you take a significant performance hit. Many of the optimization strategies possible for flat values become either difficult or impossible with discriminated unions.
The reason for this performance difference is for a very simple reason -- with an enumerated set of same types, you know all the values ahead of time, but with a discriminated union, you only know all the types ahead of time.
That fact is the achille's heel. And here is an example of how it can forcefully opt you out of a critical performance optimization.
Go back to 6:20 (and 7:23 for Swift), and look at the Dead/Alive enum they made. Because they added the state, that means that any number of Alive instances may exist at any time. That means that the number of Alive entities at any given point of time is unknown. The compiler can't know this information!
Here is something pretty cool you can do when the compiler does know that information.
In Java, our enums can have all sorts of state, but the number of instances are fixed at compile time. Because of that, we have these extremely performance optimized collection classes called EnumSet and EnumMap. These are your typical set and dictionary types from any language, but they are hyper specialized for enums. And here is what I mean.
For EnumSet, the set denotes presence of absence of a value by literally using a long integer type, and flipping the bits to represent presence or absence. It literally uses the index of the enum value, then flips the corresponding bits. The same logic is used in the EnumMap.
This is terrifyingly fast, and is easily the fastest collection classes in the entirety of the JDK (save for like Set.of(1, 2), which is literally just an alias for Pair lol).
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
By having the 2 features separate, Java got access to a performance optimization.
By allowing enums to be aliases to string/Number and also allowing enums to be discriminated unions, you force your users to make a performance choice when they want to add state to their enum. Java doesn't. And that's why I don't think the logic for Java being A tier is as clear cut as the video makes it out to be. Imo, Java should either be S tier, or the other 2 should be A tier as well.
EDIT -- So, everything I said here was true, but I still lost the argument. Explanation below.
My argument basically boiled down to this -- because Rust (and Swift, I won't keep repeating this) chose to combine both "Enumerated Values" and "Discriminated Unions" into a single feature called enum, then Rust has to accept some tradeoffs when designing their own EnumSet.
My argument was banking on the assumption that, if Rust wanted to maintain true 1-to-1 performance with Java, then the Rust solution would be a fairly ugly bit of code. Hence my comment about "difficult to impossible".
What I didn't account for was Rust Macros.
Yes, if you want feature and performance parity with Java Enums and Java EnumSet, you have to write a LOT of fairly ugly Rust code.
But since Rust has Macros, then only one (unfortunate) Rust coder has to write that implementation. From there, another (even more unfortunate) Rust coder must write a Macro that generates that implementation.
And from there, all other Rust developers can just use the Macro. That was the point that defeated my argument.
There is something to be said about maintainability and level of effort for maintainability. But, with the realization that Rust Macros allow Rust to achieve feature and performance parity with Java, then I accept Java receiving A-tier for this.
Those macros allow Rust to model pretty much any ugly code they want in a fairly clean wrapper, and then other Rust developers never have to interact with those internals. Doing the same in Java is possible (via annotations), but extremely difficult. If that is the basis for why Java deserves A-tier and Rust gets S-tier, I accept that.
I can at least claim that all of my points are still correct, even if they lacked context.
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
That's technically true, but wildly misleading. Java can make these optimizations when enums have state at the cost of only supporting global state. Sure, this might be very performant:
enum Player {
ALIVE,
DEAD,
public int health;
}
But it's also utterly useless if you ever have more than one player. I'd even argue that global mutable state hidden inside of enums is an anti-feature.
EnumSet in java is just a bit vector, you can easily code it in rust, though it doesn't come with the standard library.
The fact that a rust enum can be a classic enum and a discriminated union is irrelevant as the compiler can apply different optimizations to both.
I think you are confused about what enum "state" actually means. In java state is just an attached constant to the enum that is why you can use it in a EnumSet. In rust state is dynamic, if you want to do the same in java you need to use classes which of course don't work with EnumSet.
3 I think you are confused about what enum "state" actually means. In java state is just an attached constant to the enum that is why you can use it in a EnumSet. In rust state is dynamic, if you want to do the same in java you need to use classes which of course don't work with EnumSet.
This statement is incorrect.
Consider the following Java code.
enum ChronoTriggerCharacter
{
Chrono(100, 90, 80),
Marle(50, 60, 70),
//more characters
;
public int hp; //MUTABLE
public final int attack; //IMMUTABLE
public final int defense; //IMMUTABLE
ChronoTriggerCharacter(int hp, int attack, int defense)
{
this.hp = hp;
this.attack = attack;
this.defense = defense;
}
public void receiveDamage(int damage)
{
this.hp -= damage;
}
}
(ignore the public modifier, I am making a point here)
I can mutate each of these characters HP. I am not limited to immutable data. These are instances of a class, and with the minor exception of class level generics, anything a class can do, a Java enum value can do.
That means mutable state, methods that mutate that mutable state (and those methods can exist on the enum itself), etc.
I can do this.
Chrono.receiveDamage(10);
And then Chrono's hp will now be 90.
And there will only ever be one single instance of Chrono, ever.
So with that in mind, let's review your points 1 and 2.
For point 1, how would I attach mutable state to my enum in Rust, while also being able to use a bit vector? That's my point -- you would have to separate it out and do something along the lines having that state held somewhere else. With Java, this is just plain OOP.
And for point 2, my argument has been that the discriminated union will not be able to perform as well as the "pure enum", and that Java allows "pure enums" to have mutable state, allowing you to get the "best of both worlds", performance wise.
But someone else has already prompted me for a bench mark. I added a RemindMe somewhere. Ctrl+F and you can find it. That should be the real test.
Rust and Swift don't need this optimization because enums there are value types, not reference types.
I disagree.
For example, believe it or not, attempting the same feature in Rust would actually use MORE memory and have LESS performance than Java's!
The reason for this is that, regardless of the fact that the enums themselves are reference types, their inclusion in a set is denoted with a long, which is a value type (a primitive, really) in Java.
So, being a value type still doesn't help you achieve the same speed here because you still haven't gotten past the core problem -- Rust and Swift opted out of guaranteeing the number of instances out there.
So, instead of using a long, you all have to either use hashes or the values themselves, which is slower! After all, neither your hashes nor your values use 1 bit. Java's inclusion index uses 1 bit.
Hence, Java's version is faster AND uses less memory.
I might be missing something but I believe Rust's enums can do something similar. The number of discriminants is known at compile time so, even though the language's stdlib itself doesn't provide it, you could write your own EnumSet and EnumMap. People tend not to do that since pattern matching is enough most of the time.
I mean rust doesnt do this by default, but technically java doesnt either since you need to explicitly use EnumSet/EnumMap.
I dont see a reason why it's not possible in rust though. A quick google search shows 2 crates that seem to work the same way as the java ones (enumset and enum_map)
Rust and Swift opted out of guaranteeing the number of instances out there
But Rust does know the total number of variants for each enum, which is what matters for EnumSet and EnumMap afaict.
Niche optimization can also make it possible to know the full number of possible values, even if the enum contains a value. For example,
enum T {
A(bool),
B,
}
Has a size of 1 byte and, since Rust guarantees that bools are either 0 or 1, B can just be any other value. it's effectively treated as a 3-variant flat enum. If A contained a different enum with 255 variants, it would still be 1 byte in size.
With pattern matching, you can also intentionally ignore the contained value and only match on the discriminant. That, in and of itself, sortof removes the need for enum_map to be a first-class entity. Effectively, the discriminant is the key and the contents are the value. You can just write the match statement and the compiler will optimize to a jump table or conditional move in many cases.
This is terrifyingly fast, and is easily the fastest collection classes in the entirety of the JDK (save for like Set.of(1, 2), which is literally just an alias for Pair lol).
This needs some data for backing up because I have a feeling that combined with the JVM overhead it will not be able to match Rust.
This needs some data for backing up because I have a feeling that combined with the JVM overhead it will not be able to match Rust.
The quote you replied to said "fastest in the JDK", but it sounds like you are asking me to defend faster than Rust?
I'll take on both points.
(fair warning, it's bed time for me, so I'll be a few hours before my next response)
Fastest in the JDK
First, let's review the implementation.
An enum is an ordered set of values, all of the same type. And when using an EnumSet, because of the ordered nature of enums, one can denote inclusion or exclusion in the EnumSet by simply using a long or long[] (for when >64 enum values). You use the index of the enum value to decide which bit on the long/[] to flip. 1 means included, 0 means excluded.
So modifying inclusion or exclusion is literally just a bit flip. That's a single assembly operation. And when doing your typical Discrete math Union/Intersection/Difference between 2 sets, that's literally just an AND/OR/NOT between the 2 long or long[]. That's about as fast as the computer can get.
So, do I need to provide more evidence than this that this is the fastest option in the JDK?
The literal only one that beats it is Java's Set12 class, which is a set that can literally only hold 2 values lololol. It's another hyper optimization for when you have a set of only 2 values. But if you ever need to go more than 2 values, you are back to an array of addresses, which means that you are back to being outperformed by EnumSet. I just didn't include Set12 because I don't think a set that can literally only hold 2 values is worth mentioning lol.
Faster than Rust
I'm happy to type up a benchmark for this, but I fear that I would be unfair to Rust just due to my ignorance. If that works for you, lmk, then I'll start work on it right away.
But remember, in Java, when adding or removing enum values into a Set, you are just doing raw bit flips and AND/OR/NOT's. You aren't touching any of the Java overhead at all because all of it has been compiled away to a bunch of long and long[] instances. That's the power of the JIT -- it boils down to just a bunch of long after it gets compiled at runtime.
And Rust, by definition of using Discriminated Unions, can't do the same -- it has an unknown number of instances, so how can it use this indexing strategy when instances are being created and deleted dynamically throughout the program's lifecycle? Java's are created on classload, then done.
But like I said, if that's not enough, I'll give a benchmark a shot and post it here. But lmk if that is needed.
I agree you should do a benchmark, but you should benchmark the capabilities of enums in both languages and their equivalent forms in the other. So, do this EnumSet in both, Java-style state in both, and Rust-style state in both.
I'd be willing to help with the Rust side, though I don't really know Java.
I agree you should do a benchmark, but you should benchmark the capabilities of enums in both languages and their equivalent forms in the other. So, do this EnumSet in both, Java-style state in both, and Rust-style state in both.
Hah, I signed myself up for more work than I anticipated.
I'll pull the old "80/20", and get something useful out by the deadline, then request more time to give a proper, exhaustive analysis. I wildly underestimated my inexperience in benchmarking lololol.
I'd be willing to help with the Rust side, though I don't really know Java.
I would appreciate it. But I am going to post my initial deadline findings, get those thoroughly scrutinized by both the /r/rust and the /r/java communities, and then use that feedback to build a proper benchmark. If you want to provide support, watch out for those posts and reply there.
Rust has bit sets though. I think your post was enlightening from the Java angle but you're misinformed on Rust.
The difference is that Rust doesn't have a bit set in the standard library which is where I think your confusion comes from. Rust's standard library is very small and I personally don't want it to be larger. However, bit sets are common and common in Rust too. It's a systems language afterall.
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
You are wrong.
enum X { A, B, C }
println!(
"{} {} {} {} {} {}",
std::mem::size_of::<std::num::NonZeroU8>(),
std::mem::size_of::<Option<std::num::NonZeroU8>>(),
std::mem::size_of::<X>(),
std::mem::size_of::<Option<X>>(),
std::mem::size_of::<&u8>(),
std::mem::size_of::<Option<&u8>>(),
);
// 1 1 1 1 8 8
The reason for this performance difference is for a very simple reason -- with an enumerated set of same types, you know all the values ahead of time, but with a discriminated union, you only know all the types ahead of time.
The type theory says that type is sum of all possible values so if you know type you already know all values.
added:
Maybe I misunderstood you because the Java types you are talking about are bit masks. Specifically in Rust they are not part of the standard library but there are many third-party implementations of them. In any case this is a unique advantage for Java (although the implementation can be quite good).
Because of that, we have these extremely performance optimized collection classes called EnumSet
added:
I checked the information about EnumSet... it's just a wrapper around bitwise operations. It's a different type that has nothing to do with enum because enums should only be in one state. And it's been around in all programming languages since ancient times. Although a high-level abstraction on top of that is zero-cost is certainly nice (I often use the bitflags package in Rust for example).
Let me start by saying, one painful part about talking about enums in Java vs Rust is that we use literally the opposite terminology to describe the same things. So we can easily talk past each other.
Rather than trying that again, let me give a Java code example.
enum ChronoTriggerCharacter
{
Chrono(100, 90, 80),
Marle(50, 60, 70),
//more characters
;
public int hp; //MUTABLE
public final int attack; //IMMUTABLE
public final int defense; //IMMUTABLE
ChronoTriggerCharacter(int hp, int attack, int defense)
{
this.hp = hp;
this.attack = attack;
this.defense = defense;
}
public void receiveDamage(int damage)
{
this.hp -= damage;
}
}
Then I can do this.
Chrono.receiveDamage(10);
Chrono will now have 90 hp.
With that example in place, let me try and clarify my points.
When working with an EnumSet in Java, each index corresponds to each value of the enum. Meaning, I have a single bit in my long for Chrono, another bit for Marle, etc. If I get past 64 enum values, it switches from a long to a long[].
And these are instances of a class. Meaning, anything that a Java class can do, these can do too (with the exception of a very specific form of generics). So I can have arbitrary, mutable state, methods, static fields and methods, each instance can have their own individual fields that are not shared by the other enum values. Doesn't matter. I can add all of that, and my performance characteristics will not change wrt EnumSet and EnumMap, the only xception being that 64 values long vs long[] thing I said earlier.
This is probably where the confusion comes from, because in Rust, you all enumerate the types, whereas in Java, we enumerate the instances of a type. That is why I am saying that Rust can't have this -- they are enumerating something entirely different than we are.
And of course, Java also has a separtae language feature to enumerate the types -- we call those sealed types. That is the 1-to-1 parallel to Rust enums.
I would not approve this PR. First it's not thread-safe, but more importantly, even though we can change the state of an Enum, it's not idiomatic Java. I've been using Java since it first came out, I don't remember ever coming across an enum with mutable state.
First. Enums in Rust is sum types what's technically have sense because enums in C are sum type without state. EnumSet in Java isn't sum type, it is bitflag. I hope you understand how number represented in binary, so byte is 0b0000_0000. We associate each constant with some bit and use very effective logical cpu instruction:
const READ = 1;
const WRITE = 2;
const DEL = 4;
var permission = READ; // Only first flag is active
permission |= WRITE; // Up second byte/flag
if (permission & DEL) { ... } // false because third byte/flag is down
This is the fastest code there can be. Java associates enum variants with flags, it's nice. But this exists in any language (somewhere abstractions are written for this, somewhere - not). However, this is an elementary code at the level of adding two numbers.
Second. EnumSet has nothing to do with the code you wrote.
I would model your code like this. This is a product type because all possible states can be described as a multiplication of the tag and the number of hp.
At a low level, the size of such an object will be equal to u32 + the minimum possible size for the tag + alignment. Instead of using a tag, you can simply make a structure with all the fields.
Also note that unsigned numbers are used that can perform correct subtraction without overflow.
Summary:
Both of your examples are very distantly related to enum. You don't understand the difference between a sum types and a product types. You are trying to present basic bitwise operations that exist in all languages as something unique to Java.
While that is a cool optimization, it does not require all enums to be "named constants" like in Java. In fact, there is a library in Rust that does pretty much the same thing as Java's EnumSet: https://docs.rs/enumset/latest/enumset/
This optimization just requires the ability to convert an enum value to an integer and back. For the Rust enumset library above, it achieves this by basically disallowing enums with data from being used with EnumSets. However, it should be possible to implement a mechanism to map enums to integers even when the enum contains data, provided the total number of possible values (the type's "inhabitants") is limited.
For the Rust enumset library above, it achieves this by basically disallowing enums with data from being used with EnumSets.
Yeah, that is sort of my point -- you have to give up the ability to add state directly to your enum.
However, it should be possible to implement a mechanism to map enums to integers even when the enum contains data, provided the total number of possible values (the type's "inhabitants") is limited.
Could you explain this in more detail? I feel like I get it, but I don't want to assume.
I'll say optimizations aside: strictly speaking the sealed class strategy is more flexible than rust/swift's approach.
With sealed classes your variants are actual distinct types. They can also be part of multiple sealed hierarchies at once and the sealed hierarchies can be trees more than one level deep.
So even in that dimension there is an argument for it being "better" (at the very least more expressive, if higher ceremony) than rust or swift
Sorry I fail to see how this is better than Rust's or Ocaml's enums. All languages using sealed classes missed the spot on enums the first time and had to add yet another feature to make them more usable. So the only sure thing is that the language got more awkward. Performance wise, they are most probably in the same ballpark. I haven't checked though.
From a developer's perspective I wouldn't say this is a win. I also fail to see your point about distinct types. In a language with true ADTs, enums values are just values and these can have any type. And you can also add methods on Rust's enums..
From my experience, proper ADT support in any language is a must have as it improves both the quality of your domain modeling as well as it's ease of composition.
I should mention that support for proper matching allows to check patterns at arbitrary nesting depth, and detect both unhandled cases (with examples) and shadowed cases.
The ML language family has had the best enums for decades.
I'll say optimizations aside: strictly speaking the sealed class strategy is more flexible than rust/swift's approach.
Oh, agreed. That's why I think Java's approach is better -- you choose your flexibility, and the flexibility you give up on turns into performance gains. It's great.
With sealed classes your variants are actual distinct types. They can also be part of multiple sealed hierarchies at once and the sealed hierarchies can be trees more than one level deep.
So even in that dimension there is an argument for it being "better" (at the very least more expressive, if higher ceremony) than rust or swift
Are rust and swift not able to nest their own sealed hierarchies? I thought they were, for some reason.
Are rust and swift not able to nest their own sealed hierarchies? I thought they were, for some reason.
Rust's enums can contain other enums to make nested hierarchies. But since they are not proper subtypes, child types can't be automatically converted to parent types. You have to manually implement and call conversion functions (though they are standardized in Rust so the libraries work together).
sealed classes are probably better in a lot of ways, however they require having inheritance and type narrowing, so language differences make it impossible to have them in Rust a bit too early (as the language pretty much doesn't have type matching/narrowing at all)
Yeah, Java Enums are one of the very few times where Java was so far ahead of the curve compared to everyone else.
Back when Java Enums first came out (2005!), there was nothing else like it. And even now, 20 years later, I'd say that the other languages have merely caught up, or provided decent enum alternatives. But none have surpassed it. (unless you are a JVM language, but JVM languages literally compile down to Java bytecode lol, so I'll call that a point for Java)
Java is a fantastic language nowadays. Java 25 came out 3 weeks ago, and everything since Java 17 has been stellar. It's my favorite language of all time and Java enums are my favorite programming language feature of all time (in case the 5000 character essay didn't make that clear lol).
Java enums are my favorite programming language feature of all time
I still battle coworkers who want to use an interface with constants in it, like it is still the dark ages of pre-java 1.5. Java enums are so powerful, they are an underused language feature (at least by my coworkers).
For EnumSet, the set denotes presence of absence of a value by literally using a long integer type, and flipping the bits to represent presence or absence
Wow, Java has bitmasks? What a revolutionary feature. If only Rust had that. /s
Wow, Java has bitmasks? What a revolutionary feature. If only Rust had that. /s
The real trick is not the bitmasks, but being able to know at compile time exactly how many instances are ever going to be created (and thus, how many bits the bitmask needs).
That is the powerful part because we can skip an entire class of validation checks -- that is the performance benefit that Rust can't get, as they chose to enumerate their types rather than their instances of the types.
It took me a while to understand that the author of the message about how cool Java is doesn't understand the difference between an enums, sum types and bitmask at all.
It's actually scary how many upvotes his comment received.
In fact, abstraction over bitwise operations is useful and convenient, but it simply has to be zero-cost.
And to further drive the point home, let me point out another performance optimization that Java got access to because they opted out of including points 1 and 2 directly into their enums.
EnumSet and EnumMap aren't just the fastest Collection classes in the entire JDK, but they are also the lightest. They use the least amount of memory compared to any other Collection class in the entire JDK. Again, it is literally a single bit per enum value lol.
If I have an enum with 10 values, then my EnumSet only needs 10 bits to denote them lol. Obviously, the overhead of classes and the arrays within them adds some tax to that number, but each of those are one time payments.
And that overhead payment is the exact same for every single enum and EnumSet out there (until your enum has more than 64 values -- then it switches from a long to a long[], but again -- a one time payment).
This is stuff that Rust and Swift can't have access to (with state) because they made the choice to put discriminated unions into their enums.
Further reason why I think the logic behind Java being A tier is wrong. It should at least be S tier alongside Rust and Swift. At least then, we can treat it like what it actually is -- a tradeoff. And one that isn't clearly better, one way or the other.
EnumSet and EnumMap aren't just the fastest Collection classes in the entire JDK, but they are also the lightest. They use the least amount of memory compared to any other Collection class in the entire JDK. Again, it is literally a single bit per enum value lol.
There's a solution that the game development scene came up with that needs no storage in the object itself at all, and has only some overhead when changing the state of the object:
Imagine you have a collection of objects that can harm the player, e.g. enemies and bullets in a shoot 'em up game. Instead of storing a boolean "harmful" or an enum "EntityType" in the object, you create object pools called "ActiveEnemies" and "ActiveBullets", and their inactive counterparts. The objects are basically categorized by their address. This eliminates lots of code for loading and branching on object fields, makes the game state smaller, and removes the potential of cache and branch misses. When the object state changes, the objects need to be moved from one pool to another, but that happens relatively rarely (over several seconds instead of frames).
I don’t necessarily disagree with your point, but I have to ask about the phrasing you use when talking about Java (emphasis mine):
In Java, our enums are homogenous -- no discriminated unions. As the video mentioned, we have an entirely different feature for when we want to model discriminated unions -- we call them sealed types.
Are you a JDK developer or designer of Java? Why do you phrase it as “our” and “we” when talking about Java? And then in one of your replies regarding Rust, you talk about its design choices as “yours.”
So, instead of using a long, you all have to either use hashes or the values themselves, which is slower! After all, neither your hashes nor your values use 1 bit. Java's inclusion index uses 1 bit.
Why are you framing it as “us vs. them”? There aren’t any teams for people using one language or the other. They’re all just tools to accomplish the goal of building software. Anything else is tribalism
I don’t necessarily disagree with your point, but I have to ask about the phrasing you use when talking about Java
Guilty on all accounts.
This is kind of a perfect storm of a couple things, which I'll list in a sec. But you are 100% correct -- my word choice is needlessly incendiary, and I will stop that immediately.
Are you a JDK developer or designer of Java?
I'm not officially staffed, no, but I have been contributing to the JDK for a couple of years now. Certainly nothing impressive, but enough that this is a matter of pride, in some ways.
But to enumerate my reasons.
This video touches on enums, a tiny little niche in programming that I actually have a lot of background on, at least in Java. A good chunk of my contributions were related to enums, so it probably led me to using "us" in a lot of cases.
Enums are probably the single, solitary feature that Java has that it can say that it literally does better than any other language -- current or past. People (rightfully) criticize Java for getting so much of its design wrong in the past, and they also (rightfully) measure its recent developments to be good/great, but not quite as good as other languages do it. So, it's easy to write this off as another "pretty good, but not quite", but that's just not the case.
Anyways, thanks for the comment, this was a helpful speed bump.
I’m in two minds on TypeScript being in C tier. It’s fair it is a mess, as the main problem with TS enums is enum. Using type has always ended up being my goto. They just work better.
On a clean and well maintained code base it’s easily been the best enum system I’ve ever used. And my day is in Rust (in S tier).
However people can also create Frankenstein type abominations that are crimes against humanity. TypeScript can be the C++ of type systems.
Similarly anyone who has had to Syn tokens would not put Rust enums in S-tier. You can easily end up in a sea of enum match blocks endlessly scrolling off the page … =>
Well, TBH Perl is such an unreadable language that it's no longer a matter of personal taste. It's good at one very specific thing (everything stringy) but that's not worth the pain. To add insult to injury, it has Python levels of performance, and the bar doesn't get lower than that.
In earnest, have you tried, or are you just referring to the meme? By far the majority of Perl code I’ve read is bad because it’s treated as “Python with funny syntax” or “Bash but less awful”, instead of actually taking meaningful advantage of the tool, let alone being overly clever.
I’m no great fan of dynamic languages, but in particular I find the sigils are useful to prevent or fix a lot of basic errors caused by dynamic typing, because they’re essentially explicitly typed dereferencing operators.
bash++ is generally how I've encountered it in the wild / at work. Especially since a lot of the scripts are somewhat old, so they might have a -w in their shebang but no use strict;, certainly nothing like use 5.040; or whatever is required to get at the more modern perl features (like declaring arguments to subroutines in the way you'd do in basically any other ALGOL-ish language).
The sigils aren't that bad; certainly they make a bit more sense than in languages that just have $. The always-loaded and easily-available regexes are also a really neat part of the language (and PCRE is still really the only regex syntax I know, after Perl was the first language I learned, with the Llama book).
But I think there are many reasons why perl became less relevant, and one of them is that it permits the absolute turgid mess that a bash++ script has a tendency to become.
So we wind up in this situation where
the perl fans rate the language based on how good it can be, if the developer hangs out in /r/perl and has all the right linters and CI tools and whatnot,
the memers clown on the language because it was the butt of jokes decades ago (i.e. it's always appropriate to respond to one of those with "OK boomer"),
but the complainers rate it based on the stuff we were actually exposed to, especially at work, and likely to a large part the stuff we wrote ourselves.
Even if Perl discussions have been tainted by memers for decades, the complaints and jokes actually come from a place, just like the AbstractBeanIFactoryFactory jokes about Java.
For sure, it’s truthy if it ain’t true, just a tad old. Then again it’s very funny to hear someone call Perl “line noise” when not only have they never used Perl, they’ve never even seen line noise!
When it comes to language features in a codebase, everything that’s possible and allowed is inevitable. With hindsight, nowadays when I have a choice, I go for languages like Haskell, Mercury, or Rust, where you can still write utter scunge if you want, but more of the yucky parts are opt-in.
If you compare the Perl code I find at work to the code I write, it’s night and day, but the only real difference is that one is mainly colloquial use of a second language to get shit done, while the other is native fluency in an educated formal register. I’m a long-time user who reads everything — perldocs, camel book, Perlmonks threads, &c., so of course my code looks different. I’m not here to belittle the older code, but I can at least make newer code friendlier to the next non-native speaker who has to deal with it.
Here's a video about enums. Let's evaluate a couple of languages that don't support enums and will obviously rank lower, and ignore others that do support enums in the top 10 of most used ones.
Well now I need to remember to check UE and see what it does, decently sure it fixes some of those cpp flaws but I wasn't rigorously testing it or anything
Talking about C++ enums without ever mentioning C is a fail. The basic C++ enums are an inherited feature from C. They should have been discussed on their own.
Enum class is a C++ feature, and while it’s an incremental improvement I wouldn’t put them in the same tier.
What is this nonsense, enums achieved perfection in C, everything else is bloat and syntatic "sugar" over datatypes. At the end of the day they are not enums anymore or inferior C enum alternatives.
I don't see that much of a difference. What the union keyword is doing just seems to be slightly less work than writing an enum for Pet that contains the Cat and Dog variants. It's cool and should belong in the same high tier as Rust and Swift but it doesn't seem better enough to be S tier.
Had a prof that required us to build our Datastructure programs in ADA. Major pain at the time. Little did I know I would actually enjoy it years later.
Interesting comparison. I do wish Swift would get wider adoption outside of Apple. My biggest problem with Rust is that it reminds me of what the world went through with C++ and the kludge that turned into. From my perspective it looks like Rust is turning into another kitchen sink language that is problematic to use with the corresponding difficult syntax to support all of that functionality.
That said these days my programming needs are mostly settled with Python. If Mojo ever solidifies it might give Swift, Rust, Java and a number of other languages something to chase after. Python currently offers me the best choice for my needs, mostly due to clear code that is actually readable a year later.
153
u/rysto32 Oct 07 '25
There’s no way that the older Java enums belong at the same tier as C++ enum classes. Java enums have all of the advantages of enum classes but you can also define methods on them, which is a big improvement in expressiveness.
29
u/deejeycris Oct 07 '25
In the first 30 seconds: "Javascript doesn't have enums, even though it's a reserved keyword". Oh god
58
u/bennett-dev Oct 07 '25 edited Oct 07 '25
Rust and Swift enums are so good that they've basically become a single preference issue for language choice. I know "muh tagged unions" at this point but it majorly influences the way I do development when I have them, perhaps more than any other feature. They give you the perfect ontology for what inherence was supposed to be: Dog is a variant of Animal, but doesn't know about the Animal abstraction. It's a sort of ad hoc inheritance.
Also despite all the Apple haters, Swift is a really good language damnit! It feels precisely designed for that "high level but not dynamic" language that Go, Java, Kotlin, C#, etc are all trying to fill. It's a pleasure to work with and I find SwiftUI to be the most fun I have doing UI development.
36
u/teerre Oct 07 '25
Most ML languages have great support for enums (which is actually a misnomer, good enums are discriminated unions and pattern matching). Elixir/Ocaml/F#/Elm etc
21
u/melokoton Oct 07 '25
Too bad they didn't include PHP. It has a enum native type and also does modern stuff like throwing an error on a match (switch) for an enum with missing values, etc.
30
u/somebodddy Oct 06 '25
Modern Python offloads most of the type safety to third party type-checkers, and (at least some of) these do check for exhaustiveness when
matching on enums.13
u/boboguitar Oct 07 '25
I just skipped to the end to make sure swift is way up there. Enums are really cool in that language.
36
u/davidalayachew Oct 07 '25 edited Nov 03 '25
Before watching the video -- Java (or a JVM language) better be the top of the list.
After watching the video -- 3rd place (losing only to Rust and Swift) isn't terrible, but there is some nuance here that I think the video failed to mention.
For starters, the video made it seem like the reason why Rust and Swift have better enums than Java are for 2 reasons.
I think that both of these points have both costs and benefits. And thus, isn't worth pushing Rust and Swift up a tier above Java.
In Java, our enums are homogenous -- no discriminated unions. As the video mentioned, we have an entirely different feature for when we want to model discriminated unions -- we call them sealed types.
There is a very specific reason why we separated that into 2 features, and didn't just jam them into 1 -- performance.
In both Rust and Swift, the second that your enum contains any sort of mutable state, you turn from the flat value into the discriminated union, and you take a significant performance hit. Many of the optimization strategies possible for flat values become either difficult or impossible with discriminated unions.
The reason for this performance difference is for a very simple reason -- with an enumerated set of same types, you know all the values ahead of time, but with a discriminated union, you only know all the types ahead of time.
That fact is the achille's heel. And here is an example of how it can forcefully opt you out of a critical performance optimization.
Go back to 6:20 (and 7:23 for Swift), and look at the Dead/Alive enum they made. Because they added the state, that means that any number of Alive instances may exist at any time. That means that the number of
Aliveentities at any given point of time is unknown. The compiler can't know this information!Here is something pretty cool you can do when the compiler does know that information.
In Java, our enums can have all sorts of state, but the number of instances are fixed at compile time. Because of that, we have these extremely performance optimized collection classes called EnumSet and EnumMap. These are your typical set and dictionary types from any language, but they are hyper specialized for enums. And here is what I mean.
For EnumSet, the set denotes presence of absence of a value by literally using a
longinteger type, and flipping the bits to represent presence or absence. It literally uses the index of the enum value, then flips the corresponding bits. The same logic is used in the EnumMap.This is terrifyingly fast, and is easily the fastest collection classes in the entirety of the JDK (save for like Set.of(1, 2), which is literally just an alias for Pair lol).
Rust and Swift can't make the same optimizations if their enums have state. Java can, even if there is state.
By having the 2 features separate, Java got access to a performance optimization.
By allowing enums to be aliases to string/Number and also allowing enums to be discriminated unions, you force your users to make a performance choice when they want to add state to their enum. Java doesn't. And that's why I don't think the logic for Java being A tier is as clear cut as the video makes it out to be. Imo, Java should either be S tier, or the other 2 should be A tier as well.
EDIT -- So, everything I said here was true, but I still lost the argument. Explanation below.
My argument basically boiled down to this -- because Rust (and Swift, I won't keep repeating this) chose to combine both "Enumerated Values" and "Discriminated Unions" into a single feature called
enum, then Rust has to accept some tradeoffs when designing their own EnumSet.My argument was banking on the assumption that, if Rust wanted to maintain true 1-to-1 performance with Java, then the Rust solution would be a fairly ugly bit of code. Hence my comment about "difficult to impossible".
What I didn't account for was Rust Macros.
Yes, if you want feature and performance parity with Java Enums and Java EnumSet, you have to write a LOT of fairly ugly Rust code.
But since Rust has Macros, then only one (unfortunate) Rust coder has to write that implementation. From there, another (even more unfortunate) Rust coder must write a Macro that generates that implementation.
And from there, all other Rust developers can just use the Macro. That was the point that defeated my argument.
There is something to be said about maintainability and level of effort for maintainability. But, with the realization that Rust Macros allow Rust to achieve feature and performance parity with Java, then I accept Java receiving A-tier for this.
Those macros allow Rust to model pretty much any ugly code they want in a fairly clean wrapper, and then other Rust developers never have to interact with those internals. Doing the same in Java is possible (via annotations), but extremely difficult. If that is the basis for why Java deserves A-tier and Rust gets S-tier, I accept that.
I can at least claim that all of my points are still correct, even if they lacked context.
3
u/faze_fazebook Oct 07 '25
Exhaustive and non exhaustive switch statements should both be possible without compiler / linter rules.
3
u/cjthomp Oct 07 '25
I am so tired of seeing the words "tier list."
2
u/jl2352 Oct 07 '25
I’m in two minds on TypeScript being in C tier. It’s fair it is a mess, as the main problem with TS enums is
enum. Usingtypehas always ended up being my goto. They just work better.On a clean and well maintained code base it’s easily been the best enum system I’ve ever used. And my day is in Rust (in S tier).
However people can also create Frankenstein
typeabominations that are crimes against humanity. TypeScript can be the C++ of type systems.Similarly anyone who has had to Syn tokens would not put Rust enums in S-tier. You can easily end up in a sea of enum match blocks endlessly scrolling off the page … =>
2
u/mestar12345 Oct 07 '25 edited Oct 07 '25
In F# you don't tag your data structures with enums to which kind of data they are, you put your whole data inside your enums.
So instead of
(or something more complex, like an class hierarchy for the same purpose)
you do:
In other words, they can replace the whole class inheritance tree.
5
u/roXplosion Oct 06 '25
No perl or Fortran?
2
u/Aridez Oct 07 '25
Here's a video about enums. Let's evaluate a couple of languages that don't support enums and will obviously rank lower, and ignore others that do support enums in the top 10 of most used ones.
What
1
u/Nchi Oct 07 '25
Well now I need to remember to check UE and see what it does, decently sure it fixes some of those cpp flaws but I wasn't rigorously testing it or anything
1
u/Abbat0r Oct 07 '25
Talking about C++ enums without ever mentioning C is a fail. The basic C++ enums are an inherited feature from C. They should have been discussed on their own.
Enum class is a C++ feature, and while it’s an incremental improvement I wouldn’t put them in the same tier.
1
u/mpanase Oct 07 '25
yep
agreed
1
u/_Krayorn_ Oct 08 '25
No PHP :(
1
u/maruseron Oct 08 '25
"More on that later" - talking about Java's sealed types for ADTs. Spoiler: there wasn't more on it later.
0
u/snrcambridge Oct 07 '25
Dart - s tier. You can create simple enums that does what it says on the tin, but you can also add extensions. ‘’’dart enum Dir { left right }
extension on Dir { Icon get icon { switch(this){ case left: return Icons.arrowLeft; … } } ‘’’
-2
u/One_Being7941 Oct 07 '25
HAHA C# doesn't make the list.
-18
u/Snoo_57113 Oct 07 '25
What is this nonsense, enums achieved perfection in C, everything else is bloat and syntatic "sugar" over datatypes. At the end of the day they are not enums anymore or inferior C enum alternatives.
0
u/[deleted] Oct 07 '25
[deleted] — view deleted comment
177
u/[deleted] Oct 07 '25
[removed] — view removed comment