mardi 28 février 2017

Which approach is better for validating inputs?

I want to check input values for methods and I dont want to write code like this:

void name(String name) {
    if(name != null) {
        //some action
    } else {
        //some another action
    }
}

So I can use decorator pattern or annotations.

Decorator example:

public interface User {
    void name(String name);
} 

public final class dbUser {
    //ctor...

    void name(String name) {
        //jdbc call for update user name
    }

}

public final class CheckedNullUser {
    private final CheckedNullUser user;

    public CheckedNullUser(User user) {
        this.user = user;
    }

    void name(String name) {
        String inputName = "Some default value";

        if(name != null) {
            inputName = name;
        }

        return user.name(inputName);
    }

}

Annotation example:

public interface User {
    void name(@NotNull String name);
} 

public final class dbUser {
    //ctor...

    void name(@NotNull String name) {
        //jdbc call for update user name
    }

}

Which approach is better? Exist better approaches?

Aucun commentaire:

Enregistrer un commentaire