Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you refactor code into private methods if they aren't called more than once? [closed]

Is it worth extracting private methods for code that only gets called once in a class, or leaving the code in the parent method (maybe) with a comment that says what it does?

like image 722
mcintyre321 Avatar asked Apr 22 '09 11:04

mcintyre321


2 Answers

It is always worth extracting methods if it clarifies the intent of the code.

This is especially true for very long methods. While comments are fine, they do not delineate (at least not in a very solid way) where the process it explains ends and where the next one begins. Sometimes common abstractions will only become more obvious after you've extracted the method.

If you are into automated unit-testing (not necessarily TDD), it will also be much, much easier to unit test smaller chunks of methods -- although you might have to make your methods public for that, depending on the testing framework you use.

The point is, you can't go wrong with smaller methods, especially if they have descriptive names.

like image 143
Jon Limjap Avatar answered Nov 08 '22 05:11

Jon Limjap


There is a huge benefit in doing this. It's all about information hiding, and making intentions very clear.

In Refactoring to Code they called this Composition Methods where you break a large method down into many smaller methods. This does two things.

First it reduces the ammount of information you need to worry about when working on the parent method.

Secondly the name of the method should indicate its intention which makes the code more readable.

like image 22
JoshBerke Avatar answered Nov 08 '22 03:11

JoshBerke