switch
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Wed Dec 9 03:54:22 EST 2009
Steven D'Aprano a écrit :
> On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote:
(snip)
>> It is a principle of OO design that "an object should know what to do
>> itself." Rather running an object though a series of tests, it is
>> better to send the object a message, relying on polymorphism or duck-
>> typing, and deal with any exceptions thrown.
> But putting that aside, I find myself wondering how you would deal with
> the following switch-like series of tests.
>
>
> def print_grades(score):
> if not 0 <= score <= 100:
> raise ValueError("score must be between 0 and 100")
> if score < 50:
> print "You have failed."
> consider_suspension()
> elif score == 50:
> print "You have just passed by the skin of your teeth."
> elif score < 60:
> print "You have scored a D. You need to try harder."
> elif score < 70:
> print "You have scored a C."
> elif score < 80:
> print "You have scored a B. Well done."
> elif score < 100:
> print "Congratulations, you have scored an A."
> else:
> assert score == 100
> print "You have scored a PERFECT 100% SCORE!!!"
> if not evidence_of_cheating():
> call_newspapers()
Well, obviously such business rules must by no mean be hardcoded. You
really need a "rule engine", configurable by your domain experts thru a
DSL that we'll design specially for you. The rule engine will generate
an AbstractScoreFactory that will instanciate appropriate IScore
implementation objects that knows what to do.
You also need to decouple the output mechanism - what if you need to
output to a web page, an IPhone app, a RSS stream, an audio stream or
clay tablets ? To allow for maximum decoupling, the output mechanism
should be configurable thru a strict, well defined and universally
understood language - I mean XML, of course.
>
> Obviously that could, with a non-trivial amount of work, be turned into a
> dictionary dispatch,
Dictionnary dispatch ? C'mon, you must be joking ? An enterprise
application is not some Q&D cowboy script, you know ? You do have to
apply state of the art designs and patterns to do it properly
<g>
More information about the Python-list
mailing list