What are some guidelines for when it is not necessary to check for a null?
A lot of the inherited code I\'ve been working on as of late has null-checks
At first, this seemed like a strange question: null
checks are great and a valuable tool. Checking that new
returns null
is definitely silly. I'm just going to ignore the fact that there are languages that allow that. I'm sure there are valid reasons, but I really don't think I can handle living in that reality :) All kidding aside, it seems like you should at least have to specify that the new
should return null
when there isn't enough memory.
Anyway, checking for null
where appropriate leads to cleaner code. I'd go so far as to say that never assigning function parameters default values is the next logical step. To go even further, returning empty arrays, etc. where appropriate leads to even cleaner code. It is nice to not have to worry about getting null
s except where they are logically meaningful. Nulls as error values are better avoided.
Using asserts is a really great idea. Especially if it gives you the option of turning them off at runtime. Plus, it is a more explicitly contractual style :)