If/then style question
Kev Dwyer
kevin.p.dwyer at gmail.com
Fri Dec 17 14:18:43 EST 2010
On Thu, 16 Dec 2010 21:49:07 +0000, John Gordon wrote:
> (This is mostly a style question, and perhaps one that has already been
> discussed elsewhere. If so, a pointer to that discussion will be
> appreciated!)
>
> When I started learning Python, I wrote a lot of methods that looked
> like this:
>
>
> def myMethod(self, arg1, arg2):
>
> if some_good_condition:
>
> if some_other_good_condition:
>
> if yet_another_good_condition:
>
> do_some_useful_stuff()
> exitCode = good1
>
> else:
> exitCode = bad3
>
> else:
> exitCode = bad2
>
> else:
> exitCode = bad1
>
> return exitCode
>
>
Another way to look at this is as question of object-oriented style, as you
are using a method in your example...
Arguably, rather than branching your code based on the arguments being
passed to your method, you can embody the required behaviour in subclasses
of your class, and at runtime just use an object that "does the right
thing". Of course, you end up writing the same branching in some factory
object instead, but at least it isn't cluttering up your business logic
any longer. Trying to write an OO-style program without using any if
statements in the business logic can be an interesting exercise, albeit
not a terribly realistic one.
Apologies if your choice of a method for your example was entirely
incidental to your question :)
Kev
More information about the Python-list
mailing list