Search code examples
c#methodspropertiesencapsulation

Encapsulation in relation to automatic properties


Please look at this simple implementation of a customer class:

class Customer
{
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

    public Customer(double purchases, string name, int ID)
    {
        TotalPurchases = purchases;
        Name = name;
        CustomerID = ID;
    }
}

I noticed that there is a get and set option for customer name. Let's say I need to change the customer name.

Is it more acceptable to change the customer name through a method like so:

public void changeName(string name)
{
    this.Name = name;
}
Customer cus = new Customer(5,"John",5005);
cus.changeName("Jim");

Or is it acceptable to change it by just doing:

cus.Name = "Jim";

Solution

  • Having a method to alter a property is unnecessary. The reason properties exist is to allow you to implement additional logic around the access of a field. In essence, the property creates a private field and automatically generates accessor/mutator methods.

    A property like public string Foo { get; set; } is equivalent to

    private string foo;
    public string Foo 
    {
        get
        {
            return foo;
        }
        set
        {
            foo = value;
        }
    }
    

    So, for example, you could implement additional logic:

    private string foo;
    public string Foo 
    {
        get
        {
            return foo.Trim();
        }
        set
        {
            if (value == "bar") 
            {
                throw new Exception("validation");
            }
            foo = value;
        }
    }