I know that Null Object pattern lets us get rid of repetitive check of null. In my project there is a lot of code that looks like this (of course it's significantly simplified, just to show the idea):
public User getUserById(Long id) {
... // create db query
return (User) query.getSingleResult();
}
and then we have
public String isUserAdmin(Long id){
User user = getUserById(id);
if(user != null) {
if(user.isAdmin()) {
return "success";
} else {
return "forbidden";
}
}
}
And now instead of checking if user is not null we can check inside getUserById method if result from DB is null and if so we can return NullUser object.
But my question is - what for do we need Null Object pattern (in this case NullUser object)? Can't we just return new User() instead?
Aucun commentaire:
Enregistrer un commentaire