oo design basics here…
Edit:
To clarify after first answer – I’m not asking how to fix this but whether on the face of it the design seems screwy. I don’t want to point out the original code for social considerations.
I’m working with some code that has a virtual method which does nothing but modify a private member variable of the class. I’d like to just change the details of that modification. That’s the only behavior I want to change, but I can’t reference the private member, so I can’t just override the method. On the face of it, is that design by the original author wrong/odd, or is this not enough information to say?
public class X
{
private List<string> InterestingThings = new List<string>();
public virtual void MethodIWantToOverride(string rawData)
{
string fixedData = ...
// do some fancy stuff to clean up data that I want to come thru 'dirty'
InterestingThings.Add(fixedData);
}
}
If the purpose of the code is to enforce some invariant upon items which get added to the list, requiring that all attempts to add items to the list go through a virtual method would be a way to achieve that. Exposing the list field as
protectedwould allow derived classes to violate the base-class invariant. If that’s what you’re trying to do, and if you will be upholding all portions of the invariant that code actually relies upon, you might make the list fieldprotected, but I would suggest that you at least consider adding another protected, possible virtual, base-class method to mutate it in a way that upholds a weaker invariant.