0

I have two classes Z1 and Z0 in my legacy code which are basically a copy paste. They both contain functions f1() ... f6() which are similar and function f7() in which they differ in string. Class Z1 contains string "Z1" while Z0 contains string "Z0" in function f7().

The classes have the following 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 is the best way to get rid off this copy paste code in Python?

1
  • I would rewrite everything. Commented Nov 6, 2014 at 19:50

1 Answer 1

1

If you can safely add f1() ... f6() to B, then you could just do that, and use type(self).__name__ instead of hard-coding Z0 or Z1. That would probably be the easiest solution, but also the one that potentially introduces the most bloat.

If you don't want to bloat B, I would probably make a separate class (let's say C), add f1()...f7() (with the modified f7) to C, and have Z1 and Z2 inherit from both C and Y1/Y2 - but at that point you may want to think about restructuring the code in general.

Either way, you'll probably want to use introspection to get rid of the hard-coded class names because hard coding stuff isn't very elegant :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.