Sunday, February 13, 2011

Which method name fits in best with Objective-C/Cocoa conventions?

Here's a quicky question. Which method name makes the most sense for an Objective-C Cocoa application?

-(void) doSomethingWithAnimation:(BOOL)animated

or:

-(void) doSomething:(BOOL)animated

or even:

-(void) doSomethingAnimated:(BOOL)animated
  • -(void)doSomethingAnimated:(BOOL)animated seems most consistent with Apple's naming style. For reference, check the iPhone UIKit docs - UINavigationController's -popToRootViewControllerAnimated: method, for instance.

  • I think the Cocoa convention would give your examples the following semmantics (ignoring the BOOL type for the argument, obviously):

    -(void) doSomethingWithAnimation:(BOOL)animated
    

    would actually expect an Animation as the parameter (i.e. something that represents the animation.

    -(void) doSomething:(BOOL)animated
    

    would expect the Something to do.

    -(void) doSomethingAnimated:(BOOL)animated
    

    would, as Noah answered, do something with optional animation.

    From Barry Wark
  • Here's another option to consider: make two methods, -doSomething and -doSomethingWithAnimation.

    Then, if you want, you can have them both tail-call a third, private method, and give that method any name you want. :)

    Mike Akers : This won't work so well if the animated parm is coming from elsewhere consider this: - (void)doSomethingAnimated:(BOOL)anmimated { [self doSomethingElse:animated]; [otherView doAThirdThing:animated]; } becomes a PITA if you have 2 different methods.
  • write your comment clearly and tersely for example : //do Something with the Animation

    Then write your method name based on this comment, like below doSomethingwithAnimation:(BOOL)animated

    Objective-C and Cocoa are designed to read well, so if your method cannot be a clear narrative of your code, it might not be well named.

    From Iggy

0 comments:

Post a Comment