Tuesday, January 12, 2010

Detecting redudant initializers

The code below illustrates two initializers, one of which is unneeded.

class StudentRecord
{
public StudentRecord(string studentNo)
{
StudentNo = studentNo;
}
public StudentRecord(string studentNo, string fullName)
{
StudentNo = studentNo;
FullName = fullName;
}
public string FullName { get; set; }
public string StudentNo { get; private set; }
}

Which could be initialize in two different manners:

  • var y = new StudentRecord("1234","John Doe" );
  • var x = new StudentRecord("1234") { FullName = "John Doe" };
The latter one is clearer, the former one calls for writing additional code that does contribute anything (except increase the risk of bugs and cost of maintenance).



Custom Initializers should be used when one of the following is true only:
  • Passes in data that that is not exposed as a property
  • Passes in data that is a property that is a private set.
To restate is in a simpler way:

If
var x=new StudentRecord( a,b,c,d);
can be rewritten as:
var x=new StudentRecord( a){paramb=b, paramc=c,paramd=d};
but cannot be rewritten as
var x=new StudentRecord(){ parama= a, paramb=b, paramc=c,paramd=d};

Then
  • StudentRecord(object a) is appropriate
  • StudentRecord(object a, object b, object c, object d) is inappropriate, being redundant.

No comments:

Post a Comment