Sunday 15 April 2012

coding style - Python - removing copy paste code in subclasses -



coding style - Python - removing copy paste code in subclasses -

i have 2 classes z1 , z0 in legacy code re-create paste. both contain functions f1() ... f6() similar , function f7() in differ in string. class z1 contains string "z1" while z0 contains string "z0" in function f7().

the classes have next inheritance hierarchy:

class z1(y1) class y1(d) class d(b) class z2(y2) class y2(b) z1 -> y1 -> d -> b z2 -> y2 ------> b

what best way rid off re-create paste code in python?

if can safely add together f1() ... f6() b, that, , utilize type(self).__name__ instead of hard-coding z0 or z1. easiest solution, 1 potentially introduces bloat.

if don't want bloat b, create separate class (let's c), add together f1()...f7() (with modified f7) c, , have z1 , z2 inherit both c , y1/y2 - @ point may want think restructuring code in general.

either way, you'll want utilize introspection rid of hard-coded class names because hard coding stuff isn't elegant :)

python coding-style refactoring

No comments:

Post a Comment