Scalaだと例外はあまり使わず、EitherやValidationを使う派。
やはり、コンパイラの恩恵を受けることが出来る書き方が良い。
しかし、Clojureは動的型付けの言語。
コンパイラの恩恵は特にない。
なので、 どのような値が返ると扱いやすいかを考える。
Clojureは基本的に
- nil返す
- 例外投げる
Clojure標準のライブラリはnilを渡してもそれなりに動作するし、if-let,when-let,fnilなどの関数も用意されている。
しかし、nilだとどのようなエラーだったのか判別がつかない。
このような時に例外を使って、エラーの種類によって投げる例外を変えれば良いのだと思う。
Clojureの例外を投げるような関数は以下のように書ける。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn nthv [n vec] | |
(if (integer? n) | |
(if (and (pos? n) (< n (count vec))) | |
(get vec n) | |
(throw (IndexOutOfBoundsException.))) | |
(throw (IllegalArgumentException.)))) |
しかし、何時でもJava APIに自分が欲しいExceptionが定義されているわけではない。
このような時は、独自の例外を作るだろう。
駄菓子菓子!
Clojureでclassを定義するのはとても面倒。
nsやgen-classを見てもらえればわかると思う。
Throwableがinterfaceならば、deftypeやdefrecordが使えたのだけれど・・・
例外を定義する部分だけJavaで書いたほうが楽かも。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyException extends Exception {} |
結論
基本的にnilを返す。
独自の例外を定義したかったらJavaを使うと楽
0 件のコメント:
コメントを投稿