I saw this article that proposes a refactoring exercise and thought I'd give it a try.
Spoiler alert: I'm going to show my solution to the Kata below. You might want to attempt the Kata yourself before you look at this code, so this will not influence you in any way.
I ended up with the following three classes:
Person.cs
public class Person
{
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public bool IsOlderThan(Person person2)
{
return BirthDate > person2.BirthDate;
}
}
Pair.cs
public class Pair
{
public Person Person1 { get; set; }
public Person Person2 { get; set; }
public TimeSpan AgeDifference { get { return Person2.BirthDate - Person1.BirthDate; } }
public Pair(Person person1, Person person2)
{
if (person1.IsOlderThan(person2))
{
Person1 = person2;
Person2 = person1;
}
else
{
Person1 = person1;
Person2 = person2;
}
}
public Pair()
{
Person1 = Person2 = null;
}
}
Finder.cs
public class Finder
{
private readonly List<Person> _person;
public Finder(List<Person> person)
{
_person = person;
}
public Pair FindClosestAgeInterval()
{
return Find(pairs => pairs.OrderBy(p => p.AgeDifference).FirstOrDefault());
}
public Pair FindFurthestAgeInterval()
{
return Find(pairs => pairs.OrderByDescending(p => p.AgeDifference).FirstOrDefault());
}
public Pair Find(Func<IEnumerable<Pair>, Pair> pairSelectionLambda)
{
var availableDistinctPairs = GetDistinctPairs();
return pairSelectionLambda(availableDistinctPairs) ?? new Pair();
}
private IEnumerable<Pair> GetDistinctPairs()
{
for (var i = 0; i < _person.Count - 1; i++)
for (var j = i + 1; j < _person.Count; j++)
yield return new Pair(_person[i], _person[j]);
}
}
The test class basically remained the same (except that I have updated it with the new class/method names).
Overall I think this code is OK (it passes the tests and I could easily understand it 6 months from now).
However, I'm interested to hear your critic opinions, to find out how it can get better.
Pairto reflect their respective ages. Maybe something likeSeniorandJuniororElderandYounger. – Carl Manaster Apr 9 '12 at 15:37