Thursday, April 5, 2012

Python: When NOT To use Global Variable, Use Return!

Reference: http://stackoverflow.com/q/10036747/1276534
Credit: Ricky, jdi, Maty

Using global variable in your Python function is really easy, but today I read a post that explain why not to use it. And I found it make a lot of sense, I am not used to write without the pass by reference. Take a look at this code below.
def getSalary():
    global a, b, c
    a = input("Please enter the boss's salary")
    b = input("Please enter the director's salary")
    c = input("Please enter the factory worker's salary")

Notice this function, it asks the user for 3 different salary and store them in a, b, c respectively. But it is not a good practice, instead we should use the return function.

def getSalary():
    a = input("Please enter the boss's salary")
    b = input("Please enter the director's salary")
    c = input("Please enter the factory worker's salary")
    return a, b, c

# And to way to use this function is like
a, b, c = getSalary()
This make the code a lot more readable, and useable. Imagine if you make a mistake in the program, if you use global variable, you will have a very hard time tracking where exactly does your value get changed. While doing it the second method, you will know a, b, c is changed on the getSalary line's return. And you can print them as you writing your program to debug it.

And as jdi pointed out, it is always always better to use more meaningful variable name than a,b,c,d, or x,y,z. Imagine you use bossSalary, directorSalary, factoryWorkerSalary, the code is a lot easier to understand. Granted, maybe a little bit long. But maybe you can use workerSalary at least!

And when you have a function that modify your object, such as your own class, a list. Maybe (depending on the situation), you might want to create a new variable and assign it, or you can overwrite it too!
def newSalary(salary):
    return salary + salary * 0.02

# Use it like this
nextYearSalary = newSalary(salary)
# Or overwrite the old one
mySalary = newSalary(salary)

No comments:

Post a Comment