5

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

skayred
  • 10,603
  • 10
  • 52
  • 94
  • Is there any particular reason you do not want to check if it is a null before you actually call `isOutdated()` or similar "state checkers" ? – DejanLekic Nov 10 '11 at 10:06
  • Even if User is null, I must have access to outdated field, so I must store somewhere that info – skayred Nov 10 '11 at 10:10
  • In that case, I would simply add a state, say "readyToUse" which is set to false by default, and use the object like it is "not a null" only when readyToUse is true. – DejanLekic Nov 10 '11 at 10:15
  • 2
    What does it mean for your application when your user object is null? For example, does it mean "no user", or "some unknown user" or "a new user"? Usually the answer for this question will help you designing a Null Object. – Philipp Wendler Nov 10 '11 at 10:23

2 Answers2

2

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?

Kent
  • 189,393
  • 32
  • 233
  • 301
  • I'm afraid to use static methods because it seems to be a bad practice in OOP – skayred Nov 10 '11 at 10:20
  • i feel static methods for a util class are ok. If you really hate static, you can of course remove the 'static' and create a proper constructor. point is, if this solution in my answer works in your situation? – Kent Nov 10 '11 at 10:23
2

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.