Today, I refactored this…
public bool CanUse(string id)
{
bool rtn = true;
for (int i = 0; i <= _innerArray.Count - 1; i++)
{
Medi cur = (Medi)_innerArray[i];
if (cur.Id == id)
{
rtn = false;
break;
}
}
return rtn;
}
Into this…
public bool CanUse(string id)
{
return _innerCollection.Any(x => x.Id == id) == false;
}
The code was completely undocumented, and there wasn’t a test project at all with the solution. It was pretty easy to tell what was going on, but this is production code that has been migrated from .NET 1.1 up to 3.5SP1. Lots of ArrayLists and loosely typed data sets.
So let’s take the opportunity to leave the code cleaner than when you found it.
[TestMethod]
public void Returns_False_If_Medi_Is_Already_In_List()
{
var collection = new MediList();
collection.AddToList("AAAAA", "1");
var result = collection.CanUse("1");
Assert.IsFalse(result);
}
[TestMethod]
public void Returns_True_If_Medi_Is_Not_In_List()
{
var collection = new MediList();
collection.AddToList("AAAAA", "1");
var result = collection.CanUse("99");
Assert.IsTrue(result);
}
Before we do any refactoring at all, write the unit tests. Make sure that the block of code is really doing what we think the block of code should be doing. Tests are green? Good. Refactor. Tests are still green? Great! Check in and move on to the next problem.
Page 1 of 1
RSS
@jarrettmeyer