11.6.Traditional Encapsulation Without Properties

Languages that don’t have properties will use methods (functions or procedures) for encapsulation. The idea is to manage the values inside of the object, state, avoiding corruption and misuse by calling code. Listing 10-1 demonstrates how this traditional method works, encapsulating Customer information via accessor methods.
Listing 10-1. An Example of Traditional Class Field Access

using System;
publicclass Customer
{
privateint m_id = -1;

publicint GetID()
    {
return m_id;
    }

publicvoid SetID(int id)
    {
        m_id = id;
    }

privatestring m_name = string.Empty;

publicstring GetName()
    {
return m_name;
    }

publicvoid SetName(string name)
    {
        m_name = name;
    }
}

publicclass CustomerManagerWithAccessorMethods
{
publicstaticvoid Main()
    {
        Customer cust = new Customer();

        cust.SetID(1);
        cust.SetName("Amelio Rosales");

        Console.WriteLine("ID: {0}, Name: {1}",
            cust.GetID(),
            cust.GetName());

        Console.ReadKey();
    }
}

Listing 10-1 shows the traditional method of accessing class fields. The Customer class has four methods, two for each private field that the class encapsulates: m_id and m_name. As you can see, SetID and SetName assign a new values and GetID and GetName return values.
Observe how Main calls the SetXxx methods, which sets m_id to 1 and m_name to “Amelio Rosales” in the Customer instance, cust. The call to Console.WriteLine demonstrates how to read m_id and m_name from cust, via GetID and GetName method calls, respectively.
This is such a common pattern, that C# has embraced it in the form of a language feature called properties, which you’ll see in the next section.

Yes No Suggest edit
Suggest Edit