x=something, y=somethinelse and z=crud all likely to fail - how do i wrap them up

Steven D'Aprano steve at pearwood.info
Sun Jan 31 05:14:29 EST 2016


On Sun, 31 Jan 2016 08:40 pm, Chris Angelico wrote:

> On Sun, Jan 31, 2016 at 8:21 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>> Hmmm. Well, I've never used lxml, but the first obvious problem I see is
>> that your lines:
>>
>> description = li_item.find_class('vip')[0].text_content()
>>
>> link = li_item.find_class('vip')[0].get('href')
>>
>> price_dollar = li_item.find_class('lvprice prc')[0].xpath('span')[0].text
>>
>> bids = li_item.find_class('lvformat')[0].xpath('span')[0].text
>>
>>
>> look suspiciously like a violation of the Liskov Substitution Principle.
>> ("Talk to your dog, not to the dog's legs!") A long series of chained dot
>> accesses (or equivalent getitem, call, getitem, dot, etc) is a code-smell
>> suggesting that you are trying to control your dog's individual legs,
>> instead of just calling the dog.
> 
> (Isn't that the Law of Demeter, not LSP?)

D'oh!

I mean, yes, excellent, you have passed my test!

*wink*


> The principle of "one dot maximum" is fine when dots represent a form
> of ownership. The dog owns his legs; you own (or, have a relationship
> with) the dog. But in this case, the depth of subscripting is more 
> about the inherent depth of the document, and it's more of a data
> thing than a code one.

Yes. that's right. That's why I said it was a code smell, not necessarily
wrong. But you do make a good point -- the Law of Demeter is not
*necessarily* about the number of dots. But the number of dots is a good
hint that you're looking too deeply into an object.


> Imagine taking a large and complex JSON blob 
> and loading it into a Python structure with nested lists and dicts -
> it wouldn't violate software design principles to call up
> info["records"][3]["name"], even though that's three indirections in a
> row. Parsing HTML is even worse, as there's generally going to be
> numerous levels of structure that have no semantic meaning (they're
> there for layout) - so instead of three levels, you might easily have
> a dozen.

This might not be a Law of Demeter violation, but it's certain a violation
of "Flat Is Better Than Nested".



-- 
Steven




More information about the Python-list mailing list