3 ms·
Only since Java 8. The coalesce operator is in c# since the version 3.5 or 4 I think and c# 6 introduced the null conditional operator that, as I said before, i
by tigershark 10y ago
Only since Java 8.
The coalesce operator is in c# since the version 3.5 or 4 I think and c# 6 introduced the null conditional operator that, as I said before, is objectively nicer than the verbose Java optional.
Before c# 6 I used this simple extension method:
public static TDest IfNotNull<TSource, TDest>(this TSource obj, Func<TSource, TDest> func)
{
return obj != null ? func(obj) : default(TDest);
}
Or something similar (writing c# code on the iPad before sleeping is not exactly simple), inspired by some blog post ages ago.
Just adding these three line of codes in a static class in the solution will enable you to write something like this:
var id = order.IfNotNull(o => o.Customer).IfNotNull(c => c.Id) ?? "INVALID"
Still not as good as the null check operator but comparable with the Java optional (arguably better from my point of view)
- lacampbell 10y agoHow is it better? All you've done is re-implemented mapping over an option. Your C# code is this in Java: String id = order.map(o -> o.Customer).map(c -> c.Id).orElse("INVALID"); The Java code is actually shorter and works straight out of the box, so I don't know why you're calling Optionals "verbose".
- vile 10y agoIt's not shorter than out-of-the-box c# 6, which would be var id = order?.Customer?.Id ?? "INVALID"; I think that was the point he was making, that it's always been possible, and now is simple.
- lacampbell 10y agoExcept that nullable types aren't the same thing as option types, so it's not doing the same thing. Nullables are much weaker than options. You can't do this for instance: string? id = "Name"; While you can do stuff like this: int x = 0; int? y = x; Again, F# has nullable types and options, and the fact that no one in F# uses nullable types should tell you something.
- tigershark 10y agoThe null check operator is much more concise than my pre-c# 6 solution. Moreover you can apply both my solution and the null check operator to any type, while for Java you have to specify that a field is optional (increasing the verbosity and moving the responsibility to who write the class) and you can't do it for types that you don't own. So for these types the only way is to create a wrapper type just to add the optional fields, and this brings the amount of boilerplate code through the roof. So, just to sum it up, contrary to what you say the c# solution works out of the box, is much shorter than the Java alternative and works for every type. Honestly I can't really see why Java solution is superior for you.