我正在为kadmin命令实现一个库。除其他外,采用以下方法:
def changePassword(principal: String, newPassword: String): Either[ErrorCase, Boolean]
def deletePrincipal(principal: String): Either[ErrorCase, Boolean]
这两个操作可能返回错误,因此它们的返回类型为
Either[ErrorCase, Boolean]
。其中ErrorCase
定义为:trait ErrorCase
case object InsufficientPermissions extends ErrorCase
case object PrincipalDoesNotExist extends ErrorCase
case object IncorrectPassword extends ErrorCase
case object PasswordTooShort extends ErrorCase
case object PasswordWithoutEnoughCharacterClasses extends ErrorCase
case object PasswordIsBeingReused extends ErrorCase
case object PasswordExpired extends ErrorCase
case object UnknownError extends ErrorCase
我的问题是:如果我将特征ErrorCase定义为密封特征,那么当他/她调用API方法之一时,我将给API用户增加检查所有可能的
ErrorCase
的负担。这对于changePassword
方法是有意义的,因为所有这些错误情况都可能在此操作中发生。但是对于deletePrincipal
方法,这是没有意义的,因为与密码相关的所有错误情况将永远不会发生。换句话说,API方法共享错误情况,但是每种方法不一定使用每种错误情况。如何使特征密封,但以某种方式指定在每种方法中仅使用某些ErrorCases。
最佳答案
Any problem in computer science can be solved with another level of indirection, except the problem of too many levels of indirection.
sealed trait ErrorCase
sealed trait PasswordErrors extends ErrorCase
sealed trait OtherErrors extends ErrorCase
case object IncorrectPassword extends PasswordErrors
case object PasswordTooShort extends PasswordErrors
case object PasswordWithoutEnoughCharacterClasses extends PasswordErrors
case object PasswordIsBeingReused extends PasswordErrors
case object PasswordExpired extends PasswordErrors
case object InsufficientPermissions extends OtherErrors
case object PrincipalDoesNotExist extends OtherErrors
case object UnknownError extends OtherErrors
不确定处理
UnknownError
(OtherErrors
的子类,直接ErrorCase
的子类或其他方法)的最佳方法是什么,但这取决于您自己决定。
关于scala - 共享错误和密封特征的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33943229/