samedi 29 février 2020

Instantiate a class variable from a method - Java

I know there is not a good idea to instantiate a class variable from a method but unfortunately, I face a situation where I do not have any other solution. I have created some custom validators and I have an object (rawField) that is populated with some information from GUI. To populate that instance variable I use the method validate from javax.faces.Validator.

So I get the information for each field from GUI through this event.

My question is: Is this a good design pattern? Has anybody a better idea about how should I instantiate this variable?

Parent class:

 public abstract class FormFieldValidator extends BaseValidator implements IFormFieldValidator, Validator {

            protected RawField rawField;

            @Override
            public abstract RawField doInitialize(Object inputObject);

            @Override
            public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

            rawField = doInitialize(value);

            if (rawField == null) {

                throw new IllegalArgumentException("The field cannot be empty");

            }

            doBasicValidation();
            }
    }

Child class

@FacesValidator(Constants.Validators.USERNAME_VALIDATOR)

public class UsernameValidator extends FormFieldValidator {

    @Override
    public RawField doInitialize(Object guiField) {

    ValidationConditions validationConditions = new ValidationConditions

        .Builder(Entities.ParamsSize.USERNAME_MIN_LENGTH, Entities.ParamsSize.USERNAME_MAX_LENGTH)

            .setRegex(Constants.Regex.USERNAME_REGEX).setNullable(false).setUnique(true).build();


    FieldDetails fieldDetails = new FieldDetails(guiField, "Username");

    RawField rawField = new RawField(fieldDetails, validationConditions);

    return rawField;
    }

}

Aucun commentaire:

Enregistrer un commentaire