0

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;
    }

}

1 Answer 1

1

It's not necessarily an antipattern to populate an object with data on method invocation. What's not right in your code is that the method validate, that does more that validation. First it initializes the variable, then it validates the object. It would be better to call it something like populateAndValidate or remove the doInitialize from the body and make sure it's invoked by the client code. Null-check of rawField field can be a part of validation process.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. What do you mean when you say that doInitialize must be invoked by the "client code"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.