2

According to Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?, I should split long functions into smaller functions even if they are used once only, but my question is , how should I call the extracted functions?

Style 1: centralize them

callFunctions(){
    function1();
    function2();
    function3();
}

Style 2: call it one by one:

function1(){
  .
  .
  .
  function2();
}

function2(){
  .
  .
  .
  function3();
}

Which style should I use?

6

I prefer the centralized approach myself, rather than the chained approach.

With the chained approach, you're not gaining anything except a little bit of readability in that you now have a few small functions instead of one large one (and you're not really gaining any readability into the steps taken to complete the larger action, because you then have to read through each of the chained functions to see what's happening across the board).

With the centralized approach, you gain two distinct advantages:

  1. You can now very easily see, from the main function, what steps are required to complete the whole task
  2. Each of the smaller functions can now be more easily isolated in that they are less likely to have external factors governing how they run (e.g., you can more easily re-use some of these steps later, if need be)
  • Also, there will be cases where calling a function is dependent on the success or failure of the previous one. I personally find it easier to follow and debug that in the centralized model. – mickeyf Mar 7 at 22:39
5

In addition to jleach's answer, the reason the "centralized" approach is preferable is that code in functions should usually be at the same level of abstraction (see: Single Level of Abstraction).

In your example, callFunctions() is on a more abstract level, composing the necessary computations into finer steps functionN(). Then these "split" functions go into more detail and are less abstract.

Since functionN() is on this finer level of detail, calling other functionN()s, which is a function call on the higher level of abstraction, within functionN() would break the rule of "same level of abstraction within a function".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.