[Tutor] Help refactoring this code

Alan Gauld alan.gauld at btinternet.com
Mon Oct 10 02:21:47 CEST 2011


On 09/10/11 23:41, D. Guandalino wrote:
> Hi, in this class many methods share common code.
>
> class Foo(object):
>      def m1(self):
>          if self.foo:
>              pass # m1 do something
>          elif self.bar:
>              pass # m1 do something else
>          else:
>              pass # m1 do something different
>
>      def m2(self):
>          if self.foo:
>              pass # m2 do something
>          elif self.bar:
>              pass # m2 do something else
>          else:
>              pass # m2 do something different
>
>      # def m_n(self):
>          pass # same conditionals, different implementation
>
> I'm wondering if I have to duplicate the if/elif/else for each method.
> Does Python 2.7 provide a way to factor out this common structure?

Refactoring does not depend on the language so yes you can refactor this 
code in 2.7 as well as you can in any other language, but...
Should you?

We can't tell from the code you have posted because you have commented 
out the bits that matter - what the methods actually do.

Just because they have the same set of conditional tests does not mean 
you should refactor (except maybe at the class level - maybe you need to 
split the class into one with foo true and the other with bar true (and 
maybe a third for the else...) but never rush to create subclasses 
because that brings its own problems!). At the method level refactoring 
would depend on the content of the implementation sections. If the two 
methods did similar things within those code blocks then you might 
introduce new helper methods or parameterise the two methods into one. 
But without any idea of the implementation we really can't say.

For example, if m1 creates formatted output for reporting purposes and 
m2 saves the data into a database and m_n serialises the class for 
transmission over a network then its unlikely that there is much 
opportunity to refactor the methods. But it is likely that all three 
share the kind of structure you show above.

But if the three methods represent three different styles of report 
formatting then yes, we probably can do something.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list