Search code examples
c#staticfieldencapsulation

In C# if it recommended that I always declare my instance fields private (encapsulation) should I also always declare my static fields as private?


public class Person
{
    private string _name; // always recommended to be private

    private static string s_homePlanet; // recommended?
}

As mentioned in the question the practice of encapsulation recommends that I always declare my instance fields as private. To keep an instance's information as hidden.

According to Fields (C# Programming Guide)

"Generally, you should use fields only for variables that have private or protected accessibility."

According to C# Field Design

"The principle of encapsulation is one of the most important notions in object-oriented design. This principle states that data stored inside an object should be accessible only to that object. This interpretation immediately implies that all fields must be private."

I know a static field stores information that is shared amongst instances of a type; thus, the informaton stored within a static field is not specific to any instance. With that being said is it reccomded that I always declare a static field as private???


Solution

  • Yes, with the same logic: a static field should only be accessible from that class, and its content should only ever be exposed via getters and setters. This has several benefits:

    • The class code can enforce the consistency of its internal state. If you have a public field, then any other class can mess with its content, with no guarantees that the assumptions of the class will still hold. (e.g. if a Window class holds instances static field that lists all the creaated windows, if it is public, foreign code could empty that list)

    • If sometime in the future you decide you would like to have side-effects to setting or reading a field (e.g. log whenever it changes), it is easy to do if you use a setter and getter functions; but if you allow public access to a field, you would have to refactor your code into using getters and setters.

    • If you decide to change the internal workings of your class, even restructure your fields, as long as all the methods have the same signature you can do this easily if the only access to them is via the defined methods. However, if you expose the data, then it is not possible to restructure it if you wish to remain backward-compatible.

    None of these reasons change if the field is a class field or an instance field.