Friday, June 26, 2009

More Extensions - The Generic ToString() Method for classes and structs

NOTE: The following solution has been improved a lot in this blog.

Don't you hate repetitive tasks?

I sure do.
Writing ToString() methods for classes is one of them.
We will implement the same kind of ToString() methods if we need them to give us information about the object state as is very usefull when running UnitTests or logging exceptions.

Here is a typical example:

class ControlData
{
public Point location;
public Size size;

public ControlData(Point location, Size size)
{
this.location = location;
this.size = size;
}

public override string ToString()
{
return string.Format("[ControlData: {0} location={1} size={2}]", this.location, this.size);
}
}


Granted, codegenerators will do this job for you.
But what if you want to rename some fields or the class itself.
In that case you have to generate the ToString() method all over again, since the rename refactoring will not change anything inside of strings.
In our case, were we to change 'location' to 'firstLocation' its name in here:
"[ControlData: {0} location={1} size={2}]"

will not change with it.

Turns out, that there is a way to automate a ToString() execution alltogether. So without any further ado:

public static string FieldsToString<T>(this T fieldContainer) where T : IFieldsEnumerable
{
var sb = new StringBuilder();
int fieldCount = 0;

sb.AppendFormat("[{0}:", fieldContainer.GetType().Name);

foreach (var field in fieldContainer.GetFieldEnumerator())
{
sb.AppendFormat("\n {0}\t{1}\t{2} ",
fieldContainer.GetType().GetFields()[fieldCount].FieldType.Name,
fieldContainer.GetType().GetFields()[fieldCount].Name,
field.ToString());
fieldCount++;
}

sb.Append("]");

return sb.ToString();
}

Now lets look at the previous class again, except that it now implements the IFieldsEnumerable interface:

class ControlData : IFieldsEnumerable
{
public Point location;
public Size size;

public ControlData(Point location, Size size)
{
this.location = location;
this.size = size;
}

public override string ToString()
{
return this.FieldsToString();
}

public IEnumerable<object>GetFieldEnumerator()
{
yield return location;
yield return size;
}
}

Here is that interface:

public interface IFieldsEnumerable
{
IEnumerable<object>GetFieldEnumerator();
}
Calling:
new ControlData(new Point(12, 13), new Size(21, 30)).ToString();

produces this neat output:
[ControlData:
Point location {X=12,Y=13}
Size size {Width=21, Height=30} ]

Of course we could also have called FieldsToString() directly as in:
new ControlData(new Point(12, 13), new Size(21, 30)).FieldsToString();
with the same result.
Important is that the order of the yields in the GetFieldEnumerator() method exactly matches the order in which the fields are declared int the class. Otherwise the values of the fields will not line up with their names.
This requirement is caused by the fact, that the fieldnames are obtained from the class via reflection.

Now, if we want to change any field names, we can go ahead and be sure that all necessary changes in order to produce the correct ToString() output will be done automatically as we are not dealing with hard coded strings in the this method anymore.

If we add another field xxx , we just add a yield return xxx to the GetFieldEnumrator() method and are done.

Just to be clear, add the FieldsToString() method to your extension class and include the IFieldsEnumerable interface in the same project.

Now you just need to implement this interface for the classes to which you want this extra functionality.

Labels: , ,

Thursday, June 25, 2009

Extension methods and Unit Testing

When unit testing, we soon find out, that the testing framework (like NUnit) will use the ToString() method of an object in order to show the reason why an Equality Assertion fails.
Lets take or instance:
Assert.That(foo1, Is.EqualTo(foo2));
If this test fails, NUnit will try to show you where the objects where different by using the ToString() method as such:

Expected string length 20 but was 21. Strings differ at index 3.
Expected: "foo2 ToStringContent"
But was: "foo1 ToString Content"
--------------^
The problem with that is, that if we list a lot of fields in our ToString() method, the above Action of NUnit will throw a null reference exception, if only one of these fields wasn't initilaized. This will happen more often when using Mock objects.
In that case of course, we will never know what NUnit was trying to tell us. Not very desireable.

Therfore I decided that I'd need a null safe ToString() method. Instead of throwing an exception if the object is null, it will just return a string, that tells me that it was null.

public static class NullSafe
{

public static string ToStringNullSafe(this object obj)

{
return (obj != null) ? obj.ToString() : "NULL" ;

}

}
If you put this into your extensions project we can change this:
public override string ToString()
{

string strM = (M != null) ? M.ToString() : "null";
string strName = (Name != null) ? Name.ToString() : "null";
string strStatisticTexts = (StatisticsTexts != null) ? StatisticsTexts.Contents.ToString() : "null";

return string.Format("[ Type={0} M={1} Name={2} StatisticsTexts={3} ]",
M.GetType().Name, strM, strName, strStatisticTexts);
}
to:

public override string ToString()
{
return string.Format("[ Type={0} M={1} Name={2} StatisticsTexts={3} ]",
M.GetType().Name,
M.ToStringNullSafe(),
Name.ToStringNullSafe(),
StatisticTexts.ToStringNullSafe());
}
While we are at it, there is still one problem: M.GetType().Name
This will also throw, if M is null.

Again, extensions to the rescue. Add the following code to the NullSafe class:

static class ObjectWasNull {}
public static Type GetTypeNullSafe(this object obj)
{

return (obj != null) ? obj.GetType() : typeof(ObjectWasNull);
}
Note, that we just created the dummy class ObjectWasNull in order to communicate, that the object in question was null.

This will give us some helpfull output instead of failing totally.

Lets show another example:
Lets say we have a class:

class sut
{
Panel uninitializedPanel;
public override string ToString()
{
return uninitializedPanel.ToString();
}
}

In the test we try the following:

sut sut1 = new sut();
sut sut2 = new sut();


sut2.uninitializedPanel = new Panel();


Assert.That(sut1, Is.EqualTo(sut2));
This will give us a very ugly message like:

(......)
System.NullReferenceException : Object reference not set to an instance of an object.
at ( ...) TestClass.cs:line 145
at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.IO.TextWriter.Write(String format, Object arg0)
at NUnit.Framework.TextMessageWriter.WriteValue(Object val)
at NUnit.Framework.TextMessageWriter.WriteExpectedValue(Object expected)
at NUnit.Framework.TextMessageWriter.WriteExpectedLine(Object expected, Tolerance tolerance)
at NUnit.Framework.TextMessageWriter.DisplayDifferences(Object expected, Object actual, Tolerance tolerance)
at NUnit.Framework.Constraints.EqualConstraint.DisplayDifferences(MessageWriter writer, Object expected, Object actual, Int32 depth)
at NUnit.Framework.Constraints.EqualConstraint.WriteMessageTo(MessageWriter writer)
at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression)
(......)
Not very nice.
Now lets change:
return uninitializedPanel.ToString();
to:
return uninitializedPanel.ToStringNullSafe();

and we get
Test Failure : ( ... )
Expected: System.Windows.Forms.Panel, BorderStyle:
System.Windows.Forms.BorderStyle.None
But was: NULL

Much nicer indeed.

Labels: , ,