According to When is a number a magic number?, I know magic number should not exists, so I know the following code about creating a Label from some UI framework and set the color RGB needs to be improved:
Magic number version:
Label* label=Label::create("someText");
label->setRGBColor(32,128,192);
to refactor it, every number is replaced with a constant:
Non magic number version:
const int LABEL_COLOR_RED=32;
const int LABEL_COLOR_GREEN=128;
const int LABEL_COLOR_BLUE=192;
Label* label=Label::create("someText");
label->setRGBColor(LABEL_COLOR_RED,LABEL_COLOR_GREEN,LABEL_COLOR_BLUE);
However, I found the "Non magic number version" is actually harder to read and maintain because:
It needs more number lines of codes
It is well known that the first one is red component, second one is green component, third one is blue component. Separating them looks odd and unnatural for me, resulting taking more time to study the code.
If multiple UI exists, eg: label2, I may type the wrong variable name and not easily to find, eg:
label_2->setRGBColor(LABEL_2_COLOR_RED,LABEL_2_COLOR_GREEN,LABEL_1_COLOR_BLUE);
Designers usually give me 3 new RGB together (eg:12,34,56), instead of just changing R,G or B, keeping label->setRGBColor(r,g,b) is easier to read and modify
According to "Comments are a code smell", comments should explain "why" instead of "How". But how can RGB be further explained in "Why"? Just write "//Designer suggest that"? Write "//It needs to show the color red" (isn't specify current result is red bad as const int FOUR=3?)? Or explain what is RGB in details?
In my experience, RGB among UI components are almost surely independent to each other, so it is almost surely no 2 UI would share the same "R" (or G,B), even if it is the same currently, it is not likely I would meet the case that "every UI changes the red component from 32 to 128" like it:
const int COMMON_R=32;
Label* label_1=Label::create("someText1");
label_1->setRGBColor(COMMON_R,32,96);
Label* label_2=Label::create("someText2");
label_2->setRGBColor(COMMON_R,128,192);
So I think "magic" color RGB is cleaner and simpler and hence better. Is that true?
Color
object, and pass that tolabel
?some_kind_of_purple = Color(32, 128, 192)
tells me a LOT more. No comment. But a named triplet. Or perhapsdefault_label_color = Color(1, 2, 3)