FacundoGFlores FacundoGFlores - 1 year ago 108
Python Question

Improving code for similar code found

I passed codeclimate to my code, and I obtained the following:

Similar code found in 1 other location

This is my code:

stradd = 'iterable_item_added'
if stradd in ddiff:
added = ddiff[stradd]
npos_added = parseRoots(added)
dics_added = makeAddDicts(localTable, pk, npos_added)
dics_added = []
strchanged = 'values_changed'
if strchanged in ddiff:
updated = ddiff[strchanged]
npos_updated = parseRoots(updated)
dics_updated = makeUpdatedDicts(localTable, pk, npos_updated)
dics_updated = []

are repeated. How to change it?

Answer Source

just abstract the parameters and create an helper method:

def testmethod(name,localTable,m,ddiff,pk):
    if name in ddiff:
        npos = parseRoots(ddiff[name])
        rval = m(localTable, pk, npos)
        rval = []

    return rval

the call it:

dics_added = testmethod('iterable_item_added',localTable,makeAddDicts,ddiff,pk)
dics_updated = testmethod('values_changed',localTable,makeUpdatedDicts,ddiff,pk)

note: be careful when factorizing code, you can introduce bugs (and make code better readable :)).

Also: that helper method forces to pass a lot of local variables. Maybe creating an object and member variables would simplify even more.

In that case, it appears to be a bit "overkill" to do that in order to make your review tool shut up.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download