Declare the most complex method in the base class as virtual

I read a CLR via C # book by Jeffrey Richter and he claims that when defining a method in a base class. If there is a method that you want to declare as virtual, and it has several convenience overloads, the most complex method should be the virtual method, and the rest should be left as non-virtual. Here's an 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 rational here?

+3


source to share


4 answers


Answer: The DRY principle is the only source of truth . There is Method A, which is the most difficult. B, C, and D use subsets of their functionality. Thus, the programmer created this method, and all further modifications to the code are based on the assumption that you keep the relationship between A, B, C, D. If you allow all B, C, D to be advanced, you violate the idea that was put in class.



Reading the code suffers, people read your base class, draw up a picture of how it might work, and then read your class and assume that what they just learned does not apply to YOUR implementation. Strengthens team work. Also when you read your code 5 years later (if needed).

+3


source


The reason is that increasingly simple methods are implemented by calling a virtual method. If they were made virtual, you could violate this contract. Only by allowing you to change the specialization of the implementation of this class will follow the same contract for these methods.



+2


source


I would agree with Geoffrey; it makes sense to make the most complex element virtual, since calls to the "smaller" complex members will invoke the most complex, since they are called through the method chain. In addition, he argues that the most complex element is likely to be the one that contains all the parameters required to execute the function without any external dependencies.

I'll talk about this later if I can.

0


source


There is only one implementation, the other overloads simply redirect the call. Making this virtual

makes sense as the redirection will work when the implementation is overridden.

0


source







All Articles