import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Consumer;
class TimeValidator {
/**
* Wraps a function that validates a time value, handling potential errors with limited memory.
*
* @param validator A function that takes a LocalDateTime and returns true if valid, false otherwise.
* @param errorMessage The error message to be associated with validation failures.
* @return A validation wrapper that can be used to execute the validation function.
*/
public static ValidationWrapper<LocalDateTime> wrapValidation(Consumer<LocalDateTime> validator, String errorMessage) {
return new ValidationWrapper<>(validator, errorMessage);
}
/**
* Represents a wrapped validation result, including the validation function and error message.
*/
static class ValidationWrapper<T> {
private final Consumer<T> validator;
private final String errorMessage;
ValidationWrapper(Consumer<T> validator, String errorMessage) {
this.validator = validator;
this.errorMessage = errorMessage;
}
/**
* Executes the validation function and handles any errors.
*
* @param time The time value to be validated.
* @throws IllegalArgumentException if the validation function fails.
*/
public void validate(LocalDateTime time) {
try {
validator.accept(time);
} catch (Exception e) {
throw new IllegalArgumentException(errorMessage + ": " + e.getMessage(), e); // Re-throw with context
}
}
}
public static void main(String[] args) {
// Example usage
ValidationWrapper<LocalDateTime> validator = TimeValidator.wrapValidation(time -> {
if (time.isBefore(LocalDateTime.now())) {
throw new IllegalArgumentException("Time cannot be in the past.");
}
// Add other validation rules here
}, "Invalid time value");
try {
validator.validate(LocalDateTime.now().plusDays(1)); //Valid
System.out.println("Validation successful");
validator.validate(LocalDateTime.now().minusDays(1)); // Invalid - should throw exception
} catch (IllegalArgumentException e) {
System.err.println("Validation failed: " + e.getMessage());
}
}
}
Add your comment