jeudi 13 juin 2019

Is it correct application of the SRP(single responsibility principle)?

I have a java class:

class User {
 private String name;
 private String address;
 private int age;
 private BigDecimal salary;
 // other fields
 //getters setters
}

I can receive a map of new values in these fields and update it. It looks like this: ChangeItem changeItem where changeItem.key is field's name and changeItem.value is the field's value

I create strategies for updating each field. For example common interface:

public interface UpdateStrategy<T> {
    T updateField(T t, ChangeItem changeItem) throws ValidationExceptions;
}

And some implementation:

public class UpdateNameStrategy implements UpdateStrategy<User> {

    private static final Pattern USER_NAME = Pattern.compile(...);

    @Override
    public User updateField(User user, ChangeItem changeItem) throws ValidationExceptions {

        String fieldValue = changeItem.value;

        if (!validate(fieldValue))
            throw new ValidationExceptions(changeItem);

        user.setName(fieldValue);

        return user;
    }

    private boolean validate(String value){
        return USER_NAME.matcher(value).matches();
     }
}

In the real project I have 40 fields and 40 strategies for each field(with different validation and logic).

I think this class violates the SRP(single responsibility principle). And I move validation logic to separately class. I change the validation method to:

public class UpdateNameStrategy implements UpdateStrategy<User> {

    @Override
    public User updateField(User user, ChangeItem changeItem) throws ValidationExceptions {

        String fieldValue = changeItem.value;

        ValidateFieldStrategy fieldValidator = new UserNameValidate(fieldValue);

        if (!fieldValidator.validate())
            throw new ValidationExceptions(changeItem);

        return user;
    }
}

and

public class UserNameValidate implements ValidateFieldStrategy {

    private static final Pattern USER_NAME = Pattern.compile(...);

    private String value;

    public PaymentAmountValidate(String value) {
        this.value = value;
    }

    @Override
    public boolean validate() {
        return USER_NAME.matcher(value).matches();
    }
}

And now I have 40 strategies for update fields and 40 validators. Is it the correct way? Or maybe I can change this code more clear?

Aucun commentaire:

Enregistrer un commentaire