samedi 24 septembre 2022

Which design pattern reduces boilerplate when set method is what varies throughout the code

All this code happens when I press save button: Regex validation, JOptionPane Error Messages, and other behaviours like red spot around text field, I want to be cleaner:

/*
TextFieldValidator: Regex type, textFieldName, 
name of the field for error message, minimum size for 
validation, maximum size for validation.    
*/

public void actionPerformed(ActionEvent e) {
boolean lastModelIsValid=true;

///Id Card validation
TextFieldValidator idCardModel = new TextFieldValidator(
                    Regex.Numerical, idCardNumberTextField,
                    "ID Card Number", 9, 9);

         if (lastModelIsValid) {
            lastModelIsValid= idCardModel.isValidAndSendErrorMessage();
                            
            
                documents.setIDCardNumber(
                        Integer.getInteger(idCardModel.getTextFieldContent()));
            }


///EMail validation        
TextFieldValidator emailModel = new TextFieldValidator(
                    Regex.Alphanumerical, emailTextField,
                    "Email", 3, 20);

      if (lastModelIsValid) {
            lastModelIsValid= emailModel.isValidAndSendErrorMessage();                              
            
                documents.setEmailAddress(
                        emailModel.getTextFieldContent());
            }

 ///Twenty Fields more...

I thought about implementing something like that, but for me it is still too much code:

public void actionPerformed(ActionEvent e) {

boolean saveToDatabase=true;

///EMail validation   
if(new TextFieldValidator(Regex.Alphanumerical, emailTextField,
                    "Email", 3, 20).isValidAndSendErrorMessage()){
documents.setEmailAddress(Type.STRING, emailTextField.getText());
}
else
{
 saveToDatabase=false;
}  

///ID Card validation  
if(new TextFieldValidator(Regex.Numerical, idCardNumberTextField,
                    "ID Card", 9, 9).isValidAndSendErrorMessage()){
documents.setIdCardNumber(Type.INTEGER, idCardTextField.getText());
}
else
{
saveToDatabase=false;
}  
/// Twenty Fields more...

Aucun commentaire:

Enregistrer un commentaire