vendredi 3 mai 2019

Validating model classes in settter methods

Here, I would like to ask your ideas about designing best validation approach for below requirements: we have a User model and depending on it is status we can update some specific fields.

1- if the status of user is ACTIVE then all fields (name, surname, password ....) can be updated 2- if the status of user is INACTIVE only password can be updated 3- if the status of user is BLOCKED then sanme and surname can be updated 4- if the status of user is DELETED then update operation is not allowed for any field.

As you can see, Changeability of model class depends on it's status field. Obviously, it can be done simply by adding UserValidation class and before setting values in setter methods i can call my UserValidator to check if the operation is allowed or not. However, it has a drawback(?) what will happen if there will be new field (let's say martialStatus) and dev who would be adding that field did forget calling UserValidation class before setting martialStatus. Other ways of solving this problem that I can think of: 1- Using custom annotations by extending CustomValidator. However, it won't work as annotation can not know the previous values of object. I mean, isValid Method of CustomValidator won't know if the name field has changed or not(it was john and now dev wants to change it to Jack)

2- Proxy pattern could be useful but not sure if it is good idea to use proxy for model objects

3- I saw on the internet that Decorator pattern can be used for this problem but i can not understand how. I think validating model class is beyond the responsibility of Decorator design

public class User {

private Integer id;
private String name;
private String surname;
private String password;
private Status status;
// setters

}

public enum Status { ACTIVE, DELETED, INACTIVE, BLOCKED }

I Would like to hear your advises. Thanks

Aucun commentaire:

Enregistrer un commentaire