-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidationUtils.java
More file actions
69 lines (64 loc) · 2.42 KB
/
ValidationUtils.java
File metadata and controls
69 lines (64 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* ValidationUtils - Utility class for common validation checks
* ToDo: Add more methods for collections, maps, regex, etc.
*/
public final class ValidationUtils {
private ValidationUtils() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Check that an object reference isn't null; throw error if it is
* @param obj the object to check
* @param message the exception message if null
* @throws NullPointerException if the object is null
*/
public static <T> T requireNonNull(T obj, String message) {
if (obj == null) {
throw new NullPointerException(message);
}
return obj;
}
/**
* Make sure a number is within a specified range (double and int overloads)
* @param value the value to check
* @param min the minimum allowed value
* @param max the maximum allowed value
* @param fieldName the name of the variable (for error message)
* @throws IllegalArgumentException if the value is out of range
*/
public static void checkRange(double value, double min, double max, String fieldName) {
if (value < min || value > max) {
throw new IllegalArgumentException(
String.format("%s must be between %.2f and %.2f. Found: %.2f", fieldName, min, max, value)
);
}
}
public static void checkRange(int value, int min, int max, String fieldName) {
if (value < min || value > max) {
throw new IllegalArgumentException(
String.format("%s must be between %d and %d. Found: %d", fieldName, min, max, value)
);
}
}
/**
* Check if a condition is true; error iffalse.
* @param condition the boolean condition to check
* @param message the exception message if false
* @throws IllegalArgumentException if the condition is false
*/
public static void checkArgument(boolean condition, String message) {
if (!condition) {
throw new IllegalArgumentException(message);
}
}
/**
* Ensures a string is not null or empty.
* @param str the string to check
* @throws IllegalArgumentException if string is null or empty
*/
public static void rejectEmpty(String str, String fieldName) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException(fieldName + " cannot be null or empty");
}
}
}