I am a beginner in Java and I am writing my first application in JavaFX.
I am accepting input from a user and then creating an object if the user's input is valid.
Here's a simplified code explaining what I am currently doing:
public class Visitor {
private String id;
public enum InvalidIdType {
EMPTY,
NOT_ALPHANUMERIC,
NOT_5_CHARACTERS;
}
public Visitor(String id) {
Objects.requireNonNull(id);
checkId(id);
this.id = id;
}
private void checkId(String id) {
if (validateId(id).isPresent()) {
throw new IllegalArgumentException(validateId(id).get.toString());
}
}
public static Optional<InvalidIdType> validateId(String id) {
if (id.isEmpty()) return Optional.of(InvalidIdType.EMPTY);
if (id.length != 5) return Optional.of(InvalidIdType.NOT_5_CHARACTERS);
if (...) return Optional.of(InvalidIdType.NOT_ALPHANUMERIC);
return Optional.empty();
}
}
So that in the code elsewhere handling the user input, I can do something like:
public class Main {
public static void main(String[] args) {
...
if (Visitor.validateId(userinput).isPresent()) {
System.out.println(Visitor.validateId(userinput).get().toString())
// Tells user what is wrong. I switch-case through the different enum values.
}
}
}
So that I don't have to validate the code twice in Main.java and in Visitor.java.
But I feel like this creates unnecessarily long code in Visitor.java and is not a common way to validate inputs in Java.
What would be the best practice to validate a field in both the object's constructor and other code which handles the user input, but not duplicate my validation code.