Apparently the vast majority of errors in code are null reference exceptions. Are there any general techniques to avoid encountering null reference errors?
Unless I
Good code analysis tools can help here. Good unit tests can also help if you're using tools that consider null as a possible path through your code. Try throwing that switch in your build settings that says "treat warnings as errors" and see if you can keep the # of warnings in your project = 0. You may find the warnings are telling you a lot.
One thing to keep in mind is that it may be a good thing that you are throwing a null - reference exception. Why? because it may mean that code that should have executed did not. Initializing to default values is a good idea, but you should be careful that you don't end up hiding a problem.
List GetAllClients()
{
List returnList = new List;
/* insert code to go to data base and get some data reader named rdr */
for (rdr.Read()
{
/* code to build Client objects and add to list */
}
return returnList;
}
Alright, so this may look ok, but depending on your business rules, this may be a problem. Sure, you'll never throw a null reference, but maybe your User table should never be empty? Do you want your app to be spinning in place, generating support calls from users saying "it's just a blank screen", or do you want to raise an exception that might get logged somewhere and raise an alert quickly? Don't forget to validate what you're doing as well as 'handling' exceptions. This is one of the reasons why some are loathe to take nulls out of our languages... it makes it easier to find the bugs even though it may cause some new ones.
Remember: Handle exceptions, don't hide them.