I have an abstract base class from which many classes are derived. I want derived classes to be able to override the virtual method defined in the base class, but there is complex logic in the base class that determines if the overridden method is included at any given moment.
Consider this code - one possible solution - for example:
public abstract class AbstractBaseClass { public bool IsMethodEnabled { get; set; } public virtual void DerivedMethod() { } public void Method() { if (IsMethodEnabled) DerivedMethod(); } } public class DerivedClass : AbstractBaseClass { public override void DerivedMethod() { Console.WriteLine("DerivedMethod() was called."); } }
In the above example, IsMethodEnabled is a shorthand for more complex logic that determines whether DerivedMethod should be called - this is the code I want to encapsulate in a base class so that I don't have to reproduce it in every derived class.
The project works as intended. If I ran this sample code:
AbstractBaseClass a1 = new DerivedClass() { IsMethodEnabled = false }; AbstractBaseClass a2 = new DerivedClass() { IsMethodEnabled = true }; a1.Method(); a2.Method();
... I see exactly one DerivedMethod call, as expected.
But something spoils me wrong in this implementation. I feel that there should be a more elegant way to handle this. Is there a better way to selectively invoke a method implementation of a derived class from its abstract base class? Is there a design template that would serve me better here?
In other words, does the code above smell?
source share