Sunday

Getters and Setters in design data type


Normally when we create a class, we always define Getters and Setters for instance variables to read and write its values. But it does not follow spirit of OOP/encapsulation. Encapsulation is a mechanism of hiding implemation details which process data from user, so the client should tell an Object what to do rather than asking an object about its state and telling it how to do.

Example:
CoordinateObject a = new CoordinateObject(1.0, 2.0);
CoordinateObject b = new CoordinateObject(3.0, 4.0);

// violates spirit of encapsulation
CoordinateObject c = new CoordinateObject(0.0, 0.0);
c.setX(a.getX + b.getX);
c.setY(a.getY + b.getY);

// better design
CoordinateObject a = new CoordinateObject(1.0, 2.0);
CoordinateObject b = new CoordinateObject(3.0, 4.0);
CoordinateObject c = a.plus(b);
(jbohn.blogspot.com)

0 comments:

Post a Comment