A4 portrait - PET: Python Entre Todos - Python Argentina
A4 portrait - PET: Python Entre Todos - Python Argentina
A4 portrait - PET: Python Entre Todos - Python Argentina
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
First “non-dynamic” solution 26<br />
First “non-dynamic” solution<br />
To many one reading this, the first solution that will come to mind will be that each<br />
method (actionX…) must have within itself a big if, for each service. Something like:<br />
class Foo:<br />
def action1(self, service):<br />
if service == "A":<br />
#code for action 1 in service A<br />
elif service == "B":<br />
#code for action 1 in service B<br />
elif service == "C":<br />
#code for action 1 in service C<br />
elif service == "D":<br />
#code for action 1 in service D<br />
This will work, that I won’t deny. But… what don’t I like of this option? I don’t like:<br />
1. That if will be repeated in each of the actions, of which there are 5. When we add<br />
or modify services, I have to maintain the same if in all 5 methods “actionX”.<br />
2. The code quickly becomes unreadable when there’s a lot to do per action.<br />
3. It gives the sensation that we’re “mixing” apples and oranges, that this could be<br />
better organized.<br />
4. This ifs are two lines of code for each action and service, so with 5 actions and 4<br />
services, that’s 40 lines of code only in ifs, not including the code for the actions<br />
themselves. It’s 40 lines of code that don’t do what we want to do, that we need<br />
only to decide what to do.<br />
Enhancing the “non-dynamic” solution<br />
For the apples and oranges and organizational problem, more than one will have had<br />
the idea of something like this:<br />
class Foo:<br />
def action1(self, service):<br />
if service == "A":<br />
self.action1_in_A()<br />
elif service == "B":<br />
self.action1_in_B()<br />
elif service == "C":<br />
self.action1_in_C()<br />
elif service == "D":<br />
self.action1_in_D()<br />
def action1_in_A(self):<br />
#code of action 1 in service A<br />
def action1_in_B(self):<br />
#code of action 1 in service B<br />
def action1_in_C(self):<br />
#code of action 1 in service C<br />
def action1_in_D(self):<br />
#code of action 1 in service D<br />
I can’t deny it, the separation in many methods does help legibility and<br />
maintainability a tiny bit. Considering that part resolved, we forget about methods<br />
“actionX_in_Y”. But we still have this:<br />
<strong>PET</strong>: English Translation (Issue 1, August 2010) — http://revista.python.org.ar