如何正确地重构这个大而且具有非常相似的代码if / else语句?

时间:2015-08-31 16:46:59

标签: c# if-statement refactoring

我试图重构这个更大的代码,我想知道哪个是更好的方法。

string obje = String.Empty;
long userId = 0;
long objNewId = 0;
long objOldId = 0;
string action = String.Empty;

if (oldObject.GetType() == typeof(FooDto))
{
    obje = ConstantParams.WCFLOG_APPLICATION_Foo;
    FooDto newFoo = (FooDto)response.Data;
    FooDto oldFoo = (FooDto)oldObject;

    userId = newFoo.UserApplicationId;
    objNewId = newFoo.Id;
    objOldId = oldFoo.Id;
}
else if (oldObject.GetType() == typeof(BarDto))
{
    obje = ConstantParams.WCFLOG_APPLICATION_Bar;
    BarDto newBar = (BarDto)response.Data;
    BarDto oldBar = (BarDto)oldObject;

    userId = newBar.UserApplicationId;
    objNewId = newBar.Id;
    objOldId = oldBar.Id;
}

action = (objOldId == 0) ? ConstantParams.WCFLOG_APPLICATION_NEW : ConstantParams.WCFLOG_APPLICATION_UPD;

string message = Helper.GenerateMessage(action, obje, userId, objNewId);

问题是有可能写出这样的东西,但我不知道这样的事情是否可能:

obje = ConstantParams.WCFLOG_APPLICATION_[[XXX]];
[[XXX]]Dto newItem = ([[XXX]]Dto)response.Data;
[[XXX]]Dto oldItem = ([[XXX]]Dto)oldObject;

userId = newItem .UserApplicationId;
objNewId = newItem .Id;
objOldId = oldItem .Id;

1 个答案:

答案 0 :(得分:1)

假设Foo,Bar和他们的对手都继承或实现了一个包含Id和UserApplicationId的公共类 - 让我们称之为SuperclassDto,因为你没有指定,这可以简单如下:

string obje = String.Empty;
long userId = 0;
long objNewId = 0;
long objOldId = 0;
string action = String.Empty;

obje = ConstantParams.WCFLOG_APPLICATION_Foo;

SuperclassDto newDto = (SuperclassDto)response.Data;
SuperclassDto oldDto = (SuperclassDto)oldObject;

userId = newFoo.UserApplicationId;
objNewId = newDto.Id;
objOldId = oldDto.Id;

action = (objOldId == 0) ? ConstantParams.WCFLOG_APPLICATION_NEW : ConstantParams.WCFLOG_APPLICATION_UPD;

string message = Helper.GenerateMessage(action, obje, userId, objNewId);

如果您的继承/实现层次结构不是这么简单,那么您应该能够强制进入这样的状态。