Timeline for Are null references really a bad thing?
Current License: CC BY-SA 3.0
10 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Dec 17, 2014 at 22:52 | comment | added | Ilya Gazman | @JakeToronto this is not about handling, but how you choose to handle it. | |
| Dec 17, 2014 at 19:50 | comment | added | Jake Toronto |
Option is all about making clear to the programmer using your code that he or she must handle the null case.
|
|
| Mar 16, 2014 at 2:49 | comment | added | Tim Goodman |
It's common in functional programming languages, like Haskell, Scala, F#, etc. The accepted answer links to an implementation in Java, but in a functional language like Scala, the syntax to use it is easier. If s is an Option[String] and you want to get its length, you can say s match { case Some(str) => str.length; case None => /* Handle this case however you want */ } With a string, s.length() risks a NullPointerException. With an Option[String], s.length() is caught at compile time, because Option[String] doesn't have a length.
|
|
| Mar 15, 2014 at 10:55 | comment | added | Ilya Gazman | @TimGoodman is it scala only tactic or can it be used in other languages like Java and ActionScript 3? Also it would be nice if you could edit your answer with full example. | |
| Mar 13, 2014 at 20:01 | comment | added | Tim Goodman | However I agree with the general comment that exceptions (used properly) are not a bad thing, and "fixing" an exception by swallowing it is generally a terrible idea. But with the Option type, the goal is to turn exceptions into compile-time errors, which are a better thing. | |
| Mar 13, 2014 at 19:57 | comment | added | Tim Goodman |
Unfortunately in Scala you still can say s: String = null, but that's the price of interoperability with Java. We generally disallow that sort of thing in our Scala code.
|
|
| Mar 13, 2014 at 19:56 | comment | added | Tim Goodman |
For example: You can't say s: String = None, you have to say s: Option[String] = None. And if s is an Option, you can't say s.length, however you can check that it has a value and extract the value at the same time, with pattern matching: s match { case Some(str) => str.length; case None => throw RuntimeException("Where's my value?") }
|
|
| Mar 13, 2014 at 19:55 | comment | added | Tim Goodman |
I know quite a bit more about the Option type now than when I posted the question a few years ago, since I now use them regularly in Scala. The point of Option is that it makes assigning None to something that isn't an Option into a compile-time error, and likewise using an Option as if it has a value without first checking it is a compile-time error. Compile errors are certainly nicer than run-time exceptions.
|
|
| S Mar 13, 2014 at 8:35 | history | answered | Ilya Gazman | CC BY-SA 3.0 | |
| S Mar 13, 2014 at 8:35 | history | made wiki | Post Made Community Wiki by Ilya Gazman |