Calling an overridden base method conditionally in C#
I've never really been poised with this question: But would it be a terrible crime to call base.SomeMethod() conditionally in an overridden method?
开发者_运维问答Example as in:
protected override void SomeMethod()
{
if( condition > 0 )
base.SuperMethod();
}
I'm aware that this may be considered bad practice but I've actually never read such a claim so far.
I can't think of a reason why this would be bad off the top of my head.
It'd be a lot worse to override the base method and copy the base method's functionality to conditionally call instead of just calling the base method.
class HardHearingPerson : Person
{
override void Listen()
{
if (volume.Acceptable())
base.Listen();
}
}
Guess it depends on the context, but I am sure it could have justified usage.
I do this quite often. Every time I need to "do something more" in a method I override it do my stuff and invoke the base method (or vice versa)
I think it is totally acceptable. You might want to override the behaviour of a base class method only under certain circumstances, or extend the behaviour by calling the base method then doing your own thing.
Classes should be designed for inheritance:
If the base class is designed in a manner where calling base versions of certain methods is optional then it's ok to omit those calls.
If the base class is designed in a manner where base versions MUST be called then it is not ok to omit them.
Discussing whether this is a "good practice" misses the point, in my opinion. The way in which a class is structured for inheritance is based on its purpose and design. The decision of whether you MAY or MUST call base versions of a method is part of the classes public interface, with respect to inheritance.
You can't decide when it will be desirable or not desirable to call a base class method when you override without understanding how the base class is designed and what purpose each method serves.
精彩评论