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.
abstractclass Car
{privatestatic Random keyGenerator =new Random();privatereadonlyint keySignature = keyGenerator.Next();publicstring Driver {get;set;}publicvoid Start(Key key){
CheckSeat();
CheckMirrors();if(BeforeStartEngine !=null){
BeforeStartEngine(this, new EventArgs());}
StartEngine(key);}publicevent EventHandler<EventArgs> BeforeStartEngine;protectedbool IsKeyApproved(Key key){return key.KeySignature== keySignature;}protectedabstractvoid StartEngine(Key key);protectedvirtualvoid CheckSeat(){
Debug.WriteLine("Checking seat settings for driver {0}", Driver);}protectedvirtualvoid CheckMirrors(){
Debug.WriteLine("Checking mirrors settings for driver {0}", Driver);}}
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.