default values for primitives

I’ve just spent a few hours trying to figure out a problem in our application. It turns out that the page I was looking at has a condition at the top where if the object ID in question is 0, it assumes that it hasn’t been set. This was a problem because I was trying to look at an object which actually had an ID of 0! (Because I have a clean rebuilt database). I worked around the problem by making the value default to -1 if it hadn’t been set, and checking for that instead.

Of course the underlying problem is the difference between primitives and Objects in Java. If I have an int, say, it is just a number – I cannot say ‘this hasn’t been set yet’. So we resort to ‘special’ numbers, and then you can run into problems like this, where your ‘special’ number turns out to be a valid value after all.

Ruby is smarter – there are no ‘primitives’: everything is an object, and nil is false in a conditional context, so it is easy to check whether something has been set.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*