10. 2011/3/31 オブジェクト指向プログラミング入門 8 10
スタッククラスの例
class STACK1[G]
feature -- アクセスする
count: INTEGER
item: G is
require
not empty
do … end
feature -- 状態を報告する
empty: BOOLEN is
do … end
full: BOOLEAN is
do … end
feature – 要素を変更する
put (x: G) is
require not full
do …
ensure
not empty
item = x
count = old count + 1
end
remove is
require not empty do …
ensure
not full
count = old count – 1
end
end
12. 2011/3/31 オブジェクト指向プログラミング入門 8 12
検査が少ないほど保証は大きい
x が負の場合を考慮せずに平方根のアルゴリズムを書くことがで
きる
sqrt(x: REAL): REAL is
-- x の平方根
require x >= 0
do … end
ルーチン do 句を以下のように書いてはいけない
if x < 0 then
“ ”どうにかしてエラーを処理する
else
“ ”正常な平方根の計算を行なう
end
どんな事情があっても,ルーチンの事前条件にあたるテストを,ルーチンの
本体で行なってはならない.
非冗長性の原則
シンプルさ
が失われる
16. 2011/3/31 オブジェクト指向プログラミング入門 8 16
例:完全なスタッククラス(1)
class STACK2[G] creation
make
feature -- 初期化する
make(n: INTEGER) is
-- 最大 n 個の要素分,スタックを割り付ける
require
positive_capacity: n>= 0
do
capacity := n
create representation.make(1, capacity)
ensure
capacity_set: capacity = n
array_allocated: representation /= Void
stack_empty: empty
end
17. 2011/3/31 オブジェクト指向プログラミング入門 8 17
例:完全なスタッククラス(2)
feature -- アクセスする
capacity: INTEGER
-- スタックの最大要素
count: INTEGER
-- スタックの中の要素の数
item: G is
-- 最上位の要素
require
not_empty: not empty -- すなわち, count > 0
do
Result := representation @ count
end
18. 2011/3/31 オブジェクト指向プログラミング入門 8 18
例:完全なスタッククラス(3)
feature -- 状態を報告する
empty: BOOLEAN is
-- スタックは空か?
do
Result := (count = 0)
ensure
empty_definition: Result = (count = 0)
end
full: BOOLEAN is
-- スタックはいっぱいか?
do
Result := (count = capacity)
ensure
full_definition: Result = (count = capacity)
end
19. 2011/3/31 オブジェクト指向プログラミング入門 8 19
例:完全なスタッククラス(4)
feature -- 要素を変更する
put(x: G) is
-- 最上部に x を加える
require
not_full: not full -- すなわち, count < capacity
do
count := count + 1
representation.put(count, x)
ensure
not_empty: not empty
added_to_top: item = x
one_more_item: count = old count + 1
in_top_array_entry: representation @ count = x
end
20. 2011/3/31 オブジェクト指向プログラミング入門 8 20
例:完全なスタッククラス(5)
remove is
-- 最上部の要素を削除する
require
not_empty: not empty -- すなわち, count > 0
do
count := count – 1
ensure
not_full: not full
one_fewer: count = old count – 1
end
feature {NONE} -- 実装する
representation: ARRAY[G]
-- 配列はスタック要素を保持するのに使われる
invariant
… …後でこの部分を埋める
end
25. 2011/3/31 オブジェクト指向プログラミング入門 8 25
事前条件と公開状態
以下のようなクラスは不正(コンパイルエラーとなる)
class SNEAKY feature
tricky is
require accredited
do … end
feature {NONE}
acredited: BOOLEAN is do … end
end
顧客は tricky を呼び出す前に,それが正しいかどうか調べられな
い
事後条件にはこのような規則はない
ルーチンの事前条件にあるすべての特性は,ルーチンを利用できるすべての
顧客に利用可能でなければならない
事前条件の利用可能性の規則