Search code examples
c#propertiesencapsulation

Maintaining encapsulation with properties and methods


If I have a class as follows:

public class Name
{
    public String FirstName { get; set; }
    public String LastName { get; set; }

    public String FullName()
    {
        return FirstName + " " + LastName;
    }
}

FullName() concatenates the first and last names so it makes sense for it to be a method. Suppose I change how the class works so it stores the full name as a string and FirstName and LastName return substrings. It would then make sense for FirstName and LastName to be methods and FullName to be a property. I read these guidelines on where to use properties which states that properties should not be interdependent.

Doesn't using properties and methods break encapsulation as it means you are exposing your internal implementation details to external code?

In cases like this where you don't want to expose which values are stored and which are derived what should you do? Presumably they should all be methods or they should all be properties but which?


Solution

  • It is arguable if properties should or should not be independent.

    I would say that in your case, having property

    public String FullName { get { return FirstName + " " + LastName; } } // no set
    

    looks acceptable.

    Compare with .NET Rectangle.Bottom property, which returns sum of two other properties

    The y-coordinate that is the sum of Y and Height of this Rectangle.