1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.google.android.setupcompat.internal;
17 
18 import android.os.Looper;
19 
20 /**
21  * Static convenience methods that help a method or constructor check whether it was invoked
22  * correctly (that is, whether its <i>preconditions</i> were met).
23  *
24  * <p>If the precondition is not met, the {@code Preconditions} method throws an unchecked exception
25  * of a specified type, which helps the method in which the exception was thrown communicate that
26  * its caller has made a mistake.
27  */
28 public final class Preconditions {
29 
30   /** Ensures the truth of an expression involving one or more parameters to the calling method. */
checkArgument(boolean expression, String errorMessage)31   public static void checkArgument(boolean expression, String errorMessage) {
32     if (!expression) {
33       throw new IllegalArgumentException(errorMessage);
34     }
35   }
36 
37   /**
38    * Ensures the truth of an expression involving the state of the calling instance, but not
39    * involving any parameters to the calling method.
40    */
checkState(boolean expression, String errorMessage)41   public static void checkState(boolean expression, String errorMessage) {
42     if (!expression) {
43       throw new IllegalStateException(errorMessage);
44     }
45   }
46 
47   /** Ensures that an object reference passed as a parameter to the calling method is not null. */
checkNotNull(T reference, String errorMessage)48   public static <T> T checkNotNull(T reference, String errorMessage) {
49     if (reference == null) {
50       throw new NullPointerException(errorMessage);
51     }
52     return reference;
53   }
54 
55   /**
56    * Ensures that this method is called from the main thread, otherwise an exception will be thrown.
57    */
ensureOnMainThread(String whichMethod)58   public static void ensureOnMainThread(String whichMethod) {
59     if (Looper.myLooper() == Looper.getMainLooper()) {
60       return;
61     }
62     throw new IllegalStateException(whichMethod + " must be called from the UI thread.");
63   }
64 }
65