Re:LSP を破っている CollectionsFramework
via http://d.hatena.ne.jp/wildcats/20050117#p3
超遅レス.01/17 の日記を今頃読ませて頂きました.(^^;
public static List unmodifiableList(List list) (略)直接か、その反復子を使うかに関係なく、返されたリストを変更しようとすると UnsupportedOperationException がスローされます。これって、LSP に反している。
そうなのかなぁ? どこが反してるんだろ?
この話の流れだと例外がポイントなんですよねぇ.それが LSP に反しているということは,基本型ではスローされるはずのない例外を派生型がスローしている,という事でしょうか?
でもでも,自分が知っている限りそんなことはない気のせいが.
この場合でいうと,基本型は List
,派生型は Collections#unmodifiableList(List)
が返す実際の型ですよね.
あまり気にすることはありませんが,実は List
の JavaDoc ってこんな感じになっています (これは add()
メソッド).
/** * Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * * @throws UnsupportedOperationException if the <tt>add</tt> method is not * supported by this list. * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws NullPointerException if the specified element is null and * this list does not support null elements. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > size()). */ void add(int index, Object element);
@throws
で UnsupportedOperationException
が記述されていることに注目.この例外は,Collections#unmodifiableList(List)
の返す List
の派生型に限らず,List
インタフェースとしてスローされる可能性があるという仕様なのです.
List
型の参照が ArrayList
を参照していることを意識している場合などは,この例外がスローされることを想定しないと思いますが,その意識こそが LSP に反してるとはいえるかも.
ともあれ (JW),コレクションの「変更不可能なビュー」が UnsupportedOperationException
をスローすることに関しては LSP 違反ではないと思います.この動きは基本型である List
の仕様に準拠しています.