Style question: Nicknames for deeply nested objects

Ian hobson42 at gmail.com
Sun Jan 30 15:44:10 EST 2011


On 30/01/2011 17:51, Gerald Britton wrote:
> Hi all,
>
> Today I was thinking about a problem I often encounter.  Say that I
> have (seems I often do!) a deeply nested object, by which I mean
> object within object with object, etc.
>
> For example:
>
>     x = some.deeply.nested.object.method(some.other.deeply.nested.object.value)
>
> Well, that's extreme but I've worked with code approaching that level
> of nested-ness.  Now, consider two scenarios:
>
> 1. You need to call this thing many times with different arguments, so
> you wind up with:
>
>     x = some.deeply.nested.object.method(some.other.deeply.nested.object.value1)
>     y = some.deeply.nested.object.method(some.other.deeply.nested.object.value2)
>     z = some.deeply.nested.object.method(some.other.deeply.nested.object.value3)
>
Neither.  You should tell. Don't ask if you can avoid it.

Compare...

     queen.getButter()

and
     queen.dairymaid.alderney.getButter()

see  http://www.timelessteacherstuff.com/readerstheater/KingsBreakfast.pdf

king doesn't care where or how the butter is brought.  Neither should 
your code!

What are you doing with value1, value2 and value3 when you have them 
anyway? Stuffing them 3 levels deep into something else?

Stop writing procedural code, and write object oriented code instead!

If you you make some tell  deeply.nested.object  about 
other.deeply.nested.object it can fetch its own values, but it might be 
better
to have some tell other.deeply.nested.object about deeply.nested.object 
to it can issue the correct commands.

Then you tell some to  do Somthing by writing

       some.takeMeaningfullAction()

and it all happens "under the covers".

Regards

Ian



More information about the Python-list mailing list