Refactoring – Handling Large Chunks Within a Function

refactoring

I am designing an API which mostly involves refactoring the original code.

So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea.

The code looks like

do_something():
     if (isTrue):
         #Large block of statements.
     else:
         #another large block of statements.

The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block.

I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better.

I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.

Best Answer

If you don't want to start with the obvious thing, you can also start with identifying small, common portions in block A and B and refactor each portion to a separate method which is then called from A as well as from B. Ideally, this will lead you to new blocks A and B only containing non-common functionality.

But then moving those functionality to separate methods will most probably still be a good idea, and the final result will be the same as if you did it the other way round.

To my experience, extracting small, common functions from A and B first has the advantage that you can deal with small methods which are quite often easier to understand, so the chance of introducing errors is smaller. Doing this step-by-step reduces also the size of the blocks A and B, and increases their readability, so afterwards the refactoring of A and B to methods gets easier.

Related Topic