Keep Public Interfaces away from Children

It is natural to think of the public methods and properties of a class as the public interface of the class. When implementing a class that is meant to be derived there is also another interface – the one meant for child classes. A clear separation of the two interfaces makes the code cleaner. The one construct to avoid is public virtual methods.

As an example, consider the following implementation for a car.

abstract class Car
{
    private static Random keyGenerator = new Random();
 
    private readonly int keySignature = keyGenerator.Next();
 
    public string Driver { get; set; }
 
    public void Start(Key key)
    {
        CheckSeat();
        CheckMirrors();
        if (BeforeStartEngine != null)
        {
            BeforeStartEngine(this, new EventArgs());
        }
        StartEngine(key);
    }
 
    public event EventHandler<EventArgs> BeforeStartEngine;
 
    protected bool IsKeyApproved(Key key)
    {
        return key.KeySignature == keySignature;
    }
 
    protected abstract void StartEngine(Key key);
 
    protected virtual void CheckSeat()
    {
        Debug.WriteLine("Checking seat settings for driver {0}", Driver);
    }
 
    protected virtual void CheckMirrors()
    {
        Debug.WriteLine("Checking mirrors settings for driver {0}", Driver);
    }
}

In this class there is one public method (Start), a public property (Driver) and a public event (BeforeStartEngine) that makes up the public interface. There are also a number of protected methods that makes up the interface for child (derived) classes.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.