Is there are good DRY fix for this painful design pattern?
MRAB
python at mrabarnett.plus.com
Mon Feb 26 18:43:53 EST 2018
On 2018-02-26 21:12, Rick Johnson wrote:
> On Monday, February 26, 2018 at 8:44:14 AM UTC-6, Steven D'Aprano wrote:
>> I have a class with a large number of parameters (about
>> ten) assigned in `__init__`. The class then has a number of
>> methods which accept *optional* arguments with the same
>> names as the constructor/initialiser parameters. If those
>> arguments are None, the defaults are taken from the
>> instance attributes.
>>
>> An example might be something like this:
>>
>> class Foo:
>> def __init__(self, bashful, doc, dopey, grumpy,
>> happy, sleepy, sneezy):
>> self.bashful = bashful # etc
>>
>> def spam(self, bashful=None, doc=None, dopey=None,
>> grumpy=None, happy=None, sleepy=None,
>> sneezy=None):
>> if bashful is None:
>> bashful = self.bashful
>> if doc is None:
>> doc = self.doc
>> if dopey is None:
>> dopey = self.dopey
>> if grumpy is None:
>> grumpy = self.grumpy
>> if happy is None:
>> happy = self.happy
>> if sleepy is None:
>> sleepy = self.sleepy
>> if sneezy is None:
>> sneezy = self.sneezy
>> # now do the real work...
>>
>> def eggs(self, bashful=None, # etc...
>> ):
>> if bashful is None:
>> bashful = self.bashful
>> # and so on
>
>
> Steven... even if this example code is absolutely atrocious
> (because it is!), and even *IF* i have a uneasy suspicion
> that this "inquiry" masks some dastardly malicious plan
> (because i do!), I must admit, I am happy to see that you
> are _finally_ embracing the OOP paradigm.
>
> For starters, I would suggest replacing those ugly if-
> clauses with some short-circuit or'd-logic. But obviously
> you need to run that "paragraph of arguments" through a
> single helper function, as the point of "DRY" is "Don't
> Repeat Yourself".
>
Before using or'd-logic, you need to know whether the value could be
falsey, e.g. 0.
> </pesos count="2">
>
More information about the Python-list
mailing list