Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring abstract class in C#

Sorry if this sounds simple, but I'm looking for some help to improve my code :)

So I currently have the following implementation (which I also wrote):

public interface IOptimizer
{
    void Optimize();
    string OptimizerName { get; }
}

public abstract AbstractOptimizer : IOptimizer
{
    public void Optimize()
    {
        // General implementation here with few calls to abstract methods
    }
}

public abstract AbstractPriorityOptimizer : AbstractOptimizer 
{
     // Optimize according to priority criteria.    

     string Name 
     { 
        get { return "Priority Optimizer"; }
     }      
}

Then I have technology-specific concrete classes:

TechnologyXPriorityOptimizer : AbstractPriorityOptimizer 
TechnologyYPriorityOptimizer : AbstractPriorityOptimizer 


Now I'm trying to add a generic optimizer, one that optimizes for conditions other than priority, so my attempt:

public abstract AbstractGenericOptimizer : AbstractOptimizer 
{
     // Optimize according to a generic criteria.    

     private readonly int param;

     public AbstractGenericOptimizer (int param) : base()
     {
          // param affects the optimization
          this.param = param;
     }        
}

and I also need technology-specific implementation just like the priority optimizer:

TechnologyXGenericOptimizer : AbstractGenericOptimizer 
TechnologyYGenericOptimizer : AbstractGenericOptimizer 


Q1. TechnologyXPriorityOptimizer and TechnologyXGenericOptimizer have the same exact "extra" methods because they involve the same technology. Is there a way to keep this method common to both inheritance branches ?

Q2. For AbstractGenericOptimizer, the optimizer has a special name for special values of the int param, so would it be a good idea to extend the base generic optimizer class (where param is hardcoded) and then for every division, have a technology-specific implementation:

AbstractSpecialName1Optimizer: AbstractGenericOptimizer
TechnologyXSpecialName1Optimizer: AbstractSpecialName1Optimizer
TechnologyYSpecialName1Optimizer: AbstractSpecialName1Optimizer

AbstractSpecialName2Optimizer: AbstractGenericOptimizer
....

What would be the best way to refactor this scenario ? I feel that there is a smarter way of reducing the number of inheritance levels.

Thanks!

like image 963
alhazen Avatar asked Feb 04 '10 20:02

alhazen


1 Answers

You should probably use containment instead of inheritance.

For example, you could make an abstract OptimizerStrategy class with concrete implementations for each technology, then make the GenericOptimizer and PriorityOptimizer take an OptimizerStrategy as a generic type argument or constructor parameter.

like image 94
SLaks Avatar answered Oct 04 '22 22:10

SLaks