What does this piece of code do?
1: public void SetCustomerPropertiesOnView(IEnumerable<Customer> customers)
2: {
3: int count = 1;
4: var previousSurname = string.Empty;
5: foreach (var customer in customers)
6: {
7: this.View.AllCustomers.Add(new CustomerDisplay(customer));
8:
9: if (count == 1)
10: previousSurname = customer.Surname;
11:
12: if (customer.Surname != previousSurname)
13: {
14: this.View.SurnameFilter.Add(new NorthWindListItem(customer.Surname, customer.ID.ToString()));
15: previousSurname = customer.Surname;
16: }
17: count++;
18: }
19: }
I will explain the reasons behind this code, and come up with a more refined solution in a later post. More often than not we come across implementations like this where the maintainer has to work really hard to get to the intent of the code. In short this is an example of working code that is not easily maintainable over time, we can and should do better. With the safety net of unit tests I can now play around with this code to make it better.
This all goes back to Mike Waggs post on why he loves TDD/BDD particularly when he talks about tweaking code
“The best developers are those that continuously refine their code. They take something that is just a solution to the problem at hand and transform it into something which is clean and elegant. They craft a piece of code that is easily understandable by other developers and which can be easily maintained as the requirements of the system changes.”
I couldn’t agree more with this sentiment. The code above is a practical example of why we should strive to keep on tweaking. As I said before the code works, it does a job, should I walk away happy with this implementation. Absolutely not, we can make it better, so that the next person that has to delve into this code will get more understanding from reading it, not more questions.
Trying to understand this implementation will take time, to the business time is money and developer time is even more money. So for the good of the business don’t lock in your ignorance by leaving a first attempt at a solution to a problem, tweak it, until it clearly expresses your intent.
My solution will follow…what’s yours?