views:

66

answers:

1

This question bugged me for years now and can't seem to find good solution still. I working in PHP and Java but it sounds like this maybe language-agnostic :)

Say we have a standard status reference table that holds status ids for some kind of entity. Further let's assume the table will have just 5 values, and will remain like this for a long time, maybe edited occasionally with addition of a new status. When you fetch a row and need to see what status it is you have 2 options(as I see it at least) - put it straight ID values(magic numbers that is) or use a named constant. Latter seem much cleaner, the question though is where those named constants should leave? In a model class? In a class that uses this particular constant? Somewhere else?

+1  A: 

It sounds like what you're wanting to do is an enumerated value.

This is a value that has a literal name mapped to a constant value, this would be something like

Statusone = 1
Statustwo = 2

Then anywhere in your program you could refrenece statusone which the compiler would see as 1.

I'm not sure if this exists in php but I'm pretty sure it does in java

EDIT In response to some comments

I would typically put enumerated values in some kind of global namespace, or if you only need them when you are using that class spefically you can put them at the class level.

msarchet
you can even use enumerations in some relational databases
Tim Mahy
@tim mahy, I thought you could do this but I wasn't sure
msarchet
Well, sure, enumerations you can use, or just plain constants. That's not the question :) The question is - where do you put them?
Alex N.
I think it is best (when possible) to use enumerations in your code and in your relational database.... you can write an unit test to verify that they are "in sync" to release some of the magic :)
Tim Mahy
the main advantage of the enum is that you get type safety checking at compile time.
JustJeff