When data encapsulation is a bad idea

One of the basic concepts of Object-oriented programming is the data encapsulation principle. This princible says that you have an object which has it’s internal state private and provides public methods which forms the interface of the object and which is responsible for mutating the internal state. The internal state cannot be mutated directly from the client. This has the advantage of separation of the interface of the class with the internal implementation, so one can change the implementation without touching the interface used by client code.

However there is a case where we have plain data transfer objects with no logic. Those objects simple carry data and have no methods to perform logic on their state. For example consider that we have a point object which contains x,y coordinates:

class Point {
    private float x;
    private float y;

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public void setX(float x) {
        this.x = x;
    }

    public float getX() {
        return x;
    }

    public void setY(float y) {
        this.y = y;
    }

    public float getY() {
        return y;
    }
}

This is just a waste. The encapsulation pattern is simply redundant here, and the reason is that the class is used only for carrying data and have no logic to hide. So by this way we introduce unnecessary boilerplate code, and also introduce overhead of virtual method calling(which on some systems like Android) may make a difference.

In those situations is better to leave the fields public and remove all the accessor and mutator methods. That way we can directly access the fields without the burden of accessor/mutator methods and without breaking the data hiding principle(since this must be applied only on objects containing logic)

class Point {
    public float x;
    public float y;

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }
} 

Point myPoint = new Point(10.5,15.2);

//Directly accessing data members
float x = myPoint.x;
myPoint.x = 5.5;

When NOT to apply this
This should be applied only in the case where your objects will be used to transfer data(for example serialized and transfered through a network) and containing NO logic. If we are unsure about planning to add logic later, then we should implement data hiding. The reason for that is that if we decide later to add logic to the class we will hide the members, and that will result breaking client code which uses this

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s