A Funny Java Flavoured Look at the World

Wednesday, August 30, 2006

Using the Java API can save you time

I learnt a good lesson today, look in the Java API it could save you time. It could save you time writing something that has already been written.

luckily for me in this case it wasn't anything that took me very long, I saw me I had to ask someone about the logic of it but I thought I would write the a small util method in case I ever needed to do it again.

I was trying to convert a number which was a colour back into the RGB (Red, Green, Blue) value. I had the number I wanted to convert into an RGB but I wasn't sure how to do it. I was then given the logic to convert an RGB to the current colour number (I don't know what it's called)
(red * 65536) + (green * 256) + blue.

I'm afraid I am rubbish at maths so I had to ask one of my developer buddies and this is the code that we made which was put into a static helper class called MoreMaths because it was for classes which he thought should have been included in Maths. This method maybe should be included in here but we haven't got a NumberUtils class, although I will be probably cursing next time I want a similar function and go through this all again.

public class MoreMaths {

/** Creates a new instance of MoreMaths */
public MoreMaths() {
}

public static Color convertRGB (final int numberToConvert) {

//Color colorAdded = new Color(numberToConvert);
//below is the logic more for interest than use so if you were
//wondering how you convert a number into an RGB
final int red = (numberToConvert / 65536 );

final int gb = numberToConvert - (65536 * red);

final int green = ( gb / 256 );

final int blue = gb - (256 * green);

return new Color(red, green, blue);

}
}

It was only when I was thinking what should I return, do I really want to return an int array and then I thought hmmm I will return a Color object. It was at this time just as I was writing a unit test to see what the method produced that I thought hmmm I bet Color does all the converting for me and yes it does. If I had just looked at the API straight away I would have seen it and saved myself working out how to convert it and then writing a method that converted it.


so there you go, go and root around in the API, it could save you a lot of time and you will be using reliable tested code.

0 Comments:

Post a Comment

<< Home