Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to expose protected fields

I have a base class like this:

 public class BaseModalCommand
 {

    protected object m_commandArgument;
    protected int m_commandID;
    protected int m_enableUIFlags;

    public virtual void OnIdle()
    {
    }

    public virtual void OnResume()
    {
    }

    public virtual void OnStart(int commandID, object argument)
    {
    }

    public virtual void OnStop()
    {
    }



    public virtual int EnableUIFlags
    {
        get
        {
            return this.m_enableUIFlags;
        }
    }
}

The virtual methods are to be overridden in derived types. If I run it thru FxCop, it complains about not declaring visible instance fields and recommends changing it to private and exposing it as a protected property.

Any thoughts? I'm thinking this message can be ignored.

like image 528
Sunit Avatar asked Nov 28 '22 00:11

Sunit


1 Answers

For any class, there are two kinds of uses by client code: code that references your class, and code that inherits your class. It's widely recognized that the second kind of use by far the most tightly coupled. Changes in your class directly affect their internal mechanics. Your exposing protected members like this means that changes in your base class will affect how your derived classes work in ways that are unpredictable without comparing the code of each base and derived class. Equally bad, your derived classes can modify the internals of the base class.

If you really want to expose internal data members like this, wrap private data members in protected properties (as gisresearch suggests). These properties (along with any protected methods) constitute the inheritance interface of your class. Like any interface exposed to outside clients (whether through just defining public methods and properties, or through explicit interface implementation), this interface is something you will need to manage, particularly in larger code bases. An interface can be changed, but should be changed as a conscious decision.

If you work with protected data members directly, you have much less control over the dependencies between base and derived classes. Trust me on this: not even being able to determine what effects a change may have can be a Very Unpleasant Thing.

like image 195
Pontus Gagge Avatar answered Dec 12 '22 02:12

Pontus Gagge