private or protected variables?

oop

Solution

In this case, the location of that image used to be a private, implementation-specific feature of the base class. Your new requirements meant that it needed to be able to vary from one derived class to another.

You should keep the member field private, but define a protected virtual property to expose it to derived classes:

private const string _defaultImagePath = @"C:\whatever.bmp";

protected virtual string ImagePath {
    get {return _defaultImagePath;}
}

In the derived class that wants to change it:

private const string _myImagePath = @"C:\other.bmp";
protected override string ImagePath {
    get {return _myImagePath;}
}

You will also want to change the base class so that it uses the property when it needs the image path, instead of using the field. This is the "Encapsulate Field" refactoring.

Problem

I am currently reading Code Complete where McConnell strongly encourages making all variables private. Coincedentally I just so happened to be working on a project where I needed to change a private variable. The class had a private variable (a `String`) telling it where to load an image from to use in the system chrome. I needed to change this image, I do not know about other languages but as far as I know in Flex/AIR, there is no way to override a private variable. If it had been declared protected, I could have simply extended the class, and overridden that variable. But since it was private, I had to copy all the code from the class and create a duplicate class with the only difference being that string. I think the argument is to use private as it makes for looser coupling between super and subclasses, however I had to completely violate DRY to be able to achieve a simple string change, which seems to me as worse. This makes me think that protected is better than private. However, I want to do things the right best-practices way. So if private is better, I want to understand why. If the general consensus is that private is better, can someone explain why?

Original source