Validation Strategies
Comprehensive Numeric Validation Approach
graph TD
A[Validation Strategies] --> B[Range Checking]
A --> C[Type Validation]
A --> D[Special Value Handling]
A --> E[Precision Verification]
Validation Techniques and Patterns
1. Range Validation
public class NumericValidation {
public static boolean validateRange(int value, int min, int max) {
return value >= min && value <= max;
}
public static boolean validateDoubleRange(double value, double min, double max) {
return value >= min && value <= max && !Double.isNaN(value);
}
public static void main(String[] args) {
// Integer range validation
System.out.println("Integer in range: " +
validateRange(50, 0, 100));
// Double range validation
System.out.println("Double in range: " +
validateDoubleRange(75.5, 0.0, 100.0));
}
}
2. Type-Safe Validation Strategies
Validation Type |
Description |
Recommended Method |
Null Check |
Prevent null numeric values |
Objects.requireNonNull() |
Type Conversion |
Safe numeric conversion |
Number.parseXXX() methods |
Boundary Check |
Ensure values within limits |
Math.min/max() |
3. Advanced Validation Framework
public class NumericValidator {
public static class ValidationResult {
public boolean isValid;
public String errorMessage;
public ValidationResult(boolean isValid, String errorMessage) {
this.isValid = isValid;
this.errorMessage = errorMessage;
}
}
public static ValidationResult validateNumber(Number number) {
// Comprehensive validation strategy
if (number == null) {
return new ValidationResult(false, "Null value not allowed");
}
if (number instanceof Double) {
Double doubleValue = (Double) number;
if (Double.isNaN(doubleValue)) {
return new ValidationResult(false, "NaN is not a valid number");
}
if (Double.isInfinite(doubleValue)) {
return new ValidationResult(false, "Infinite values not permitted");
}
}
return new ValidationResult(true, "Valid number");
}
public static void main(String[] args) {
ValidationResult result1 = validateNumber(42.5);
ValidationResult result2 = validateNumber(Double.NaN);
System.out.println("Result 1: " + result1.isValid);
System.out.println("Result 2: " + result2.isValid);
}
}
Precision and Floating-Point Considerations
Floating-Point Comparison Strategy
public class PrecisionValidation {
private static final double EPSILON = 0.00001;
public static boolean approximatelyEqual(double a, double b) {
return Math.abs(a - b) < EPSILON;
}
public static void main(String[] args) {
double value1 = 0.1 + 0.2;
double value2 = 0.3;
System.out.println("Precise Comparison: " +
approximatelyEqual(value1, value2));
}
}
LabEx Validation Best Practices
- Implement multiple validation layers
- Use type-safe validation methods
- Handle special numeric states explicitly
- Create reusable validation components
Key Validation Principles
- Validate input before processing
- Use built-in Java validation methods
- Create custom validation frameworks when needed
- Consider performance and readability