一天一个重构方法(24):提炼类
2009-08-13 23:58:24Extract class:提炼类
你也许听过类似这样的教诲:一个class应该是一个清楚的抽象,处理一些明确的责任。但是在实际工作中,class会不断成长扩展。于是随着责任不断增加,这个class会变得很复杂。很快这个class就会变成一团乱麻。建立一个新的class,将相关的字段和方法从旧class搬移到新class。
public class Person
{
public string GetName()
{
//other code
}
public void SetName(string name)
{
//other code
}
public string GetTelephoneNumber()
{
//other code
}
public string GetOfficeAreaCode()
{
//other code
}
public void SetOfficeAreaCode(string areaCode)
{
//other code
}
public string GetOfficNumber()
{
//other code
}
public void SetOfficNumber(string number)
{
//other code
}
}
这个例子中,可以将与Office相关的行为分离到一个独立的class中。
public class Person
{
public string GetName()
{
//other code
}
public void SetName(string name)
{
//other code
}
public string GetTelephoneNumber()
{
//other code
}
}
public class Office
{
public string GetOfficeAreaCode()
{
//other code
}
public void SetOfficeAreaCode(string areaCode)
{
//other code
}
public string GetOfficNumber()
{
//other code
}
public void SetOfficNumber(string number)
{
//other code
}
}
当然,上面的实例没有任何价值,只是说明某个class如果做了两个classes做的事,就可以分离这个类。
这样的class往往含有大量方法和字段。此时你需要考虑哪些部分可以分离出去,并将它们分离到一个独立的class中。如果某些字段和方法总是一起出现,如果某些字段经常同时变化甚至彼此相依,这就表示你应该将它们分离出去。你应该做一些测试,如果你搬移了某些字段和方法,会发生什么事?