Friday 13 July 2007

cast it


public static int roundSup(float n){
int round=0;

if(n > (new Float(n).intValue()))
round = new Float(n+1).intValue();
else round=new Float(n).intValue();

return round;
}

Sure it needs to create new Float object to do this operation. And the code is ugly.

Try this,

public static int roundSup(
final float n
) {
return ((int) n) + 1;
}

Wow ! Cleaner, clearer, better !
Why just a cast will do it ?

See Java Language Specification 3rd : Narrowing Primitive Conversions

But don't forget to COMMENT you're code ! A code without comments it's like a life without meaning.

No comments: