いいえ、リクエストを激しく失敗させるのはよくありません:
def user(userId: Int) : Option[User] // is OK
def user(userId: Int) : Either[String,User] // is OK
def user(usedId: Int) : User // is not OK
または、Integer をカプセル化する型 (概念) を作成して、それが有効な UserId (出生時) であることを確認することもできます。
sealed case class UserId(u:Int) //extends AnyVal // If it's scala 2.10.0
object UserId {
def get(i:Int) : Option[UserId] = //some validation
} /// ....
def user(userId:UserId) : User //is OK // well it depends on the semantic of user destruction.
def を作成するときは、関数のドメイン (this と引数) とコドメイン (結果) の間に適切な関係があることを確認する必要があります。
とにかく、ためらわずに入力 (概念を作成) してください。それは、コードについて推論するのに役立ちます。
なぜdef user(userId: Int) :User
OKではないのですか?
Integer
の要素と の要素の間の関係がUser
存在しないためです。UserId がすべて正の整数であるのに、 を要求するとどうなりuser(-10)
ますか? (それは起こりませんよね?) この呼び出しは例外を発生させるべきですか? または null を返しますか?
null を返す必要があると思われる場合は、Option を返します。これにより、欠落している可能性のある対応がカプセル化されます。
例外を発生させる必要があると思われる場合は、次を返します。
- a
Validation[SomethingRepresentingAnError, User]
(スカラス),
- an
Either[SomethingRepresentingAnError, User]
(scala 2.7、2.8、2.9)
- または
Try[User]
(scala 2.10)
豊富な戻り値の型があると、API を正しく使用するのに役立ちます。
ところで、Scala はチェック例外を使用しないため、代替結果として例外を使用することはできません。例外は、真に例外的な動作のために保持する必要があります (ランタイム例外として)。
も参照してください。
- http://www.scala-lang.org/api/current/index.html#scala.util.control.Exception$