Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which pattern would I prefer?

In our project we need to store some object (User, for example) and also User class must have a validation flag (methods like setOutdated and isOutdated)

From time to time, our User object may be null, but validation flag must be reachable in this case. It is possible to extract those methods from User class, but that field and methods must be inside that class because of semantics.

I've found some articles about Null Object pattern (like this), and I want to know - is it possible to create Null Object (as a pattern) which can store several states like null outdated, null not outdated, not null outdated and not null not outdated.

PS: If a introduce "Outdated" field in my class, it will be really hard to clear object instead of setting it to null

like image 434
skayred Avatar asked Oct 10 '22 12:10

skayred


2 Answers

You want to differentiate between (among others) "null outdated" and "null not outdated".
This means you suggest two different Null Objects, with different behaviour. This is a violation of the pattern that says that a Null Object should have one kind of behaviour, the default behaviour for an uninitialized object of it's kind.

I suggest you either use the solution @Kent provided, or that you make your user object something like "PresentUser" and "FormerUser" objects. The latter is technically the same solution that you propose yourself, but it is not a Null Object Pattern.

like image 155
S.L. Barth Avatar answered Oct 13 '22 12:10

S.L. Barth


My first idea is adding a UserUtil class (name could be something else).

and a method like

public static boolean isUserOutdated(User u){
return (u==null)? true :u.isOutdated();

}

 or return (u==null)? false :u.isOutdated(); depends on your businesslogic

does it work in your situation?

like image 32
Kent Avatar answered Oct 13 '22 12:10

Kent