BigWeirdAlFan
BigWeirdAlFan

Reputation: 105

How to Reduce Code Duplication of If-Else Statements in Python

I'm a student with the very bad habit of duplicating code all over the place, which is something I want to change.

Below, I have a snippet of code from a function I'm writing. Quick explanation: The code would look at an HR website for a person, and return info about the employees he's managing (assuming he manages anyone).

There are two types of employees: regular employees and contract workers. On the website, regular employees underneath the manager would all be listed under employeeList, and the contractors would be listed under contractWorkerList.

response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager')
allDataFromPage = (response.read())
jsonVersionOfAllData = json.loads(allDataFromPage)

listOfAllReports = []

numOfEmployeeDirectReports = len(jsonVersionOfAllData['employeeList']['list'])
numOfContractWorkerReports = len(jsonVersionOfAllData['contractWorkerList']['list'])

if numOfEmployeeDirectReports != 0:
    for i in range(0, numOfEmployeeDirectReports, 1):
        workerInfo = {}
        workerInfo['empLname'] = jsonVersionOfAllData['employeeList']['list'][i]['lastName']
        workerInfo['empFname'] = jsonVersionOfAllData['employeeList']['list'][i]['firstName']
        listOfAllReports.append(workerInfo)

if numOfContractWorkerReports != 0:
    for i in range(0, numOfContractWorkerReports, 1):
        workerInfo = {}
        workerInfo['empLname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['lastName']
        workerInfo['empFname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['firstName']
        listOfAllReports.append(workerInfo)

As you can see, I have several lines of code that are almost identical to other lines, with only small variations. Is there a way to check both contractWorkerList and employeeList to see if they're not empty, and (assuming they're not empty) go through both contractWorkerList and employeeList and grab values without duplicating the code?

(Since I'm a relative beginner, any simple examples you could provide with your recommendations would be much appreciated)

Upvotes: 2

Views: 1587

Answers (3)

Tony Babarino
Tony Babarino

Reputation: 3405

Most common way of avoiding code duplication is to define a function with that code.

def checkIfEmpty(numOfReports, listName):
    if numOfReports != 0:
        for i in range(0, numOfReports, 1):
            workerInfo = {}
            workerInfo['empLname'] = jsonVersionOfAllData[listName]['list'][i]['lastName']
            workerInfo['empFname'] = jsonVersionOfAllData[listName]['list'][i]['firstName']
            listOfAllReports.append(workerInfo)

So You will end up with simple and easy to read code:

checkIfEmpty(numOfEmployeeDirectReports, 'employeeList')
checkIfEmpty(numOfContractWorkerReports, 'contractWorkerList')

Upvotes: 2

Gerrat
Gerrat

Reputation: 29690

For starters, every time you see something duplicated, think about creating a variable upfront & use that. After that, you can decide what should be factored out into a function. Below, I just removed most of the duplicated items.

response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager')
allDataFromPage = (response.read())
jsonVersionOfAllData = json.loads(allDataFromPage)

listOfAllReports = []

for listType in ('employeeList', 'contractWorkerList'):

    json_ver = jsonVersionOfAllData[listType]['list']
    directReports = len(json_ver)

    if directReports != 0:
        for i in range(0, directReports, 1):
            workerInfo = {}
            for wi_name, json_name in (('empLname', 'lastName'), ('empFname', 'firstName')):
                workerInfo[wi_name] = json_ver[i][json_name]
            listOfAllReports.append(workerInfo)

Upvotes: 3

Brendan Abel
Brendan Abel

Reputation: 37539

In this particular scenario, you could do something like this:

for var, key in [(numOfEmployeeDirectReports, 'employeeList'),
                 (numOfContractWorkerReports, 'contractWorkerList')]:
    if var != 0:
        for i in range(0, var, 1):
            workerInfo = {}
            workerInfo['empLname'] = jsonVersionOfAllData[key]['list'][i]['lastName']
            workerInfo['empFname'] = jsonVersionOfAllData[key]['list'][i]['firstName']
            listOfAllReports.append(workerInfo)

Upvotes: 0

Related Questions