views:

60

answers:

2

I have a main class that has a Sub procedure with no implementation. Any derived class should override and implement this procedure, so I used MustOverride in the base class.

Now, any time this procedure is called, I need to set a specific Boolean variable to True at the beginning of the procedure and set it to False at the end.

Is there a way to avoid writing these two lines of code in procedure implementation of every single derived class? Can I set this value to True in the base class, then run procedure in the derived class and then set the value back in the base class?

Thank you in advance.

+3  A: 

When I have scenarios where a derived class needs to override a method, but I want specific things to happen before or after the overridden method code, I split it into two methods. Something like this (very simplified):

VB.NET version:

Class BaseClass
    Public Sub DoWork()
        ' perform pre-steps ' 
        DoWorkImpl()
        ' perform post-steps '
    End Sub

    Protected MustOverride Sub DoWorkImpl()
End Class

Derived classes will override DoWorkImpl, but the method cannot be called from the outside, since it is protected. Only DoWork can be called from the outside, ensuring that the pre- and post steps are always performed.

Fredrik Mörk
+1  A: 

The way I would do this is break the work up into 2 methods. The first method would be non-virtual on the base class and would take care of setting the Boolean value. It would then call the second MustOverride method. For example

Sub Method()
  MyValue = True
  Try 
    MethodCore()
  Finally
    MyValue = False
  End Try
End Sub

Sub MustOverride MethodCore() 
JaredPar