Tuesday, August 6, 2013

Encapsulation - A simple approach to OOP

We wrote a class. And some other developers will use it. And somehow we want to change our class because others use it for their purposes in a way that we don't want to be. It is like there is a variable in our class and we don't want it to be less than zero , but the developers who use our class can easily change it to any value because lack of our code quality.
Take a look at this code.
class BadClass {
    
    // public unprotected variables
    // any one who has an instant can change them to any value
    public int age;
    public String name;
 }

public class UseBadClass {

    public static void main(String[] args) {
        BadClass b = new BadClass();

        //Since we can access the age variable directly
        //we can change it to any value
        b.age = -10;

        //this assignment is not illegal. But obviously an age cannot be negative !! 
        //So this is bad and we have to stop this been happening. 

    }
}

Think that now we want to change our class. Will our changes affect other codes ? Will our changes bring errors to others codes. ?
That means our code not supporting flexibility and maintainability (which are two main benefits of OOP ).So we have to write our code in a way that it supports flexibility and maintainability . The ability to make changes in our implementation code without breaking others code who use our code is a key benefit of ENCAPSULATION.
The idea of ENCAPSULATION is hiding information behind a Public Programming Interface. That means our codes API. !!
To do that we have to keep instance variables protected (by making them private). and make public methods to access the variables and force others to use them. (our API)
after that our code will looks like this
 
  
class BadClass {

    //protect the instance variables 
    private int age;
    private String name;

    // make publicly accessible methods   
    // we can now protect our code and others as well !!
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class UseBadClass {

    public static void main(String[] args) {
        BadClass b = new BadClass();

        b.setAge(-10);

        // (-10) will not be assigned 
        System.out.println(" age = " + b.getAge());
    }
}

A well protected code !!! :)

2 comments:

Post a Comment