java 代碼細節(Inline Method)

來源:互聯網
上載者:User


這個觀點來自《重構-----改善既有代碼的設計》

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

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

int getRating() {        return (moreThanFiveLateDeliveries()) ? 2 : 1;} boolean moreThanFiveLateDeliveries() {        return _numberOfLateDeliveries > 5;}
04
int getRating() {        return (_numberOfLateDeliveries > 5) ? 2 : 1;}
Motivation 05

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. 06

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. 07

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 08

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. 09

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.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.