minimalize an if conditions
I wrote the following constructor that gets 2 parameters and if a value (x or y) is negative, it will be initialize into zero.
public Point1 ( int x , int y )
{
//if one or more of the point values is <0 , the constructor will state a zero value.
if (x < 0)
{
_x = 0;
}
else
_x=x;
if (y < 0)
{
_y = 0;
}
else
开发者_JAVA百科 _y = y;
}
I just need it to be minimalism if it can be...
_x = Math.max(x,0);
_y = Math.max(y,0);
_x = Math.max(0, x);
_y = Math.max(0, x);
or
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
_x = (x<0)?0:x ;
_y = (y<0)?0:y ;
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
How about...
_x = (x < 0) ? 0 : x;
_y = (y < 0) ? 0 : y;
This might work for you:
public Point1 (int x, int y)
{
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
}
Try:
_x = Math.max(0, x);
_y = Math.max(0, y);
If you want to use the fewest characters possible, maybe something like:
public Point1(int x, int y) {
_x = Math.max(0,x);
_y = Math.max(0,y);
}
Write a function, NegativeToZero
and use that instead:
_x = NegativeToZero(x);
_y = NegativeToZero(y);
That code is as simple as it gets. If you're looking for cleaner code (and this depends on the developer) I always use ternary operators for simple if-else statements:
_x = (x < 0) ? 0 : x;
_y = (y < 0) ? 0 : y;
That just says that if x < 0, use 0, otherwise use x
public Point1 ( int x , int y ) {
if(x < 0 ) x = 0;
if( y < 0) y = 0;
_x = x;
_y = y;
}
or
public Point1 ( int x , int y ) {
_x = x < 0 ? 0 : x;
_y = y < 0 ? 0 : y;
}
What I'd actually prefer:
public Point1(int x, int y) {
this.x = nonnegative(x);
this.y = nonnegative(y);
}
where:
public static int nonegative(int value) {
if (value < 0) {
throw new IllegalStateException(
value + " is negative"
);
}
return value;
}
If you hide the constructor and add a static creation method, so much the better (if a little more verbose). Certainly a negative carpet-sweeping creation method shouldn't be munged into a constructor.
This is just for fun (no conditionals and of course not efficient at all). It does minimize if conditionals though :)
int temp = (x&(~Integer.MAX_VALUE))>>>(Integer.SIZE - 6);
_x = (x >>> (temp - (temp >> 5))) - (temp >> 5);
Slight improvement:
int temp = (x&(~Integer.MAX_VALUE))>>>(Integer.SIZE - 6);
_x = (x << (temp - (temp >> 5))) & Integer.MAX_VALUE;
精彩评论