How to reduce the DRY violation in this code

Marko Rauhamaa marko at pacujo.net
Tue Sep 27 12:21:19 EDT 2016


Steve D'Aprano <steve+python at pearwood.info>:

>     def __init__(self, bashful=10.0, doc=20.0, dopey=30.0, 
>                  grumpy=40, happy=50, sleepy=60, sneezy=70):
> [...]
>
>     @classmethod
>     def from_strings(cls, bashful='10.0', doc='20.0', dopey='30.0', 
>                      grumpy='40', happy='50', sleepy='60', sneezy='70'):
> [...]
>
> That's a pretty ugly DRY violation. Imagine that I change the default
> value for bashful from 10.0 to (let's say) 99. I have to touch the
> code in three places (to say nothing of unit tests):

    OMITTED = object()

    def __init__(self, bashful=OMITTED, doc=OMITTED, dopey=OMITTED,
                 grumpy=OMITTED, happy=OMITTED, sleepy=OMITTED,
                 sneezy=OMITTED):
        # the usual assign arguments to attributes dance...
        self.bashful = 10.0 if bashful is OMITTED else bashful
        self.doc = 20.0 if doc is OMITTED else doc
        [...]

    @classmethod
    def from_strings(cls, bashful=OMITTED, doc=OMITTED dopey=OMITTED,
                     grumpy=OMITTED, happy=OMITTED, sleepy=OMITTED,
                     sneezy=OMITTED):
        if bashful is not OMITTED:
            bashful = float(bashful)
        if doc is not OMITTED:
            doc = float(doc)
        [...]

Helper functions will make it look a bit less repetitious.


Marko



More information about the Python-list mailing list