在 android 中验证函数先决条件

Validate function preconditions in android

通常在编写 public 方法时我会做一些错误检查,例如

public SomeResult processSomething (int i, List<String> items) {
   if( i < 0 ) {
      throw new IllegalArgumentException();
   }
  if(items == null) {
     throw new NullPointerException();
  }
etc
}

在android编程中,对此的标准方法是什么?我注意到,当一个片段崩溃时,模拟器会转到前一个片段,因此从向用户显示的行为来看,我猜这是可以的。但是处理 exceptional/error 条件的最佳方法是什么?

此处的最佳实践与 Java 世界其他地方使用的最佳实践非常相似:

1. 方法的第一行通常用于检查方法参数的有效性。如果出现错误,该方法应尽快失败。

验证参数时,如果测试失败,将抛出 Exception。抛出的通常是这些 未检查 异常之一:

  • IllegalArgumentException
  • NullPointerException
  • IllegalStateException

这些都来自RuntimeException

2. If every object parameter of every method in a class 需要是非空的,以避免抛出 NullPointerException,然后在一般 class javadoc 中声明一次是可以接受的,而不是为每个方法重复它。

参考文献:

Preconditions, Postconditions, and Class Invariants.

编辑:

回答关于 "view specific for errors" 的问题:虽然确实可以这样做,但想法是 Exception 表示代码中存在编程错误。因此,应该允许应用程序崩溃,以便用户可以报告错误,开发人员从而从应用程序的 Play 商店帐户中获取错误日志。这样他就可以纠正这些错误的来源。该过程应该一直持续到假设应用程序完全没有错误为止。

现在我们可以使用 Kotlin Preconditions.kt:

data class User(val active: Boolean, val email: String?)

class UserHelper (private val user: User) {

    fun mergeUsers(otherUser: User) {
        // To verify enclosing class state we use "check methods".
        // If check fails IllegalStateException will be thrown
        checkNotNull(user.email) { "user email is null" }
        check(user.active) { "user is not active" }

        // To verify argument we use "require methods".
        // If check fails IllegalArgumentException will be thrown
        requireNotNull(otherUser.email) { "otherUser email is null" }
        require(otherUser.active) { "otherUser is not active" }

        // All the preconditions has been meet, so we can merge users
        // ...
    }
}