Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Refactoring Tips - Tip 10

2.33/5 (5 votes)
2 Mar 2010CPOL 1  
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


C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)