[C#] Encapsulation – Three Pillars of OOP (1)

Encapsulation, Inheritance, and Polymorphism; they are called three pillars of OOP.

Let’s look at the first pillar among three – Encapsulation. Subsequent posts will deal with other 2 pillars.

 

1. What is Encapsulation?

Encapsulation means how the language can hide object’s internal implementation details and preserve data integrity. Any consumers of  your objects (classes) only need to know how they can get the result as simple as possible without making mistakes.

Suppose you create the following simple “BankAccount” class. To make the code simple, the interest rate will be applied whenever we deposit any amount to the account.

public class BankAccount
{
    public double balance;
    public static double interestRate = 0.05;

    public BankAccount(double initialBalance)
    {
        balance = initialBalance;
    }

    public void Deposit(double amount)
    {
        balance += amount;
        ApplyInterest();
    }

    public void ApplyInterest()
    {
        balance *= (1 + interestRate);
    }
}

BankAccount account = new BankAccount(50);
account.Deposit(50);
Console.WriteLine(account.balance); // prints 105

It works anyway. But what’s the problem of this code?

Breaking encapsulation does not mean that your code will not work and you need to modify the code completely. The “BankAccount” class exposes too many information to class users unnecessarily.

  • First, users can access and modify the “interestRate” at any time. The interest rate should be remained the same value as it is initialized.
  • Secondly and more seriously, the “balance” can be directly modified at any time.
  • Thirdly, users can call “ApplyInterest()” methods as many times as they want to increase the balance.

All these problems happen because you declare all members as public so anybody can access and modify the data.

You might think it’s OK to make the members open to users because programmers are not dumb to make silly mistakes such as assign million dollars to the balance without checking it. I think you’re right. We do not make such mistakes. But still we are not perfect. Even though you are smart, others are not so smart as you are.

Your fellow developer also knew the business rules. He thought that the interest rate need to be added to the balance every time the deposit is made. So he implemented the code like this:

BankAccount account = new BankAccount(50);
account.Deposit(50);
account.ApplyInterest();

Now what happened? Your deposit method already called the “ApplyInterest()” method. So the “ApplyInterest()” method was called twice and an account owner will get more money. But the bank will not be happy about this.

Encapsulation helps to minimize this kind of errors by exposing only minimum set of class members to class users.

 

2. How to encapsulate a class

  • Set the fields to “private” and provide accessor methods for the required ones. C#’s property syntax will help you to declare setters and getters simpler than before.
  • If the methods need to be used inside the class, do not set them to “public“. Set them to “private” or “protected

You can write the “BankAccount” class again.

public class BankAccount
{
    private double balance;
    private static double interestRate = 0.05;

    public BankAccount(double initialBalance)
    {
        balance = initialBalance;
    }

    public double Balance
    {
        get { return balance; } // read only
    }
    public static double InterestRate
    {
        get { return interestRate; } // read only
    }

    public void Deposit(double amount)
    {
        balance += amount;
        ApplyInterest();
    }

    private void ApplyInterest()
    {
        balance *= (1 + interestRate);
    }
}

Calling the “ApplyInterest()” method outside of the class will cause a compile time error. Also you cannot set the balance or interestRate directly outside of the class, either.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s