FacundoGFlores FacundoGFlores - 2 months ago 20
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)
else:
dics_added = []
strchanged = 'values_changed'
if strchanged in ddiff:
updated = ddiff[strchanged]
npos_updated = parseRoots(updated)
dics_updated = makeUpdatedDicts(localTable, pk, npos_updated)
else:
dics_updated = []


Where
iterable_item_added
and
values_changed
are repeated. How to change it?

Answer

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)
    else:
        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.