@ledsun blog

無味の味は佳境に入らざればすなわち知れず

デメテルの法則を詳しく

デメテルの法則 - @ledsun blogでは原典に当たりませんでした。 原典に当たります。

デメテルの法則は次の文章で提唱されました。 https://www2.ccs.neu.edu/research/demeter/papers/law-of-demeter/oopsla88-law-of-demeter.pdf

定義

次のように定義されています。

For all classes C, and for all methods M attached to C, all objects to which M sends a message must be instances of classes associated with the following classes:

  1. The argument classes of M (including C).
  2. The instance variable classes of C.

(Objects created by M, or by functions or methods which M calls, and objects in global variables are considered as arguments of M.)

これに従うと、クラスCのメソッドMが参照して良いのは次のものです

  • メソッドMの引数
  • クラスCのインスタンス変数
  • メソッドM内で生成したオブジェクト
  • メソッドM内で関数またはメソッドを呼び出して取得したオブジェクト
  • グローバル変数

プログラミング言語に合わせた読み替えは必要だと思います。

  1. メソッドMのスコープで最初から見えているオブジェクト
  2. 1のオブジェクトから取得出来るオブジェクト

まで参照して良さそうです。 2からから先を見に行くと違反になります。

効能

この法則を守ると何が嬉しいのでしょうか?

Any method written to obey this Law will only know about the immediate structure of the class to which it is attached. The structure of the arguments and the sub-structure of C are hidden from M. Therefore, should a change to the structure of the class C be necessary we need only to look at those methods attached to C and its subclasses for possible conflicts.

この法則に従ったメソッドは、クラスの内部構造しか知りません。 参照するオブジェクトとサブクラスの内部構造を知りません。 クラスCを変更したくなったときは、CのメソッドとCのサブクラスと矛盾しないことだけを考えれば良くなります。

まあ、言われてみたら当たり前ですね。 Cの変更容易性に注目しているのは、僕の中では意外でした。

他にも興味深い記述があります。

The Law of Demeter effectively reduces the methods we can call inside a given. a method and therefore limits the coupling of methods with respect to the “uses” relation.

デメテルの法則は“uses”関係を制限します。

The Law is stated in terms of types

この法則は型の観点から述べられています。

やはり"use"関係を制限して型情報の依存関係を減らすための法則のようです。

Compile Time Checking of the Law

The Law of Demeter (the original version, not the object version) can be checked at compile-time for useful subsets of object-oriented languages.

コンパイル時にチェック可能とか書いてあります。 本当でしょうか? メソッドチェーンの存在を考えると、単なる呼び出し階層の深さではわかりません。 あるメソッド呼び出しによって型情報が増えたかどうかチェックするのでしょうか? 謎です。 僕は「デメテルの法則」をチェックするlinterを知りません。

参考