Apr 22, 2014

Defensive programming – simple method to prevent Object reference not set exception

 

Just to share a simple way to prevent the ugly “object reference not set” exception: 

public class DefensiveCode
{
//Non-defensive code (unsafe):
public IList<string> UnsafeProps { get; set; }
public void DoSomething(string input)
{
//props can be null --> exception
if (UnsafeProps.Contains(input))
{
//....do work
}
}

//Defensive code #1:
public IList<string> SafeProps { get; set; }
public void DoSomethingSafely(string input)
{
//a little better, but have to check every time
//and it may depend on how compiler evaluate: L-to-R is OK, but R-to-L will not be OK
if (SafeProps != null && SafeProps.Contains(input))
{
//....do work
}
}


//Defensive code #2: (preferred)
private IList<string> _SafestProps;
public IList<string> SafestProps
{
get
{
//initialize before accessing it.
if (_SafestProps == null) _SafestProps = new List<string>();
return _SafestProps;
}
set { _SafestProps = value; }
}

public void DoSomethingSafestWay(string input)
{
//it’s always safe
if (SafestProps.Contains(input))
{
//....do work
}
}
}
A lesson learnt: do not return NULL , return empty list or empty string instead.

No comments:

Post a Comment