The Meaning of Abstraction
- Tony Hoare: “Abstraction arises from a recognition of similarities between certain objects, situations, or processes in the real world, and the decision to concentrate upon those similarities and to ignore for the time being the differences.”
- Grady Booch: “An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.”
- Abstraction is one of the fundamental ways to deal with complexity
- An abstraction focuses on the outside view of an object and separates an object’s behavior from its implementation
Encapsulation
- Grady Booch: “Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation.”
- Craig Larman: “Encapsulation is a mechanism used to hide the data, internal structure, and implementation details of an object. All interaction with the object is through a public interface of operations.”
- Classes should be opaque
- Classes should not expose their internal implementation details
Information Hiding In Java
- Use private members and appropriate accessors and mutators wherever possible
- For example:
Replace
public double speed;
with
public double speed;
with
private double speed;
public double getSpeed() {
return(speed);
}
public void setSpeed(double newSpeed) {
speed = newSpeed;
}
Use Accessors and Mutators, Not Public Members
- You can put constraints on values
public void setSpeed(double newSpeed) {
if (newSpeed < 0) {
sendErrorMessage(...);
newSpeed = Math.abs(newSpeed);
}
speed = newSpeed;
}
if (newSpeed < 0) {
sendErrorMessage(...);
newSpeed = Math.abs(newSpeed);
}
speed = newSpeed;
}
- If users of your class accessed the fields directly, then they would each be responsible for checking constraints
- You can change your internal representation without changing the interface
// Now using metric units (kph, not mph)
public void setSpeedInMPH(double newSpeed) {
speedInKPH = convert(newSpeed);
}
public void setSpeedInKPH(double newSpeed) {
speedInKPH = newSpeed;
}
public void setSpeedInMPH(double newSpeed) {
speedInKPH = convert(newSpeed);
}
public void setSpeedInKPH(double newSpeed) {
speedInKPH = newSpeed;
}
- You can perform arbitrary side effects
public double setSpeed(double newSpeed) {
speed = newSpeed;
notifyObservers();
}
speed = newSpeed;
notifyObservers();
}
- If users of your class accessed the fields directly, then they would each be responsible for executing side effects