Remove Double Negative -- 移除双重否定

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(替换算法)进行重构。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值