New Design Guideline: Avoid Protected Static

Here is a minor update to the design guidelines around subclassing. It is based on this quiz I did a last week. Please let me know if you have any questions or comments.  

As always, you can check out the base design guidelines and my incremental updates.

Avoid Protected Statics. Carefully consider what information you expose in and use from static protected data because parallel subclass can access it. Consider the following example. Even though Child and Malicious are parallel and unrelated, Malicious is able to access state the Child sets. The core issue here is that sensitive data should not be exposed as protected as any arbitrary subclass can use access it. FxCop rule <tbd> flags any protected static member for review of this issue.

    public class Base

    {

        static protected String _password;

    }

    public class Child : Base

    {

        static Child()

        {

            _password = "Darb";

        }

    }

    public class Malicious : Base

    {

        public static String StealPassword()

        { return _password; }

    }  

Notice, any subclass of Base can access _password, the Child class is not required.

Annotation (BradA): Notice that, unlike C++, the runtime does eliminate this problem for protected instance data as a subclass is only allowed to access instance data through its own type. In the example below Malicious is not allowed to access _password through an instance of Child.

    public class Base

    {

         protected String _password;

    }

    public class Child : Base

    {

        public Child(string password)

        {

            _password = password;

       }

    }

    public class Malicious : Base

    {

        public String StealPassword(Child child)

        { return child._password; }

    }