4 ms·
What's wrong with null?
by Kiro 8y ago
What's wrong with null?
- coldtea 8y agoA null is not a string or an integer or a MyClass instance, etc. So why does it pollute variables of all those types? https://medium.com/@hinchman_amanda/null-pointer-references-the-billion-dollar-mistake-1e616534d485 https://medium.com/@hinchman_amanda/null-pointer-references-... https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare https://www.infoq.com/presentations/Null-References-The-Bill... https://www.quora.com/Why-was-the-Null-Pointer-Exception-in-Java-called-a-billion-dollar-mistake https://www.quora.com/Why-was-the-Null-Pointer-Exception-in-... https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/ https://www.lucidchart.com/techblog/2015/08/31/the-worst-mis...
- Kiro 8y agoThanks. Stupid question but consider the following: entity = Entity.fetch(id) if (!entity) doSomething() Entity.fetch returns null if it doesn't find anything. How would this work without null?
- wtetzner 8y agoThe real problem isn't null itself, it's that in most languages that have it, null inhabits all types (or at least all reference types). Different languages solve this problem in different ways. Many languages get rid of null entirely, and use option types in its place. Other languages, like Kotlin, fix it in the type system, by differentiating between e.g. String and nullable String (spelled String? in Kotlin) .
- ptx 8y agoYou would still have null, but only when asked for and checked explicitly. In Kotlin, for example, you mark something with a question mark to say that it can be null, which forces you to check for null before using it: val entityOrPossiblyNull: Entity? = Entity.fetch(id) if (entityOrPossiblyNull == null) { doSomething() } else { // The compiler knows that the variable is not null in this branch, // so this assignment is OK. val entityForSure: Entity = entityOrPossiblyNull doSomethingWithEntity(entityForSure) }
- coldtea 8y agoThere are several ways. A popular one is an Optional type. Here's how Java does it: https://www.baeldung.com/java-optional https://www.baeldung.com/java-optional
- deleted 8y ago[deleted]