Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate function preconditions in android

Usually when writing a public method I do some error checking e.g.

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

In android programming what is the standard approach for this? I noticed that when a fragment crashes the emulator goes to the previous fragment so from behavior shown to the user I guess it is ok. But what is the best way to deal with exceptional/error conditions?

like image 992
Jim Avatar asked Mar 22 '15 11:03

Jim


2 Answers

The best practices here would be very similar to those used elsewhere in the Java world:

1. The first lines of a method are usually devoted to checking the validity of method arguments. The method should fail as quickly as possible in the event of an error.

When validating an argument, an Exception is thrown if the test fails. It's often one of these unchecked exceptions that are thrown:

  • IllegalArgumentException
  • NullPointerException
  • IllegalStateException

These are all derived from RuntimeException.

2. If every object parameter of every method in a class needs to be non-null in order to avoid throwing NullPointerException, then it's acceptable to state this once in the general class javadoc, instead of repeating it for each method.

References:

Preconditions, Postconditions, and Class Invariants.

EDIT:

To answer your question about "view specific for errors": while it is certainly possible to do that, the idea is that an Exception indicates the presence of programming errors in the code. Therefore, apps should be allowed to crash so that the user can report the error, and the developer thereby gets the error logs from the app's Play Store account. This way he can correct the sources of those errors. The process should continue till, hypothetically, the app is completely free of errors.

like image 102
Y.S Avatar answered Sep 30 '22 00:09

Y.S


Nowadays we can use 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
        // ...
    }
}
like image 44
Igor Avatar answered Sep 29 '22 22:09

Igor