[Tutor] Optimize the code - removing the multiple IF conditions

Steven D'Aprano steve at pearwood.info
Mon Dec 21 08:42:49 EST 2015


On Mon, Dec 21, 2015 at 05:52:29PM +0530, Sunil Tech wrote:

> class OptIf(object):
>     """docstring for OptIf"""
> 
>     def opt_me(self, ext):
>         if ext == 'CM':
>             rec = self.call_cm(cm, ad)
>         if ext == 'MM':
>             rec = self.call_mm(mm, ax)
>         if ext == 'DM':
>             rec = self.call_dm(dm, md)
>         return rec

As written above, it probably is not worth re-factoring that code, since 
not only are the method calls different, but so are the arguments. But 
let's do it anyway:

        if ext == 'CM':
            method = self.call_cm
            arguments = (cm, ad)
        if ext == 'MM':
            method = self.call_mm
            arguments = (mm, ax)
        if ext == 'DM':
            method = self.call_dm
            arguments = (dm, md)
        return method(*arguments)


Hardly worth it, is it? It's actually longer than the original.

Can we do better? Not really, but let's do it anyway:

       
        arguments = {'CM': (cm, ad), 
                     'MM': (mm, ax),
                     'DM': (dm, md)}
        method = getattr(self, "call_" + ext.lower())
        return method(*(arguments[ext]))

Shorter, but perhaps not more readable.

The following methods are all broken. They all need a "self" parameter.

 
>     def call_cm(cm, ad):
>         pass
>     def call_mm(mm, ax):
>         pass
>     def call_dm(dm, md):
>         pass



-- 
Steve


More information about the Tutor mailing list