lundi 31 août 2015

How to correctly refactorize this big and with very similar code if/else statements?

I'm trying to refactorize this code that would be much more bigger and I'm wondering wich is the better way to do it.

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);

The thing is that it may be possible to write something like this but don't know if something like that is possible:

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;

Aucun commentaire:

Enregistrer un commentaire