Should functions always called back-to-back be wrapped inside a new function?

  softwareengineering

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.

4

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.

LEAVE A COMMENT