Farhad Alizadeh Noori
Farhad Alizadeh Noori

Reputation: 2306

Declare most complex method in base class as virtual

I've been reading the book CLR via C# by Jeffrey Richter and he argues that when defining a method in a base class, If there is a method you want to declare as virtual and it has a few convenience overloads, the most complex method should be the virtual method and the others should be left as non-virtual. Here is the example he gives:

public class Set {
    private Int32 m_length = 0;
    // This convenience overload is not virtual
    public Int32 Find(Object value) {
        return Find(value, 0, m_length);
    }
    // This convenience overload is not virtual
    public Int32 Find(Object value, Int32 startIndex) {
        return Find(value, startIndex, m_length - startIndex);
    }
    // The most feature-rich method is virtual and can be overridden
    public virtual Int32 Find(Object value, Int32 startIndex, Int32 endIndex) {
        // Actual implementation that can be overridden goes here...
    }
    // Other methods go here
}

What is the rational here?

Upvotes: 3

Views: 148

Answers (4)

Victor Zakharov
Victor Zakharov

Reputation: 26454

The answer is - DRY principle - a single source of truth. There is method A which is most complex. B, C and D all use subsets of its functionality. So the programmer created this way, and all further code modifications are based on the assumption you keep relation between A, B, C, D. If you allow all of B, C, D be overridable, you are breaking the idea that was put in the class.

Code readability suffers, people read your base class, compose a picture of how it can work, then read your class, and figure that what they just learned is not the case with YOUR implementation. Makes team work hard. Also when you are reading your code 5 years later (if it needs to happen).

Upvotes: 3

Sinatr
Sinatr

Reputation: 22008

There is only one implementation, other overloads are simply forwarding a call. Making that one virtual make sense, as forwarding will still be working when implementation is overriden.

Upvotes: 0

Brian Rasmussen
Brian Rasmussen

Reputation: 116471

The reason is that all the simpler methods are implemented by calling the virtual method. If these were made virtual you could potentially break this contract. By only allowing you to change the implementation specializations of this class will follow the same contract for these methods.

Upvotes: 2

Dan
Dan

Reputation: 10548

I would agree with Jeffrey; it makes sense to make virtual the most complex member as calls to the 'lesser' complex members will invoke the most complex one as they are called via method chaining. Further, it stands that the most complex member would likely be the one that contains all the parameters required to execute the function without any external dependencies.

I'll expand on this later on, if I can.

Upvotes: 0

Related Questions