mardi 22 mars 2016

Design patterns - How to enforce object attributes only in some situations (Builder pattern, Dependency Injection)

I am in a very particular situation with one of the classes I'm coding. I have this class called User that looks like this:

public class User {
    private long id; // + getters and setters
    private boolean isDeletable; // + getters and setters
    private String name; // + getters and setters
    private String password; // + getters and setters
    private String email; // + getters and setters
    private String authenticationRealm; // + getters and setters
    private String displayName; // + getters and setters
    private Date deletedDate; // + getters and setters
}

Within my code there are several situations where I just need an empty object of the type User and therefore just build it using the default constructor: new User().

However, I have another class called CreateUserRequest which models a REST request to create the user in a server. The minimum payload must contain the name, password, email, and authenticationRealm attributes sent in JSON format.

Right now I am handling this by checking for these parameters in the constructor of the request:

public CreateUserRequest(User user) {
    if(user.getName() == null || user.getPassword() == null || user.getEmail() == null || user.getAuthenticationRealm() == null)
        throw new RuntimeException("Not enough attributes in User object. Minimum: name, password, e-mail and authentication realm.");
}

This is working OK but something is itchy... I would like to enforce this in a safer way, so that the code would enforce the attributes to be populated with no possibility of an exception being thrown.

I feel like there must be a better way to do this with a design pattern. I thought of creating a UserRequestBuilder class, but that would also possibly imply throwing an exception in the build() method (otherwise, is there a way I can guarantee that the attributes are populated before build()?). Dependency injection also sounds like a possibility, but I'm not sure how I would put it in place in this particular example...

Any thoughts?

Aucun commentaire:

Enregistrer un commentaire