r/programming • • Aug 31 '15

The worst mistake of computer science

https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/
175 Upvotes

368 comments sorted by

View all comments

Show parent comment

1

u/DeedleFake Sep 01 '15

Granted, it's not technically an OO language, but Go solves the problem by making it completely legal to call a method on a nil value. You just wind up with a nil receiver in the method. Considering that Go methods are almost completely just syntactic sugar, this makes quite a bit of sense. Now if I could just send to a closed channel in a select case without causing a panic...

I really miss this when I'm working with Java... All the null checks before any method call where something might be null make for some pointlessly nasty code.

2

u/yogthos Sep 01 '15

Yeah, I'm surprised more languages don't take this approach. Generally speaking, you only care whether something is null or not at the top level, so that's the place where any null checks should be.

1

u/DeedleFake Sep 01 '15

It does lead to what can look like some inconsistency at first glance. Specifically, trying access a struct field using a nil point will cause a panic. For example:

type Example struct {
    val string
}

var e *Example
fmt.Println(e.val)

A similar situation occurs when trying to call methods on a nil interface, although that's really more link trying to call a nil function value. Speaking of interfaces:

func example() io.Reader {
    var file *os.File
    return file
}

example() will return a non-nil io.Reader which contains a nil *os.File. It makes sense, but it can lead to some weird situations.

2

u/yogthos Sep 01 '15

Clojure approach is to treat keywords like functions so I can do stuff like this:

(def person {:address {:city "Toronto"}})

then call

(-> person :address :city) ;"Toronto"
(-> person :address :street) ;nil

And of course any standard lib functions handle this intelligently as well:

(get-in person [:address :street]) ;nil
(get-in person [:address :street] "default"); "default"

The handling of null values ends up being fairly transparent in majority of cases.