Just Stop Writing Python Functions Like This!!!
Last week, I was reviewing someone else’s code. I just stumbled upon a Python function that made me feel whether I must cry or laugh.
Then I decided to write about that incident…so that you didn’t make the same mistake.
Not a medium member, yet? Read it FREE here.
Terrible Code About Which I am Talking About
This was the code that just made me feel like this:
def process_data(data, flag1, flag2, flag3): if flag1: data = [item for item in data if item.isdigit()] if flag2: data = [item.upper() for item in data] if flag3: data = sorted(data) result = "Processed: " + ", ".join(data) return result
This code doesn’t seem that much bad at first glance. But let me tell you why I am saying this to be terrible:
At first glance, it doesn’t seem too bad, right? But let’s understand what’s wrong with this code.
1. Too Many Flags
It’s using too many flags (flag1, flag2, flag3) to control behavior, which is making the function a little bit confusing.
In this, every time we are calling a function, we have to figure out which combination of flags is producing the desired result.
Let me explain this with the help of this example
res = process_data(my_data, True, False, True)
Did you understand what does True, False, True even means? This is the same case with the above function.