首先就功能做个说明,该函数的功能是计算一个softwaregroup的所有device使用信息,把具有相同ID的device信息进行叠加统计后输出。一个softwareGroup包括多个software, 一个software可以在多个device上安装。(红色函数为要重构函数)
class SoftwareGroup
{
ArrayList GetAllDevices()
{
Hashtable allDevices = new Hashtable();
ArrayList allSoftwares = this.softwares;
foreach (Software sw in allSoftwares)
{
ArrayList devices = sw.GetDevices();
foreach (Device device in devices)
{
if (allDevices.ContainsKey(device.ID))
allDevices[device.ID] = device;
else
allDevices[device.ID] = Add(allDevices[device.ID] as Device, device);
}
}
return new ArrayList(allDevices.Values);
}
private object Add(Device oneDevice, Device twoDevice)
{
Device ret = new Device();
ret.ID = oneDevice.ID;
ret.Name = oneDevice.Name;
ret.Type = oneDevice.Type;
ret.ExecNum = oneDevice.ExecNum + twoDevice.ExecNum;
ret.LastTime = oneDevice.LastTime.CompareTo(twoDevice.LastTime) > 0 ? oneDevice.LastTime : twoDevice.LastTime;
return ret;
}
ArrayList softwares;
}
class Software
{
int id;
public ArrayList GetDevices()
{
return new SoftwareDAO().GetDevices(id);
}
}
class Device
{
public int ID;
public string Name;
public string Type;
public DateTime LastTime;
public int ExecNum;
}
函数重构完成后:
class SoftwareGroup
{
ArrayList GetAllDevices()
{
ArrayList devices = new ArrayList();
foreach (Software sw in softwares)
{
devices.AddRange(sw.GetDevices());
}
return new SoftwareUtil().SumDevices(devices);
}
}
class SoftwareUtil
{
public ArrayList SumDevices(ArrayList devices)
{
Hashtable allDevices = new Hashtable();
foreach (Device device in devices)
{
if (allDevices.ContainsKey(device.ID))
allDevices[device.ID] = device;
else
allDevices[device.ID] = Add(allDevices[device.ID] as Device, device);
}
return new ArrayList(allDevices.Values);
}
private object Add(Device oneDevice, Device twoDevice)
{
Device ret = new Device();
ret.ID = oneDevice.ID;
ret.Name = oneDevice.Name;
ret.Type = oneDevice.Type;
ret.ExecNum = oneDevice.ExecNum + twoDevice.ExecNum;
ret.LastTime = oneDevice.LastTime.CompareTo(twoDevice.LastTime) > 0 ? oneDevice.LastTime : twoDevice.LastTime;
return ret;
}
}
重构后,增加了一个辅助算法类,来完成device信息叠加功能。
通过重构得到的代码,有如下好处。首先方便了测试,重构前测试一个方法就是SoftwareGroup中的GetAllDevices,重构后,变成两个测试,一个同上,同时增加了一个SoftwareUtil中的SumDevices算法,方便了测试,主要侧重与算法的正确性。其次的好处是分清了类的职责,增加了个SoftwareUtil类,它的主要功能,就是把容器中的多个相同device的信息叠加起来,使得SoftwareGroup类的功能减少,职责更清晰。我平常写代码时,很多时候强迫让自己先写测试,然后写代码,那天因为习惯,顺手就写了代码。其实上面的重构,如果先写测试代码,就不会有这么大的重构变动了,因为如果开始写测试代码的话,会发现不容易测试,就会改变这个函数的涉及。测试驱动设计,此言不谬!
经常看博,但很少写,语言能力差,惭愧。第一次写博,语言有点混乱,辞不达意(其中的有些过程觉的一下没法说清楚,所以偷懒省略了),敬请谅解。
欢迎拍砖,更欢迎一起探讨!