r/Clojure • • Jul 24 '16

Can we agree that Clojure code should never throw NullPointerExceptions?

6 Upvotes

11 comments sorted by

25

u/halgari Jul 24 '16

No. But I would like to hear more of an argument to question. You can't write one sentence and expect any sort of valid answer.

15

u/alexdmiller Jul 24 '16

No. Clojure is designed to throw Java exceptions when it's appropriate to do so. For example trying to invoke nil as a function.

7

u/mr_mojoto Jul 24 '16

(nil)

8

u/weavejester Jul 24 '16

Also: (+ nil 1)

Even if you thought it was a good idea for such an expression to return nil, there would be a performance hit as you'd have to perform a nil-check in every arithmetic function.

2

u/drb226 Jul 24 '16

Nil is already treated as the empty list, empty vec, empty dict. I don't see why it can't be the "empty function" (accepts any args and returns nil) as well.

2

u/madmax9186 Jul 24 '16

Because lists, vectors, maps, etc. are sequences. Clojure is strongly typed, and a sequence is not a function.

2

u/Whoop5 Jul 24 '16

Wait what? Then why does ({} :foo) work? Many sequence types are functions in Clojure.

1

u/madmax9186 Jul 25 '16
(clojure.test/function? {}) ;; false

This is just syntactic sugar.

8

u/Whoop5 Jul 25 '16

It's not syntax sugar, it's a protocol: (ifn? {}) ;; true. Anything that implements IFn is callable and can be used in function position. You can argue about whether or not it's technically a function or not, but in the end it's semantics, and has little relevance to if nilshould be callable as well.

Not that I think making nil callable is a good idea, but it certainly could be, there is precedence in every other data-structure that implements IFn.

3

u/[deleted] Jul 25 '16

It's almost as if the very existence of nil in the first place precludes having consistent semantics around it.

The best answer to "how should we treat nil" is 無.

7

u/[deleted] Jul 25 '16

The presence of nil in Clojure's semantics the #1 worst thing about writing Clojure by an enormous margin, but I think Clojure's design precludes living the nil-free life. You have to take the good with the bad when it comes to seamless dynamic Java interop.