简体   繁体   English

从方法实例化类变量 - Java

[英]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.我创建了一些自定义验证器,并且我有一个对象( rawField ),其中填充了来自 GUI 的一些信息。 To populate that instance variable I use the method validate from javax.faces.Validator .为了填充该实例变量,我使用了javax.faces.Validator validate 方法。

So I get the information for each field from GUI through this event.所以我通过这个事件从 GUI 获取每个字段的信息。

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

}

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.您的代码中不正确的是方法validate ,它执行的验证更多。 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.最好将它称为populateAndValidate或从正文中删除doInitialize并确保它由客户端代码调用。 Null-check of rawField field can be a part of validation process. rawField字段的空检查可以是验证过程的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM