Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Refactoring by applying design pattern

I have to write 3 functions which accepts a parameter of BaseClass type and then return a DerivedClasses as the return value.

Public DerivedClass1 SimpleTest1(BaseClass baseType)
{
DerivedClass1 derivedClass1 = new DerivedClass1();
derivedClass1.item = baseType.item;
derivedClass1.itemGroup = baseType.itemGroup;
return derivedClass1;
}

Public DerivedClass2 SimpleTest2(BaseClass baseType)
{
DerivedClass2 derivedClass2 = new DerivedClass2();
derivedClass2.item = baseType.item;
derivedClass2.itemGroup = baseType.itemGroup;
return derivedClass2;
}

Public DerivedClass3 SimpleTest3(BaseClass baseType)
{
DerivedClass3 derivedClass3 = new DerivedClass3();
derivedClass3.item = baseType.item;
derivedClass3.itemGroup = baseType.itemGroup;
return derivedClass3;
}

The code written in all the 3 methods is the same! Is there a better way to achieve this, without code duplication? Is there a specific design pattern that I can apply here?

like image 855
papfan Avatar asked Jan 28 '26 02:01

papfan


1 Answers

Use generics on this and you can express it fairly nicely:

public T SimpleTest<T>(BaseClass baseType) where T : BaseClass, new()
{
    T derived = new T();
    derived.item = baseType.item;
    derived.itemGroup = baseType.itemGroup;
    return derived;
}

There is one caveat that you have to have a default constructor or else this won't work. In instances where you have a constructor with one or more arguments (but the same signature for each), you can dynamically instantiate the class using Reflection, as in dbaseman's answer.

like image 144
Mike Bailey Avatar answered Jan 29 '26 14:01

Mike Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!