How to DRY refactor several similar functions

dryrefactoringvariables

I was assigned a refactoring.

We have several modules having similar functions with some differences. My task is to extract common portions of code for DRY principle.

I am a little lost how to do it.

I could just cut&paste similar fragments of code, extracting them into separate functions, but if I do it this way mechanically, then the declarations and usage of local variables of the fragmented functions may happen to fall into different functions, what could lead to invalid code.

Could you do some practical advice how to handle this issue. I'd wish a step-by-step guide on refactoring such code with local variables.

And also: In some reason my boss wants the resulting code not to be object oriented. I think this can be solved by passing fragments of code as function pointers.

I can't show a code example for my question, because the real code is closed-source and I can't write a minimal example, because the entire issue is dealing with long functions.

One more note: We write in Perl.

Best Answer

You should look for what they have in common, e.g. they all open an SQL connection, they all need to handle errors and close resources at the end, they all call some API in the middle, etc. Then focus on separating what is constant from what is variable.

There are a few patterns that help deal with this. Consider the

Strategy Pattern

Template Pattern

Related Topic