I have created a method in Java that allows me to "check" several JTextFields
, the idea is that a user enters his personal data (name, surname, email, password etc)
and that this method allows me to check if JTextfields
they are not NULL
, the format of the Email is correct and finally that the password is not NULL
.
public boolean checkRegistrationData(ArrayList<JTextField> jTxts, JPasswordField pass, JTextField theEmail) {
if (isJtextNotNull(jTxts) && isJPasswordNotNull(pass) && isValidEmailAddress(theEmail)) {
JOptionPane.showMessageDialog(null, "A confirmation Code has been sent to your Email adress");
return true;
} else if (isJtextNotNull(jTxts) && !isJPasswordNotNull(pass) && isValidEmailAddress(theEmail)) {
JOptionPane.showMessageDialog(null, "The password field is empty");
return false;
} else if (isJtextNotNull(jTxts) && isJPasswordNotNull(pass) && !isValidEmailAddress(theEmail)) {
JOptionPane.showMessageDialog(null, "The email address is not valid");
return false;
}
else {
JOptionPane.showMessageDialog(null, "Some data is empty");
return false;
}
}
it ArrayList<JTextField> jTxts
is where most of the JTextFields with the user data are "stored".
Is there any way to improve this method ? would it be better to use switch?
To avoid showing a message for each type of error, which could be cumbersome for the user, you can group all the errors with the help of a list. That is:
✍ Code
✍ Exit
In this way, you show all the errors that exist in the data entered and the user has the opportunity to correct them all at once.
A common pattern ( Guard clause / Early exit ) is to check at the beginning of the method that the arguments are valid, exiting the method if they are not. In this way, the true objective of the method is separated from the previous verifications. With that pattern, the method would look like this:
switch
It would be useful to evaluate the different results of the same expression. A switch is always more efficient than a concatenation of if, elseif...else. But in your case you evaluate 4 different expressions:I don't see much point in using switch in this case unless you use an extra variable, for example form_state , and its value corresponds to each of the possible states of the form.