Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices: Many small functions/methods, or bigger functions with logical process components inline? [closed]

Is it better to write many small methods (or functions), or to simply write the logic/code of those small processes right into the place where you would have called the small method? What about breaking off code into a small function even if for the time being it is only called from one spot?

If one's choice depends on some criteria, what are they; how should a programmer make a good judgement call?

I'm hoping the answer can be applied generally across many languages, but if necessary, answers given can be specific to a language or languages. In particular, I'm thinking of SQL (functions, rules and stored procedures), Perl, PHP, Javascript and Ruby.

like image 386
Pistos Avatar asked Oct 30 '08 14:10

Pistos


People also ask

Is it better to have many small functions?

The main advantages to keep the size of the method small (which means dividing a big method into several small methods) are: better unit testing (due to low cyclomatic complexity) better debugging due to a more explicit stack trace (instead of one error within one giant method)

How small should a function be?

A function should be as short as possible. A function may grow if it needs to enforce sequential coupling rules, e.g. if there are several steps that need to happen in a particular order. On the other hand, the individual steps could be farmed out to separate functions if the function gets too big.

How do you write a small function?

Functions should be small !!!They should not be longer than 20 lines and mostly less than 10 lines. Functions should be making as few arguments as possible, ideally none. Small functions are easy to understand and their intention is clear. “Coding like poetry should be short and concise.”


2 Answers

I always break long methods up into logical chunks and try to make smaller methods out of them. I don't normally turn a few lines into a separate method until I need it in two different places, but sometimes I do just to help readability, or if I want to test it in isolation.

Fowler's Refactoring is all about this topic, and I highly recommend it.

Here's a handy rule of thumb that I use from Refactoring. If a section of code has a comment that I could re-word into a method name, pull it out and make it a method.

like image 171
Bill the Lizard Avatar answered Oct 02 '22 04:10

Bill the Lizard


The size of the method is directly linked to its cyclomatic complexity.

The main advantages to keep the size of the method small (which means dividing a big method into several small methods) are:

  • better unit testing (due to low cyclomatic complexity)
  • better debugging due to a more explicit stack trace (instead of one error within one giant method)
like image 42
VonC Avatar answered Oct 02 '22 03:10

VonC