65.9K
CodeProject is changing. Read more.
Home

Refactoring Tips - Tip 10

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (5 votes)

Mar 3, 2010

CPOL
viewsIcon

5800

Refactoring Tips - Tip 10Tip 10 If the derived classes(or concrete/specialized classes) cant make use of all the functionalities (100% usage) of its base class(though it is a 'is a kind of' relationship among them, then prefer delegation/composition over...

Refactoring Tips - Tip 10 Tip 10 If the derived classes(or concrete/specialized classes) cant make use of all the functionalities (100% usage) of its base class(though it is a 'is a kind of' relationship among them, then prefer delegation/composition over Generalization/inheritance. Bad practice
public abstract class BaseClass
{
 abstract void Method1();
 abstract void Method2();
 //Some more methods....
}

public class Derived : BaseClass
{
 public override void Method1()
 {
  //Some processing...
 }

 public override void Method2()
 {
  //Actually this derived class doesnt need this method2...but since it is abstract in its base class, i have to override to getout of compilation issues...
 }

 //Some more methods...
}
Good practice
public class BaseClass
{
 public void Method1()
 {
  //Some processing
 }
 public void Method2()
 {
  //Some processing..
 }
 //Some more methods....
}

public class Derived 
{
 private BaseClass objBase;

 public Derived():this(new BaseClass())
 {
 
 }

 public Derived(BaseClass obj)
 {
  objBase = obj;
 }

 public void Method1()
 {
   objBase.Method1();
   //If needed some more derived class processing...
 }
 
 //Some more methods...
}
I hope this helps!. Regards, -Vinayak