Refactoring example in Python

hamed sheykhlou
3 min readAug 9, 2021

--

Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.

Refactoring is a controlled technique for improving the design of an existing code base. Its essence is applying a series of small behavior-preserving transformations, each of which “too small to be worth doing”. However the cumulative effect of each of these transformations is quite significant. By doing them in small steps you reduce the risk of introducing errors. You also avoid having the system broken while you are carrying out the restructuring — which allows you to gradually refactor a system over an extended period of time

Recently I finished Martin Fowler Refactoring book and it was very good. but there is a little point about it, the source codes are with JavaScript. I don’t like JavaScript, and because of that, I decided to convert the codes based on refactoring steps to Python.

every refactoring step is specified by a commit with a little description. Full commit logs can be found here on Github.

Initial code

here is the initial code in Python:

This code wants to Print bill, based on various events specified by two JSON files and print output like this:

play.json:

and this is bills.json

Refactoring steps

Through refactoring, we change a lot of things with the code. I have done these steps again and again to reach our final refactored code:

If you have to spend effort looking at a fragment of code and figuring out what it’s doing, then you should extract it into a function and name the function after the “what.” Then, when you read it again, the purpose of the function leaps right out at you, and most of the time you won’t need to care about how the function fulfills its purpose (which is the body of the function).

turning variables into their own functions makes it easier to extract parts of the function, since I no longer need to pass in variables into the extracted functions. Putting this logic into functions often also sets up a stronger boundary between the extracted logic and the original function, which helps me spot and avoid awkward dependencies and side effects.

Rename Method, Add Parameter, Remove Parameter, Change Signature

if you’re doing two different things in the same loop, then whenever you need to modify the loop you have to understand both things. By splitting the loop, you ensure you only need to understand the behavior you need to modify.

Code is easier to understand when things that are related to each other appear together. If several lines of code access the same data structure, it’s best for them to be together rather than intermingled with code accessing other data structures. At its simplest, I use Slide Statements to keep such code together.

Final Code

here is the final code:

Full commit logs can be found here on Github.

--

--