ADT的RI和AF

ADT

ADT也叫抽象数据结构,主要有如下意义:

  • Abstraction(抽象): Omitting or hiding low-level details with a simpler, igher-level idea.
  • Modularity(模块化): Dividing a system into components or modules, eachof which can be designed, implemented, tested, reasoned about, andreused separately from the rest of the system.
  • Encapsulation(封装): Building walls around a module (a hard shell orcapsule) so that the module is responsible for its own internal behavior,and bugs in other parts of the system can’t damage its integrity.
  • Information hiding(信息隐藏): Hiding details of a module’s implementation from the rest of the system, so that those details can be
    changed later without changing the rest of the system.
  • Separation of concerns(关注点分离):Making a feature (or “concern”) the responsibility of a single module, rather than spreading it across multiple modules. 模块具有单独的责任,不要将一个责任分散在不同的模块中

UserDefined Types,即用户自定义类型

对于抽象数据类型操作有如下分类:

  • Creators create new objects of the type. 产生类型的新对象
    • 例如构造函数
    • t* → T
  • Producers create new objects from old objects of the type. 在已有对象基础上产生新的对象
    • String里的concat()
    • T+, t* → T
  • Observers take objects of the abstract type and return objects of a different type. 输入抽象类型的对象,返回其他类型的对象
    • List里面的size()
    • T+, t* → t
  • Mutators change objects. 改变对象
    • List的add()
    • T+, t* → void | t | T
      (T表示本类,t表示其它类,正则表达式)

基本数据类型也有如上操作,例如int:

  • creators: the numeric literals 0 , 1 , 2 , …
  • producers: arithmetic operators + , - , * , /
  • observers: comparison operators == , != , < , >
  • mutators: none (it’s immutable)

ADT的设计原则:

  • 设计一组简单操作,通过简单操作的组合实现复杂的操作
  • 操作的行为应是内聚的(单一职责),某个操作不要包罗万象的将所有特例都考虑进去,比如List中不应增加sum方法,缺乏通用性
  • 操作集应该是完备的,覆盖该类型所有应支持的行为
    • 判断方法:检查对象的每个需要被访问到的属性是否都能够被访问到
  • ADT不应该混合领域无关的(通用的)和领域特定的特征

Rep Invariant(RI)and Abstraction Function(AF)

在实现ADT时有如下两个空间
R: 实现时用到的值空间
A: 被表示的空间
ADT的RI和AF_第1张图片
对于R与A满足
R到A:一定满射,不一定单射

AF:抽象函数R->A
RI:R → boolean

也就是说:AF描述内存到实际的映射,RI告诉我们空间R中的r是否被AF映射到了空间A中的某个值,故而RI形成了空间R的一个子集(子集中的所有元素均被AF映射到了空间A中)

书写RI与AF
  • 应该写在类里面
    例如:ADT的RI和AF_第2张图片
  • AF和 RI 既不由选定的表示值空间决定,也不由抽象值空间单独决定

RI与AF对ADT设计的影响
使用断言技术检查不变性可以更早地捕获bug
即checkRep();
ADT的RI和AF_第3张图片
应该在所有creators,producers, and mutators类型方法的最后检查不变性

这里介绍一个概念:
**表示泄露(representation exposure):**指 类外的某个代码可以直接修改表示形式

故而对表示泄露安全相关的参数,特别是输入参数和返回值,给出保证不泄露内部表示的策略

为了建立并保证不变性,应当有如下操作:

  1. 在初始化时使之为真
  2. 所有修改都使不变性得到保持
  3. 只通过creators and producers创建
  4. 通过mutators and observers保持
  5. 没有表示泄露发生

你可能感兴趣的:(ADT的RI和AF)