Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I break a function?

Tags:

refactoring

Its prudent to break a long function into a chief function and helper functions.

I know that the outside the module only chief function will be called, but its long length may prove to be intimidating.

Textbooks put a limit on the number of lines, but I feel that this is too rigid.

P.S. I am programming in Python and need to process incoming, messages. The function returns a tuple containing the message but in Python's internal data types. So you can see somewhat independent code for each message type.

Duplicate Question

When is a function too long?

like image 846
Xolve Avatar asked Mar 04 '09 13:03

Xolve


4 Answers

One good rule of thumb is that if it doesn't fit on a single screen it is worth thinking about splitting it up. But only if it makes sense to split it up, some long functions are perfectly readable and it doesn't make any sense to slavishly split them into multiple functions just for the sake of it.

like image 36
andynormancx Avatar answered Oct 19 '22 20:10

andynormancx


I think you need to go about this from the other end of the problem. Think bottom-up. Identify small units of work, as small as possible, and start composing your code that way. You will only run into spaghetti-code issues when you code top-down and don't keep a structured approach.

If you already have spaghetti code and need to refactor, you pretty much have to start over. It is probably more work to break up existing spaghetti code than to rewrite it, and the result may not be as good.

I don't think there should be a hard number for the lines of code in a method either, but well written code does not have methods with more than 5 to 10 lines in the lower layers, and 20 to 30 lines in the business logic. To give you some kind of metric.

like image 166
cdonner Avatar answered Oct 19 '22 19:10

cdonner


I'm not a big fan of breaking a function into multiple functions unnecessarily. It's not a hard and fast thing - if there are things that seem like distinct logical units, then by all means, break those out and think about them separately. But don't just break things out for the sake of some guideline like "one page per function" or "N lines per function".

like image 21
Paul Tomblin Avatar answered Oct 19 '22 19:10

Paul Tomblin


Never write a function that, when printed on fanfold paper, is taller than you are.

like image 2
joeforker Avatar answered Oct 19 '22 20:10

joeforker