java 代码细节(Inline Method)


这个观点来自《重构-----改善既有代码的设计》

A method’s body is just as clear as its name.

Put the method’s body into the body of its callers and remove the method.

int getRating() {
        return (moreThanFiveLateDeliveries()) ? 2 : 1;
}
 
boolean moreThanFiveLateDeliveries() {
        return _numberOfLateDeliveries > 5;
}
graphics/arrow.gif
int getRating() {
        return (_numberOfLateDeliveries > 5) ? 2 : 1;
}

Motivation

A theme of this book is to use short methods named to show their intention, because these methods lead to clearer and easier to read code. But sometimes you do come across a method in which the body is as clear as the name. Or you refactor the body of the code into something that is just as clear as the name. When this happens, you should then get rid of the method. Indirection can be helpful, but needless indirection is irritating.

Another time to use Inline Method is when you have a group of methods that seem badly factored. You can inline them all into one big method and then reextract the methods. Kent Beck finds it is often good to do this before using Replace Method with Method Object. You inline the various calls made by the method that have behavior you want to have in the method object. It’s easier to move one method than to move the method and its called methods.

I commonly use Inline Method when someone is using too much indirection and it seems that every method does simple delegation to another method, and I get lost in all the delegation. In these cases some of the indirection is worthwhile, but not all of it. By trying to inline I can flush out the useful ones and eliminate the rest.

Mechanics

  • Check that the method is not polymorphic.

    Don’t inline if subclasses override the method; they cannot override a method that isn’t there.
  • Find all calls to the method.

  • Replace each call with the method body.

  • Compile and test.

  • Remove the method definition.

Written this way, Inline Method is simple. In general it isn’t. I could write pages on how to handle recursion, multiple return points, inlining into another object when you don’t have accessors, and the like. The reason I don’t is that if you encounter these complexities, you shouldn’t do this refactoring.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值