Archive

Archive for January, 2010

WPF, magic strings and some Linq love

January 24, 2010 1 comment

WPF as you might have experienced, is a lot more powerful as compared to WinForms when it comes to UI. However as you might have also noticed, it uses a lot more “magical strings”. e.g. if you have to show some entries in a combo box and if you have to group / sort those entries in any way, you might see code like this –

Reasons = new ListCollectionView(GetFilteredReasons(message.Reasons).ToList());

Reasons.GroupDescriptions.Add(new PropertyGroupDescription("IsCallOn"));
Reasons.SortDescriptions.Add(new SortDescription("IsCallOn", ListSortDirection.Descending));
Reasons.SortDescriptions.Add(new SortDescription("DisplayName", ListSortDirection.Ascending));

Here Reasons is an ICollectionView and IsCallOn and DisplayName are properties of Reason class whose collection is to be shown in the combo. But think what happens if you rename those properties to some other names. These property names which are strings in the above code, are not refactored. However, if these properties were used in the form of “objectName.PropertyName” form, they would’ve been promptly renamed when you refactor your code.

I had read the “strongly typed reflection” post from Daniel Cazzulino long back but was not clear on how to implement such stuff. I had also read the Functional .Net – Lose the magic strings post from Mathew Podwysocki on how the Asp.Net MVC gets rid of magic strings. With the help of these two posts I was finally able to write the below code – 

public static class ListCollectionViewExtensions
{
	public static ICollectionView GroupByOn<T>(this ICollectionView collection, Expression<Func<T, object>> expression)
			where T : class
	{
		var propertyName = Reflector.GetPropertyName(expression);
		collection.GroupDescriptions.Add(new PropertyGroupDescription(propertyName));
		return collection;
	}

	public static ICollectionView SortByOn<T>(this ICollectionView collection, Expression<Func<T, object>> expression, ListSortDirection sortDirection)
		where T : class
	{
		var propertyName = Reflector.GetPropertyName(expression);
		collection.SortDescriptions.Add(new SortDescription(propertyName, sortDirection));
		return collection;
	}
}

public class Reflector
{
	public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
	{
		var property = GetProperty(expression);
		return property.Name;
	}

	private static MemberInfo GetProperty<T>(Expression<Func<T, object>> expression)
	{
		var lambdaEx = expression as LambdaExpression;
		if (lambdaEx == null) throw new ArgumentNullException("expression");

		MemberExpression memberExpression = null;

		if (lambdaEx.Body.NodeType == ExpressionType.Convert)
		{
			var unaryExpression = lambdaEx.Body as UnaryExpression;
			if (unaryExpression == null) throw new ArgumentNullException("expression");

			if (unaryExpression.Operand.NodeType == ExpressionType.MemberAccess)
			{
				memberExpression = unaryExpression.Operand as MemberExpression;
			}
		}
		else if (lambdaEx.Body.NodeType == ExpressionType.MemberAccess)
		{
			memberExpression = lambdaEx.Body as MemberExpression;
		}

		if (memberExpression == null) throw new ArgumentNullException("expression");
		return memberExpression.Member;
	}
}

Which makes use of Expression<> class from the System.Linq.Expressions namespace. So, instead of writing code like above, one can write the below code, which is type safe and resharper friendly.

Reasons = new ListCollectionView(GetFilteredReasons(message.Reasons).ToList());

Reasons
	.GroupByOn<Reason>(x => x.IsCallOn)
	.SortByOn<Reason>(x => x.IsCallOn, ListSortDirection.Descending)
	.SortByOn<Reason>(x => x.DisplayName, ListSortDirection.Ascending);

So not only are we writing less code than before, but we’ve also saved ourselves from possible future refactoring headaches 🙂 And as usual, here are the unit tests for checking the ListCollectionViewExtensions class –

[TestFixture]
public class As_a_ListCollectionViewExtensions
{
	[Test]
	public void should_add_group_by_clause_on_an_int_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.Id);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_bool_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.IsGood);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_string_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.Name);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_char_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.CharProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_byte_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.ByteProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_sbyte_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.SByteProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_double_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.DoubleProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_long_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.LongProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_decimal_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.DecimalProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_float_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.FloatProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	[Test]
	public void should_add_group_by_clause_on_a_short_property()
	{
		var list = GetSampleData();
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(0));

		list.GroupByOn<SampleClass>(x => x.ShortProp);
		Assert.That(list.GroupDescriptions.Count, Is.EqualTo(1));
	}

	private static ICollectionView GetSampleData()
	{
		var list = new List<SampleClass>()
		       	{
		       		new SampleClass()
		       			{
		       				Id = 1,
		       				IsGood = true,
		       				Name = "hi",
						ByteProp = 255,
						SByteProp = 127,
		       				CharProp = 'y',
		       				DoubleProp = 20.2d,
		       				LongProp = 4294967296,
		       				DecimalProp = 9898.34m,
		       				FloatProp = 234.567f,
		       				ShortProp = (short) 5
		       			}
		       	};

		return new ListCollectionView(list);
	}

	private class SampleClass
	{
		public int Id { get; set; }
		public bool IsGood { get; set; }
		public string Name { get; set; }

		public byte ByteProp { get; set; }
		public byte SByteProp { get; set; }
		public char CharProp { get; set; }
		public double DoubleProp { get; set; }
		public long LongProp { get; set; }
		public decimal DecimalProp { get; set; }
		public float FloatProp { get; set; }
		public short ShortProp { get; set; }
	}
}

Hope you like it.

Advertisements
Categories: Programming

The importance of unit tests

January 12, 2010 Leave a comment

A few days back, one of my friends asked me following questions related to unit testing –

1. Should I start using unit tests for my new development only?
2. I don’t know why but whenever I start thinking about writing unit tests I suddenly feel “lazy” 🙂
3. I still can’t figure out which are those dark spots where I should not go about test driven development?

Well, first things first. Test Driven Development is hard and requires lots of practice and discipline, so don’t try it at the beginning, you might not even get it. Even if you start writing tests after development, your code base will be in a good shape.

Now Let’s tackle no. 2 first – thanks for being honest about feeling lazy, but I read sometime back that Agile development is “DISCIPLINE”, and there can’t be a more appropriate word to describe that fact. If you are writing unit tests for the code you write, that in itself shows that you are a mature and disciplined developer (person). However highly we rate our programming skills 😉 we are still humans and so we are bound to make mistakes; not only that, our code certainly depends on code which our fellow developers write, and what if they unexpectedly change the behavior of the code (while keeping the external interface same)? How will you know if the code you wrote doesn’t break?

Also, most of us are habituated of doing debugger-driven-development, so much so that a couple days back, I was debugging one of my unit tests 🙂 and one of my colleagues said, stop that! Run the test! So the crux is that debugging is a waste of time, running a unit test is very easy (right click of mouse) if you have tools like Resharper and it definitely saves a lot of time. So think hard, how much of your total development time you spend in the debugger?

Now let’s see some of the philosophical reasons for writing unit tests –

1. Jeremy Miller says that he won’t even look at the code which is not covered with unit tests
2. Ayende says that any code written immediately becomes legacy code if not covered with unit tests
3. Will you buy any car if it was not tested thoroughly in a factory? What if it’s brakes are faulty?
4. Equally importantly, will you sell a car without testing it? (If the answer to this is no, then please do not check in any code until you have written unit tests and do not consider your work done until you have unit tests. Did I mention discipline earlier?)
5. Truly great developers will look at your tests first, to understand the behavior of your code, and the list goes on…

So is that it? No, there are solid technical reasons why unit tests make your code solid –

1. If you don’t have unit tests, you won’t be able to (or find it almost impossible to) refactor your code. If you are not refactoring your code, then you are assuming that you write very good code, which even if it is true in that particular moment, might not remain so after a couple of months (when some of the requirements have changed and you get fresh insights into the code after working on it for a long time). It’s only a couple of months in my current project and I’ve refactored my code atleast twice – introduced some base classes where none existed etc. How do you think was I confident if it didn’t break any existing stuff?

2. Without unit tests, chances are that you are writing tightly coupled code and your code can’t even be unit-tested. I mean how do you know if it can be unit tested? What if you’ve have written all the logic on the button click handler of a form? So a very desirable side effect of a code having unit tests is that it might be less coupled than the one with no unit tests. Now think of this – what does IoC gives you? Less coupling, right? Did you think why? Because if you are using IoC, you must be using classes which implement interfaces. So the benefit is that you can mock those classes instead of using the real implementations.

3. I hope you are aware of mock testing frameworks like Rhino mocks or Moq. There are situations where the SUT (system under test) doesn’t have a state, so you can’t use state testing tools like NUnit. Or while testing the UI, most likely you’ll want to test the interaction of the UI with the presenter, rather than checking the state of the UI. These mocking frameworks make mocking an interface (meaning providing an alternative implementation of your interface with pre-set return values etc.) very easy, so that you can check against those. Most mocking frameworks work on interfaces so if you are not using interfaces heavily you can’t mock anything. Note: you can also do state based testing using Mock frameworks.

4. One other advantage with writing unit tests is that they serve as regression tests i.e. as your code keeps growing, so do your number of unit tests. And after some time, you have a good collection of tests to cover your code base. So think of this – if you write some framework, will anyone want to use it if you haven’t written any unit tests?

5. Lastly, as I mentioned before, if you are writing unit tests, you’ll most probably use interfaces, use some mocking framework and / or write some stub classes e.g. my current code base works off a DB where we have bare minimum rights and there are other accessibility issues. On top of it, we are using messaging heavily (using MassTranit) so when the initial development must’ve started, there would’ve been more such issues impeding development. Hence we have two sets of classes – one actual implementation, which will actually connect to the DB and fetch data and a fake one (where we’ve used the Builder pattern) which will return some hard-coded data. So most of the time we are developing against these fakes, and only when the development is complete, the unit tests are in place, do we check against the actual classes, and this works very well for us. But then think, how much more code we’ve written – stub classes and the unit tests – but doesn’t it show the discipline of the team? And when we hand over the code to the testing team, then we are pretty confident that the code should work.

So long story short – the answer to Q. 1 is NO. If you start writing unit tests for an existing code, you’ll start making it better. Also, maintaining a code base with unit tests is far easier than a code base with none.

Answer to Q. 3 is – I am not sure about this question, but if you are writing tests against a database or to test an actual web service, then beware, those are not unit tests, they are integration tests. So barring these, I believe one can pretty much unit test everything.

I’ve tried my best to answer my friend’s queries and I hope he finds this useful. Please let me know. And btw, once you actually work on a good code base (meaning one having unit tests and having a continuous integration server setup which runs all unit tests when anyone checks-in the code) – you’ll realize that the whole Agile development way is very addictive and you’ll hate to go back to your previous ways of writing un-automated tested code.

Categories: Programming, Unit Testing

Why I won’t need any other GetDelimitedString method in C#

January 7, 2010 Leave a comment

The various Func<T1, TResult> and Action<T> overloads and lambdas are old stuff in C# and .Net, but how clear one is in them and how fluently one can use it in code is a different topic. Today, in my quest to write a generic GetDelimitedString method, I happened to write a nice little function which uses a Func<>.

You must have faced situations where you have an IList<T> or IEnumerable<T> and you want either a comma delimited string value made up of all the objects in this list, or a string using some delimiting character. e.g. if you have this class –

public class Person {

    public string Name { get; set; }
}

and you have a List<Person>, and you want a comma delimited names of all the persons in this list.

Now I wrote an extension method on the IEnumerable<T> –

		public static string GetDelimitedString<T>(this IEnumerable<T> list, Func<T, string> func, string delimiter)
		{
			var delimitedString = new StringBuilder();
			for (int i = 0, length = list.Count(); i < length; i++)
			{
				var name = func(list.ElementAt(i));

				if (i < length - 1)
				{
					delimitedString
						.Append(name)
						.Append(delimiter)
						.Append(" ");
				}
				else
				{
					delimitedString.Append(name);
				}
			}

			return delimitedString.ToString();
		}

I need to pass in a Func<T, string> because only this particular logic is the variable part in the whole algorithm to get a delimited string. The reason this is the variable logic is because this particular extension method doesn’t know how to extract a string value from an object of type T. One might want to use the Name property of type T, or the FirstName property of type T, or FirstName and LastName properties of T or simply a ToString() method on the object of type T.

So whoever is using this method (the developer) will supply a method (Func<T, string>) to this extension method telling  it how to arrive at a string from a T. So in the above Person example, the method which should be passed to the extension method, must take a Person parameter and return a string, like this –

public string GetName(Person p) {
    return p.Name;
}

which can be represented using a lambda like – p => p.Name assuming p is of type Person. Here’s the actual usage –

[Test]
public void should_convert_a_list_of_ints_to_a_delimited_string()
{
	var names = new List<Person> { new Person {Name = "MW"}, new Person {Name = "BB"} };
	var expected = "MW, BB";

	Assert.That(names.GetDelimitedString(p => p.Name, ","), Is.EqualTo(expected));
}

Another example –

[Test]
public void should_convert_a_list_of_ints_to_a_delimited_string()
{
	var listOfInts = new List<int> { 1, 2, 3 };
	const string expected = "1, 2, 3";

	Assert.That(listOfInts.GetDelimitedString(i => i.ToString(), ","), Is.EqualTo(expected));
}

An even more interesting example is this –

[Test]
public void should_convert_any_list_to_a_delimited_string()
{
	const string delimiter = "";
	const string sungard = "SunGard";
	const string datasystems = "DataSystems";
	const string expected = sungard + " " + datasystems;

	var firstAnonymousType = new { Name = sungard };
	var secondAnonymousType = new { Name = datasystems };
	var list = new List<object> { firstAnonymousType, secondAnonymousType };

	Assert.That(list.GetDelimitedString(o => GetName(o), delimiter), Is.EqualTo(expected));
}

private string GetName(object o)
{
	var anonymousTyped = Cast(o, new {Name = ""});
	return anonymousTyped.Name;
}

private T Cast<T>(object obj, T type)
{
	return (T)obj;
}

If you notice, firstAnonymousType is an anonymous type with a single Name property. Then, I am making a List containing these anonymous types because there is no way in which I can specify a type parameter T (which is of anonymous type) to the List, because well, it is anonymous, isn’t it? 😉 The magic is in the Cast method which is casting an object (of type object) back to an object of type anonymous type. The critical piece of code is in the way the Cast method is called – var anonymousTyped = Cast(o, new {Name = “”})

This above magical piece of code (about casting of anonymous types) came from Tomas Petricek’s article.

One last info. – just by looking at a lambda expression, you won’t be able to figure out if the underlying delegate is an Action<> or a Func<> because in both cases, the lambda looks similar – x => x.Something.

Update: Yesterday, one of my colleagues, Dan modified the code of the above method to a one liner using Linq 🙂 sweet….

public static string GetDelimitedString<T>(this IEnumerable<T> list, Func<T, string> converter, string delimiter)
{
	return String.Join(delimiter, list.Select(converter).ToArray());
}
Categories: Programming