Hacker News new | ask | show | jobs
by xkcdfanboy 4775 days ago
Don’t Pass Null? This is idiotic if you want performant code and don't want to have to use static empty object constants littered throughout your code.

Null is perfectly fine in place of an object. The author mentions this saves you debugging time. No, it will cause you pain later because you won't see errors that should happen. Instead they are masked by operating on some dummy object that you don't give a rats ass about.

2 comments

Don't pass NULL (but do collect $200).

For modules I write in C, I only have one function that can return NULL---the function that creates a new structure. All other functions that work with that structure assume (backed by an assert()) that the passed in pointer will not be NULL. For the code I write, there is no reason for functions to accept a NULL pointer. And it's less painful that it sounds. I got the idea from _Writing Solid Code_, one of only two books that fundamentally changed how I write code (the other being _Thinking Forth_).

I'm sold on "don't pass null" for collections. Return empty collections instead of null, this saves you from a world of pain, and it reduces the code size.

The right way to work around null for scalar variables is to use Maybe/Option, preferably in a language with pattern matching, as opposed to using "magic values" like 0 or the empty string. This means removing null pointer errors by construction.