tags:

views:

152

answers:

5

I've never really been poised with this question: But would it be a terrible crime to call base.SomeMethod() conditionally in an overriden 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.

Thanks everyone!

+7  A: 

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.

Kevin
+6  A: 
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.

leppie
+2  A: 

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)

Sergio
Are you missing the 'conditionally' part?
leppie
@leppie: No. The "do something more" can include conditionals
Sergio
+1  A: 

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.

Philip Wallace
That might justify another class (specialization) :)
leppie
@leppie - doesn't inheriting a class count as creating another class? Take this example: class CSharpProgrammer inherits class Programmer... CSharpProgrammer is a specialised class based on Programmer.
Philip Wallace
+1  A: 

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.

LBushkin
This is why `sealed` should be the default in C#; or at the very least, be able to put `base` where can put `sealed`.
Dan