开发者

Java/C Ternary Operator

i want to transform a code from if condition to a ternary condition, first i've succeeded to transform one condition like:

    int minutes=59,hours=23;
// 1) if condition
if (minutes<59)
    minutes++;
else
    minutes=0;

// 2) ternary condition
minutes = (minutes < 开发者_运维技巧59) ? minutes+1  :  0;

Now the problem is when i've more than one value to edit it, like:

    int minutes=59,hours=23;
// if condition
if (minutes<59)
    minutes++;
else
{
    minutes = 0;
    if (hours<23)
        hours++;
    else 
        hours=0;
}

what do you think about the ternary condition ? thanks :)


What I think about it is that you shouldn't do it.

But if you really want to, you can write this:

minutes = (minutes < 59)
        ? (minutes+1)
        : ((hours = (hours < 23) ? (hours+1) : 0), 0);

But don't.


"Don't do that, then."

It isn't appropriate, or even possible, to transform all if-then constructs to ?: constructs, in either Java or C. (It is possible in functional languages, but even then it is not always advised.)

For what you appear to be trying to do, I would write

minutes++;
if (minutes == 60) { minutes = 0; hours++; }
if (hours == 24)   { hours = 0;   days++;  }
// etcetera


Multiple ternary conditions are painful! Just don't...

Not sure what you're trying to do but if need to round dates you might want to take a look at DateUtils for instance.


I think my preferred way to do this would be

minutes = minutes == 59 ? 0 : minutes + 1;
if (minutes == 0) {
    hours = hours == 23 ? 0 : hours + 1;
}

You avoid the readability problems of the nested ifs, but don't have a crazy ternary statement. The best balance between concision and readability, I think.


Though the ternary operator is a nice shorthand when you would like to embed a conditional into a larger expression, it's not good to overuse it. It can make things less readable and doesn't necessarily speed up your code. However...

You can use the comma operator to combine expressions (the value will be that of the last one). Your example could be rewritten as follows:

minutes = (minutes < 59) ? 
    minutes + 1 : 
    ( hours < 23 ? 
        (hours++, 0) : 
        (hours = 0) );

Though for the example you gave, using the modulus operator for hours could simplify it as follows:

hours = (minutes = (minutes + 1) % 60) ? hours : ((hours + 1) % 24);

..since the result of an assignment is the value assigned in C, and you can use that as your test expression.

This works for C... not sure about Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜