开发者

How can I shorten this code using ternary operators?

I have the following piece of code

public class direction do(direction)
    if(istrue) {
        left = do(left);
    } else {
        right = do(right);
    }
}

I was wondering if there is anyway to shorten this. I tried using ternary operator开发者_如何学编程s, but had some difficulty. suggestions?


In your example, there is no sensible use for the ternary operator.

The value of the ternary operator in Java (and other C-like languages) is that a ternary operator expression is an expression, while the if statement is a statement. Expressions yield values, but statements do not. If you are not using the value resulting from the ternary operator expression, then you have no business using the ternary operator. Just don't do it.

For your interest, here's an example of a valid use of the ternary operator:

int max(int x, int y) {
    return x > y? x : y;
}


You might use a ternary expression if the other programmers on your team don't mind. So if your example were in valid Java:

public void Do(Direction direction)
{
    (istrue)? left = Do(left) : right = Do(right);
}

You could omit the braces in the if:

public void Do(Direction direction)
{
    if ( istrue )
        left = Do(left);
    else
        right = Do(right);
}

Or you even could have a one liner:

public void Do(Direction d)    { (istrue)? left = Do(left) : right = Do(right); }

Above all, choose a style that's clear and not too clever. Use more lines if they make your code easier to read and understand.

One-liners generally aren't very readable, though in some cases they make sense (to me), especially if you have families of very similar small methods:

public String getFirstName()        { return first_name; }
public String getLastName()         { return last_name; }
public String getAddress1()         { return address1; }
public String getAddress2()         { return address2; }
public String getCity()             { return city; }
public String getState()            { return state; }
public String getZip()              { return zip; }


Your code requires that you assign to two different variables (left or right) depending on the condition. A ternary expression won't help you do that, since it cannot be used on the left hand side of an assignment.

That leaves the RHS of the (two) assignments. While you could in theory use a ternary expression, it will probably make the code longer.

So the short answer is that a ternary operator won't help.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜