您的位置:首页 > 其它

Reverse Conditional -- 反转条件

2013-03-18 20:47 183 查看

Reverse Conditional

Refactoring contributed by Bill Murphy and Martin Fowler

You have a conditional that would be easier to understand if you reversed its sense.

通过反转条件语句能使得条件语句更容易理解。

Reverse the sense of the conditional and reorder the conditional's clauses.

反转条件并且重新排列条件分支。
if ( !isSummer( date ) )
charge = winterCharge( quantity );
else
charge = summerCharge( quantity );




if ( isSummer( date ) )
charge = summerCharge( quantity );
else
charge = winterCharge( quantity );


Motivation

Often conditionals can be phrased in way that makes them hard to read. This is particularly the case when they have a not in front of them. If the conditional only has a "then" clause and no "else" clause, this is reasonable.
However if the conditional has both clauses, then you might as well reverse the conditional.
经常有一些条件语句表达方式不同于日常的表达方式,特别是他们还不是显而易见的时候。如果条件语句只有if没有else,还算是可以的。如果条件语句具有完整的分支时,你应该使用反转条件重构手段使得符合日常的表达方式。

Mechanics

Remove negative from conditional.
移除否定条件
Switch clauses
交换条件分支。
Compile and test.
编译测试
There's further discussion on this kind of refactoring on the wiki.
更多内容请查看wiki。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息