Search code examples
c#propertiesfieldencapsulation

Where's the Encapsulation?


I'm a new programmer, so please excuse any dumbness of this question, how the following code is encapsulating private data? -

public class SomeClass
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public SomeClass(int age)
    {
        this.age = age;
    }
}

I mean, with no restriction logic or filtering logic in the properties, how is the above code different from the folowing one -

public class SomeClass
{
    public int age;

    public SomeClass(int age)
    {
        this.age = age;
    }
}

Is the first code providing any encapsulation at all?


Solution

  • It's providing one piece of encapsulation: it's saying, "there's an Age property you can get and set, but I'm not going to tell you how I'm implementing it."

    That's not very strong encapsulation, but it does keep the implementation details separate from the public API. Without changing the public API at all, you could start to store the age somewhere else - in two short fields, in a service somewhere, as part of a long field or whatever. You could put logging in the property to see how often it's used. You could add an event which gets fired when the age changes (that's an API change, but won't break existing callers).

    EDIT: One thing to note: even though this does nothing now, the change to make it do something later is both source and binary compatible. Changing a field to become a property is not backward compatible, either in source or binary forms. In most cases it will be source-compatible, but not binary-compatible. In some cases source will no longer build. In more evil (and contrived, admittedly) both versions will build, but with different effects.

    Also note that as of C# 3, you can declare a trivial property as easily as a field:

    public int Age { get; set; }
    

    I have an article about all of this which provides more details.