What do you think?
I have read several times that so called magic numbers are from the dark side. But in this case you can see it in the picture that it is difficult to be confused by the digits. Let’s look at one of the lines:
I have a panel component which preferred size property should be… the horizontal parameter: 356 and the vertical parameter is 356 pixels.
Is it hard to understand? Does it take a long time to see what are the magic numbers for?
If you have to use more than once the same parameter, then it is ok to use constants. But a preferred size of a widget is used only once usually.
As you can see above, the names of constants should be self explaining. In usual it means long names (a lot of characters). Too long and too much text is less readable IMHO.
Let’s see an example from the web:
Answer says that using constant in this case makes the code more readable. I think it is not. Password length must be greater than seven is absolutely readable for me. Much more than seeing a constant’s name. But to maintain the code is easier when you use constants.
And what about this solution?
We have discussed this in an other forum in Hungary with Gábor and he wrote a quite good essay about the magic numbers and usage of constants, properties, parameters. He said the followings:
– When constants (let’s say parameters) are for the whole project, then they can go into a so called constants’ file. This is a pure java class which has constants and nothing else inside. It is easy to maintain our constants, but they are a little bit far from the place of their usage.
– Second case is when the parameters are for a little part of the code and/or they are for configuration which can be modified by the customer. In this case it is good to use property files
– And finally, place your constants as close to the place where they are used as you can.
Thank you Gábor!