开发者

How can I reorder sub-expressions in Visual Studio?

I would like to re-order sub expressions in an if statement. Here is an example:

Input:

if ((a == 1) || (a == 3) || (a == 2))
{
}

Desired output:

if ((a == 1) || (a == 2) || (a == 3))
{
}

Is there any tool that can automatically reorder these sub expressions?

Or the following identical code:

Input:

switch (a)
{
    case: 1;
    case: 3:
    case: 2;
    break;
}

Desired output:

switch (a)
{
    case: 1;
    case: 2:
    case: 3;
    break;
}

Clarification:

My question do开发者_StackOverflow中文版es not address short circuiting. This is a useful discussion, and as Reed pointed out re-ordering parameters in most cases is dangerous.

I was just curious if parsing tools such as ReSharper or Code Rush have this functionality. These tools probably create an AST to preform their refactoring and for them to reorder sub-expressions would not be too difficult.


I don't know of a tool that would automatically do this, at least in the "if" statement case.

In general, it would be bad if a tool did this automatically. The following two statements behave differently:

if ((a == 1) && (b == 3) && (c == 2))

and

if ((a == 1) && (c == 2) && (b == 3))

In the first case, if b != 3, but a == 1, it will check a, then check b, then skip the block.

In the second case, it would check a, then check c, then check b. You'd lose the ability to short-circuit the checks.

Granted, in most cases, this doesn't matter, but when you're using methods instead of values for a/b/c, it can be expensive.


Edit: I see that you've updated to use OR instead of AND. The same issue exists with OR, except that the short circuit will happen when the first condition is true, instead of when the first condition is false.


I agree with Reed Copsey's answer. However, since no one has mentioned it yet:

Depending on the language that you use, the switch statement doesn't behave the same as if/elsif/else. I know that for C, Java, etc. they use branch tables to determine what should be executed. (Not sure about something like PHP.) It's mentioned on the Wikipedia article, if you'd like to read more.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜