Something I like in Ruby is symbols.
Sometimes the values of our constants in PHP don’t matter because they are only ever used in comparisons and array keys. For example, the app might have options like these
const FORMAT_CSV = 'csv'; const FORMAT_EXCEL = 'excel'; const FORMAT_SQLITE = 'sqlite';
The values could have been
'z' and the app would work the same.
Now imagine that the app allows the user to select from a number of duration intervals and one is declared as
const INTERVAL_1_WEEK = '1week';
A coder might by mistake use it, e.g. in
DateTime::modify(). It would be a programming error to do that but you can imagine how it might happen. And it could lead to a nasty bug that’s hard to understand. In our team we had the habit of assigning meaningful string values to such constants and we ran into a nasty bug of exactly this kind.
Once we figured it out I saw that the programming error would have been avoided or detected early if we had used something like a Ruby symbol. PHP doesn’t have them so I wondered if we might approximate them with opaque values, e.g.
const FORMAT_CSV = 'rtPL7NrvWN'; const FORMAT_EXCEL = 'u672AdVSkW'; const FORMAT_SQLITE = 'bw6bs6LbED';
The chance of these values meaning something in any context is remote. It seems to me this forces us to write more robust, less-coupled code.
What do you think of the idea? Do any of you do that?