1 /*
2 * Copyright 2009-2010 Steve Chaloner
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 be.objectify.led.util;
17
18 import java.util.Collection;
19
20 /**
21 * Utility methods for asserting contracts.
22 *
23 * @author Steve Chaloner
24 */
25 public class ContractUtils
26 {
27 private ContractUtils()
28 {
29 }
30
31 /**
32 * Checks if <i>object</i> is null. An IllegalArgumentException is thrown
33 * if it is null.
34 *
35 * @param object the object
36 * @param objectName the name to reference the object by for exception messages
37 */
38 public static void notNull(Object object,
39 String objectName)
40 {
41 if (objectName == null)
42 {
43 throw new IllegalArgumentException("objectName must not be null");
44 }
45 if (object == null)
46 {
47 throw new IllegalArgumentException(objectName + " must not be null");
48 }
49 }
50
51 /**
52 * Checks if <i>objects</i> is null, and if any of its contents are null. An
53 * IllegalArgumentException is thrown if either of these cases are true.
54 *
55 * @param objects the array of objects
56 * @param objectName the name to reference the array by for exception messages
57 */
58 public static void nonNull(Object[] objects,
59 String objectName)
60 {
61 notNull(objects,
62 objectName);
63
64 for (Object object : objects)
65 {
66 if (object == null)
67 {
68 throw new IllegalArgumentException("All items of " + objectName + " must be non-null");
69 }
70 }
71 }
72
73 /**
74 * Checks if <i>objects</i> is null, and if any of its contents are null. An
75 * IllegalArgumentException is thrown if either of these cases are true.
76 *
77 * @param objects the collection of objects
78 * @param objectName the name to reference the collection by for exception messages
79 */
80 public static void nonNull(Collection objects,
81 String objectName)
82 {
83 notNull(objects,
84 objectName);
85
86 for (Object object : objects)
87 {
88 if (object == null)
89 {
90 throw new IllegalArgumentException("All items of " + objectName + " must be non-null");
91 }
92 }
93 }
94 }