[Tutor] Optimize the code - removing the multiple IF conditions
Alan Gauld
alan.gauld at btinternet.com
Mon Dec 21 11:26:37 EST 2015
On 21/12/15 12:22, Sunil Tech wrote:
> class OptIf(object):
> """docstring for OptIf"""
This does not look like a useful class, it should probably
just be a function. Are you really going to have multiple
instances?
> 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
These should probably be an if/elif chain rather
than multiple if options (no risk of multiple
operations).
Without knowing more about what this is doing and what the
various parameters represent it's hard to be sure how best
to "optimise" it. Bear in mind too that optimising may mean
improving readability and the if statements may be more
readable and maintainable than any dictionary lookup
would be.
> def call_cm(cm, ad):
> def call_mm(mm, ax):
> def call_dm(dm, md):
As methods they should have a self parameter.
But these look suspiciously like the same method
with different names. The first parameter looks
like it might be a size value. (But I've no idea
what the second is supposed to be.)
Could this be a single function which incorporates
a scaling factor?
> med_map = {'CM': call_cm, 'MM': call_mm, 'DM': call_dm}
> but I am not able to pass the arguments.
They all take two arguments so you can pass those in
if the types are consistent.
result = med_map[unit](arg1,arg2)
Your problems start if the parameters are all
different types. If that's the case you are probably
better sticking with the if chain. Or maybe creating
three real classes that can be instantiated as needed
and use polymorphism to avoid the if statements.
But without any more detail on what's really going on
I am just making wild guesses.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list