Null is considered bad, because of nullcheck. My question is, what other way there is, that would have replaced this null problem? How could that have been avoided?
Asked
Active
Viewed 123 times
0
-
so basically https://en.wikipedia.org/wiki/Monad_(functional_programming)#The_Maybe_monad should be the solution? but even there, you have to check, if you got Nothing or Just some value. so what does it help? – Tomy Oct 03 '15 at 12:18
-
No, you mostly don't have to check explicitly (instead, you use library functions that know how to handle it), and Option/Maybe composes better than null. Also, even when checking explicitly, since most languages that have Option also use pattern matching, the compiler will warn you if you forget to match against one of the cases. And finally, Option is a type that means "this may be optional". The type that says "this may be null" doesn't exist in Java... or rather, *all* types are. – Andres F. Oct 03 '15 at 12:30
-
1@Tomy the value of a `Maybe` monad or `Option` type is that the type system *requires* you to check whether the value is null. If `x` is an instance of a nullable type, Java allows you to do `x.foo()` which can throw a NullPointerException. If `maybeX` is an Option, `maybeX.foo()` won't compile. In many `Option` implementations you could do `maybeX.get().foo()` which is equivalent to not checking for a null pointer, but there are stricter variants where you have to have to supply code paths for both alternatives. E.g. in Scala: `val y = maybeX getOrElse { throw SomeException() } + 2` – amon Oct 03 '15 at 12:33
-
Nulls aren't inheriantly bad, nulls being a valid value in potentially any variable is bad – Richard Tingle Oct 03 '15 at 15:28
-
@RichardTingle: Unless one wants to add compiler-generated run-time checking, there's no real alternative to nullable variables when writing a class like `List
`. The backing store needs to be an array with more elements than the list has items, and there's really no sensible value that can be placed in the unused slots. One could have code generation generate run-time null checks for non-nullable generic types and omit such checks for nullable ones, but that would impose added costs at run-time without necessarily providing any useful safety improvement. – supercat Oct 29 '15 at 15:13 -
@supercat Thats why it would have been good to be able to define nullable values, so `T?` would be used internally, but the list itself could guarantee it only emits `T` and only allows `T` to be added unless `T?` was specified as the generic type (all garanteed **at compile time**). Obviously the entire language would have to support this and I think its probably too late to introduce it to java now. Putting a `T?` in a `T` list would be the same as putting a `Cat` in a `T` list, garanteed at compile time – Richard Tingle Oct 29 '15 at 16:26