Thursday, 8 November 2012

Reducing code noise for argument checking / assignment

Leading on from the previous blog post on reducing code noise when checking for null parameters, these help functions can be utilised to further reduce code noise that generally occurs in class constructors. Most constructors are purely made up of the following duplicated checking / assignment code.

public class MyClass
{
private readonly object var1;
private readonly object var1;
 
public MyClass(object arg1, object arg2)
{
if (arg1 == null)
{
throw new ArgumentNullException("arg1");
}
 
if (arg2 == null)
{
throw new ArgumentNullException("arg2");
}
 
this.var1 = arg1;
this.var2 = arg2;
}

Again putting together a small helper function, making use of the previous Throw class can remove 90% of the previous argument checking / assignment code resulting in:

public class MyClass
{
private readonly object var1;
private readonly object var1;
 
public MyClass(object arg1, object arg2)
{
this.var1 = ReturnParameter.OrThrowIfNull(arg1, "arg1");
this.var2 = ReturnParameter.OrThrowIfNull(arg2, "arg2");
}

Get the code from GitHub.

No comments:

Post a Comment