A junior developer asked me this week when she should use Integer objects over int primitives. Many classes (eg, java.util.Calendar) use ints to represent quantities - eg, month, day of the month etc and this makes perfect sense since there is no point in time with a null month. But what about the other way around, she asked? When would you have to use Integers?
I was a bit stumped at first. Although it's intuitively obvious to me that there are such occasions, I couldn't think of an example off the top of my head. So, I just waffled about null having a semantic meaning in certain circumstances.
Later, I thought of this one: imagine an application for lawyers in which a class captures a defendant's answer. If it were modelled using an int, you might see something like this in the system:
Application: How many days has it been since you last beat your wife?
Defendant: I've never beaten my wife.
Application: OK, I'll just put you down as "0 days since you last beat your wife".
Null would have been a reasonable value here and hence I'd argue an Integer should be used. An int of -1 (ie, "-1 day(s) ago") favoured in some APIs could possibly be interpreted as "tomorrow".
Damn my slow, coffee-addled brain.
Saturday, April 17, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment