Re: is this badly written code?
Re: is this badly written code?
- Subject: Re: is this badly written code?
- From: "Michael Ash" <email@hidden>
- Date: Mon, 14 Apr 2008 23:24:51 -0400
On Mon, Apr 14, 2008 at 10:53 PM, Adam Gerson <email@hidden> wrote:
> In cocoa its very tempting to write a single line of code like:
> NSManagedObject *selectedTreeObject = [[[[[self delegate]
> mainWindowController] treeController] selectedObjects]
> objectAtIndex:0];
>
> or to flush it out in to individual lines:
>
> NSWindowController *mainWindow = [[self delegate] mainWindowController];
> NSTreeController *treeController = [mainWindow treeController];
> NSArray *selectedTreeObjects = [treeController selectedObjects];
> NSManagedObject *selectedTreeObject = [selectedTreeObjects objectAtIndex:0];
>
> I am looking for some guidance on best practices in a situation with a
> lot of nested calls like this. If ultimately the only value I care
> about is the final one, selectedTreeObject, whats the best way to go
> about getting it? I know "best" is a subjective word. Interested to
> hear all of your opinions.
For guidance on this, I recommend reading about the Law of Demeter:
http://c2.com/cgi/wiki?LawOfDemeter
As a "law" it's a bit too strict, IMO, but it's still good guidance.
You're talking to objects which are really far away from the one where
this code goes. Is that a good thing? You're embedding a lot of
knowledge about the structure of your application in this one spot,
and it's all going to break when you change it. I have no specific
advice on improving it, but there are some possibilities. Would it
make sense for your delegate to have a -selectedTreeObject which does
all of this work? Could there be other intermediate methods along this
chain which take care of their individual pieces? That would help to
split up the code and move the structural knowledge closer to where
it's applied.
Ignoring design issues, I vastly prefer the multiple line approach. I
don't find the single-line approach to be any easier to read or write,
and it's significantly harder to debug. Intermediate variables don't
cost anything except a bit of typing, and it's very nice to be able to
step through each call individually in the debugger.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden