简体   繁体   中英

Force One of Two Method Implementations In A Child Class

I have an abstract method in a base class declared like so...

public abstract void StartHere();
public virtual void StartHere(string flag)
{   
    switch(flag)
    {
        default : StartHere(); break;
    }
}

Is there any way to change it so that the inheriting child class is forced to implement one or the other, but not both? Currently the child class is forced to implement only StartHere().

Also would you say its good practice to have the default virtual method point back to the parameterless abstract? or is this just pointless?

The function of this method is to setup the class, the programmer can either do a simple setup using StartHere() or a more complicated one taking in a flag StartHere(string).

Thank you!

Generally, it would be wise for the parameter less function to call the Para-metered function by passing the default values. This is called Function chaining.

I'd prefer a different design, something like:

public void StartHere();
public virtual void StartHere(string flag)
{
    StartHere();
}

Because in this case, the parent class and the child classes are more loosely-coupled: the parent class don't have to know anything about the * flag *s that only child classes are interested in.

If you have to follow your current design for some reason, I suggest you at least change the following lines:

    switch(flag)
    {
        default : StartHere(); break;
    }

to something like:

    switch(flag)
    {
        "DEFAULTFLAG" : StartHere(); break;
        default : throw ArgumentException(
            String.Format("Unrecognized flag '{0}'!", flag)
            );
    }

It's easier for you to catch unintended errors when you set wrong flags by mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM