If I have two functions that I repeatedly use back-to-back, should I wrap those functions inside a new one? For example, I have:

def prepare_data(data):
  # do a few lines of data prep
  return prepared_data

def process_data(prepared_data):
  # do a few lines of processing
  return result

These two functions always run one after the other. In fact, if I see process_data without prepare_data in front of it, it's a bug. I call these functions several times throughout my codebase. Given this, is it a good design to create a wrapper function that calls both of them? Like so:

def prepare_and_process_data(data):
  prepared_data = prepare_data(data)
  result = process_data(prepared_data)
  return result

This way I'm just calling one function throughout the codebase.

  • Is the downvote because it's so obviously I should or so obvious I shouldn't? Or so obvious that there is no general principle and it's subjective?
    – jss367
    Feb 19 at 19:07
  • I might also have prepare_data set a field or flag in the data, and process_data raise an exception if that flag is not set.
    – user949300
    Feb 19 at 20:35
  • 2
    I vote not to create the wrapper function until you think of a better name. The name should tell me less about how it works and more about what it’s for. Feb 19 at 21:05
  • Related: Sequential coupling
    – John Wu
    Feb 19 at 21:57

In fact, if I see process_data without prepare_data in front of it, it's a bug.

Then in this specific case, yes. Put them into a prepare_and_process_data function.

This might not apply for all function calls that are found together, but if you see the same groups of functionality being used in the same way, then it's probably time to refactor that pattern into its own 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.