lundi 5 août 2019

Should I use a Design Pattern to put logic from my abstract base class somewhere else?

I'm currently working on a .NET 4.7.1 application. We don't use Dependency Injection in our project.

I implemented an abstract base class for my message handlers.

Currently I have one common logic method in my abstract base class which is not used in all inheriting sub classes. It actually messes up my inheriting classes somehow, because it adds logic which is not necessary in all inheriting sub classes.

Perhaps I should put the logic into a separate class, or perhaps you know a good design pattern to use? Though, I'm not quite sure about it. My code looks like this:

public abstract class BaseVegetableHandler
{
   public virtual int HandleMessage(string message) => throw new NotImplementedException();

   // this method has logic which is used in some inheriting sub classes, but not all -> where should I put this logic?
   protected void SaveSalad(string vegetables) 
   {
      // some logic, which is only used in some inheriting classes, but not all!
   }
}

public class TomatoHandler : BaseVegetableHandler
{
   // Handle message is overriden in all inheriting sub classes
   public override HandleMessage(string message)
   {
      // some logic and then:
      SaveSalad(vegetables); // => this method is implemented in my abstract base class, but not used in all inheriting classes, nor can be used in all inheriting classes... where should I put this logic?
   }
}

// I thought about putting this logic into its own helper/handler class, this way I could just create a new instance in each class, that needs the logic:
public class SaladHelper
{
   public void SaveSalad(string vegetables) 
   {
      // some logic
   }
}


I'm not sure if I should leave the logic for SaveSalad in my abstract base class or put it somewhere else?

What do you think, what is the best place to some logic which is used by several inheriting classes, but not all - neither can be used by all inheriting classes?

Thank you very much!

Aucun commentaire:

Enregistrer un commentaire