Click here to Skip to main content
15,896,606 members
Articles / Programming Languages / C#
Tip/Trick

Refactoring Tips - Tip 10

Rate me:
Please Sign up or sign in to vote.
2.33/5 (5 votes)
2 Mar 2010CPOL 5.7K   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)


Written By
Architect MindTree Ltd
India India
Motivated achiever who guides organizations in applying technology to business settings, provides added value, and creates project deliverables in a timely manner. An experienced Technical Consultant, have successfully led large project teams of more than 20 people from requirements gathering to implementation and support using C#, .NET ,ADO.NET, ADO.NET Entity Framework,ASP.NET,ASP.NET MVC, WCF and SQL Server.

Comments and Discussions

 
-- There are no messages in this forum --