Hacker News new | ask | show | jobs
by yisonPylkita 1168 days ago
Option<> type works well in Rust because compiler enforces its proper usage. In dynamic languages programmers are on their own
2 comments

> because compiler enforces its proper usage

For languages where the compiler doesn’t help, is there any benefit? I’ve seen Option in Java projects where it just seems to add one more layer of could-be-null.

Java's optionals are incredibly half-baked IMO, and I say this as someone who is generally quite pro-Java.

They make the code slower, harder to read and don't really solve any problem.

Yeah, in particular since you cannot have Some(null) which is just very bad design because it makes interaction with code that uses null impossible (or unreliable).

And syntactically, it's not a pleasure to use, but that's more a fault of Java being so verbose and limited in terms of the typesystem, not a fault of the Optional type.

I don't think amending the type system (or using the existing type system) would make sense for Java.

I think either a null-delegating operator (like C#'s foo.?bar ); or a variable modifier (a bit like 'final') that doesn't permit nulls would make far more sense in the context of the language at large. In fact, the approach is commonly enforced through annotations and static analysis. Built-in support for the construct would be very beneficial.

Yeah, I agree.
The rule in Java, enforced by the programmer, not the compiler, is that you never assign an Optional to null. If a method returns Optional, you're free to assume it will never return null. If it does, you should track down and publicly shame the author of such monstrosity.
"If you do that, ideally, a small gnome climbs out the back of the computer and hits the developer with a mallet."

(various bits of perl IRC have adopted the mallet gnome as an idiom over the years and it seems to convey the "please don't" point without being overly combative ;)

There's always benefit, as long as programmers stick to it. Compilers and linters help a lot, but it's not impossible to do without them, just requires more discipline and effort. And you don't have that "it compiles" guarantee that makes you feel warm and fuzzy inside.
One important property of options is that they don't get flattened when nested. None and Some(None) are different.
If anyone wondering what that means for "optional ifs":

        if let Some(new_variable) = method_that_returns_optional_value {
            println!("value: {new_variable}")
        } else {
            println!("{new_variable} is not in scope, this wont't compile");
        }
I find it powerful. "if-let" and "while-let" are part of the language. OTOH rustaceans are happy with and constantly reasoning (constantly fighting the borrowchecker?) about scopes and if a variable / it's intended value is accessible at a certain line of the source code.