Bob Tarr: Some Object-Oriented Design Principles(1): Minimize The Accessibility of Classes and Members

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

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 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;
}

  • You can perform arbitrary side effects
public double setSpeed(double newSpeed) {
speed = newSpeed;
notifyObservers();
}

  •  If users of your class accessed the fields directly, then they would each be responsible for executing side effects

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值