I have an abstract base class from which many classes are derived. I want derived classes to be able to override a virtual method defined in the base class, but there is complex logic in the base class that determines whether the overridden method is “enabled” at any particular 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 example above, IsMethodEnabled is shorthand for more complex logic that determines whether DerivedMethod should be called — it’s code that I want encapsulated in the base class so that I don’t have to reproduce it in each derived class.
The design works as intended. If I run this sample code:
AbstractBaseClass a1 = new DerivedClass() { IsMethodEnabled = false };
AbstractBaseClass a2 = new DerivedClass() { IsMethodEnabled = true };
a1.Method();
a2.Method();
…I see exactly one call to DerivedMethod, as expected.
But something rubs me wrong about this implementation. I feel like there must be a more elegant way to handle this. Is there a better way to selectively call a derived class’s method implementation from its abstract base class? Is there a design pattern that would better serve me here?
In other words, does the code above “smell”?
This is a perfectly reasonable implementation.
The main changes I would suggest are:
protectedinstead of publicpublic void Method()andprotected virtual void OnMethod()