2
\$\begingroup\$

All colors can be represented by an int, and often you want to get the individual red, green and blue values from that int.

I have a method int2rgb (and another called rgb2int) that does this. Is this a clear/good name?

public static int[] int2rgb(final int color) {
    return new int[] { (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF };
}

public static int rgb2int(final int red, final int green, final int blue) {
    return (red << 16) + (green << 8) + blue;
}

public static int rgb2int(final int[] color) {
    return (color[0] << 16) + (color[1] << 8) + color[2];
}

And in case you are interested, the rest of the class is here.

\$\endgroup\$
0
10
\$\begingroup\$

As far as naming is concerned: Using 2 instead of to is pretty much a no-no - "to" is spelled out everywhere in the Java standard library. Further Java's naming convention is to capitalize every word, but the first in method names - except for acronyms which are all-caps no matter where they appear in the name. So the methods should be called intToRGB and RGBtoInt (to is lower case because it directly follows an acronym - compare for example Color.RGBtoHSB in the java standard library).

In regards to the code: I'd recommend representing your colors as Color objects rather than 3-element arrays. If you choose to do that, you don't have to define any of your methods, because that functionality already exists in the Color class.

\$\endgroup\$
1
1
\$\begingroup\$

Make a RGB class with properties Red, Green and Blue and add a static FromInt() method, or a RGB(int color) constructor.

\$\endgroup\$
0
1
\$\begingroup\$

Capitalization:

I would use something in the form rgbToInt or intToRgb. I know, Javadoc tells that acronyms should be capitalized, but that leads to some weird results (v.g., RGB rGBVariable;)

1) Joel Spolsky recommends to use "form" instead of "to", so code is easier to read. Compare

Rgb rgbVariable = intToRgb(intVariable); // mix of `rgb` an `int` in the line

to

Rgb rgbVariable = rgbFromInt(intVariable); // `rgb` to the right, `int` to the left; mistakes are easier to spot

More info here http://www.joelonsoftware.com/articles/Wrong.html

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.