Python Worst Practices

Chris Angelico rosuav at gmail.com
Wed Feb 25 19:26:40 EST 2015


On Thu, Feb 26, 2015 at 10:54 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> - Violating the Rule of Demeter: don't talk to the dog's leg, talk to
>   the dog. Or another way to put it: don't let the paper boy reach
>   into your pocket for money.

I'd call that code smell, rather than an automatic worst practice. Suppose this:

class Shelf:
    def __init__(self):
        self.items = [] # Empty shelf

bookshelf = Shelf()
bookshelf.items.append(book)

To enforce Demeter, you'd have to add a bunch of methods to the Shelf
whose sole purpose is to pass word along to the items list. Sure, it
makes some design sense to say "Add this book to the shelf" rather
than "Add this book to the items on the shelf", but all those lines of
code are potential bugs, and if you have to reimplement huge slabs of
functionality, that too is code smell. So there are times when it's
correct to reach into another object.

But the times to use two dots are much rarer than the times to use one
dot (the paper boy shouldn't reach into your pocket for money, but
ThinkGeek has your credit card number on file so you can order more
conveniently), and I can't think of any example off-hand where you
would want more than three dots.

ChrisA



More information about the Python-list mailing list