Remove Double Negative -- 移除双重否定

来源:互联网 发布:mac显示器颜色 编辑:程序博客网 时间:2024/04/30 15:15

Remove Double Negative

Refactoring contributed by Ashley Frieze and Martin Fowler

You have a double negative conditional.

你有一个双重否定条件语句

Make it a single positive conditional

使其变为一个肯定条件语句。

 if ( !item.isNotFound() )

 if ( item.isFound() )

Motivation

Double negatives are often frowned on by mavens of natural language. Often this frowning is inappropriate - certainly in English the double negative has its uses.

双重否定不太符合自然语言,不易于理解,或者容易产生错觉。(另外有时候‘!’很容易漏掉)

But that is not true in programming. There double negatives are just plain confusing. So kill them on sight.

干掉它!!!!不要让它在我面前出现第二次!

Mechanics

  • If you don't have a method with the opposite sense, create one. The body can just call the original (you can fix that later).
  • 如果没有相对的方法(如isNotFound的相对方法为isFound),那么就创建一个。
  • Compile
  • 编译
  • Replace each double negative with a call to the new function
  • 以肯定条件取代双重否定。
  • Compile and test after each replace
  • 编译测试。
  • If the negative form of the method isn't used elsewhere, use Inline Method to inline it into the positive form
  • 如果否定方法没有到处用到,利用InlineMethod使得变为一个肯定方法。
  • If you do need both forms, consider moving the body of the negative form over to the positive and reversing its sense, and then have the negative method call the positive one.
  • 如果含有两个分支,考虑将肯定条件放在第一分支,否定条件放在第二分支。
  • Consider using Substitute Algorithm if the positive form is difficult to understand.
  • 如果肯定条件的代码不易理解考虑使用 Substitute Algorithm(替换算法)进行重构。