【objc-zen-book】2.命名

这个小系列是从 "Zen and the Art of the Objective-C Craftsmanship"中 进行的摘抄,共分成6篇,大部分是讲代码风格及美化,偶尔看看也不错。

  • 原文GitHub地址:
    https://github.com/objc-zen/objc-zen-book
  • 中文版GitHub地址:
    https://github.com/oa414/objc-zen-book-cn

  • 尽量使用长的、描述性的方法和变量名。

    // 推荐
    UIButton *settingsButton;
    
    // 不推荐
    UIButton *setBut;
    
  • 常量应该以驼峰法命名,并以相关类名作为前缀。

    // 推荐
    static const NSTimeInterval ZOCSignInViewControllerFadeOutAnimationDuration = 0.4;
    
    // 不推荐
    static const NSTimeInterval fadeOutTime = 0.4;
    
  • 推荐使用常量来代替字符串字面值和数字。可以方便复用,快速修改。

  • 常量应该用static声明为静态常量,而不要用#define,除非它明确作为宏来使用。

    // 推荐
    static NSString * const ZOCCacheControllerDidClearCacheNotification = @"ZOCCacheControllerDidClearCacheNotification";
    
    static const CGFloat ZOCImageThumbnailHeight = 50.0f;
    
    // 不推荐
    #define CompanyName @"Apple Inc."
    #define magicNumber 42
    
  • 常量如果需要暴露给外部,那么要在头文件中以这样的形式:

    extern NSString *const ZOCCacheControllerDidClearCacheNotification;
    

    并在实现文件中为它赋值

  • 只有公有的常量才需要添加命名空间作为前缀。尽管实现文件中私有常量的命名可以遵循另外一种模式,你仍旧可以遵循这个规则。

  • 方法名与方法类型(-/+符号)间应加上一个空格。

    方法段间也应该以空格间隔。

    参数前应该有一个描述性的关键词。

  • 尽可能少用”and”这个词,它不应该用来阐明有多个参数。

    // 推荐
    - (void)setExampleText:(NSString *)text image:(UIImage *)image;
    - (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;
    - (id)viewWithTag:(NSInteger)tag;
    - (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;
    
    // 不推荐
    - (void)setT:(NSString *)text i:(UIImage *)image;
    - (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;
    - (id)taggedView:(NSInteger)tag;
    - (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
    - (instancetype)initWith:(int)width and:(int)height;  // Never do this.
    
  • 使用字面值来创建不可变的NSString,NSDictionary,NSArray和NSNumber对象。

    用这种方式,注意不要将nil放在NSArray和NSDictionary里,这样会导致崩溃。

    NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
    NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"};
    NSNumber *shouldUseLiterals = @YES;
    NSNumber *buildingZIPCode = @10018;
    

    不要这样:

    NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];
    NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil];
    NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];
    NSNumber *buildingZIPCode = [NSNumber numberWithInteger:10018];
    
  • 避免这样的方式创建可变数组:

    NSMutableArray *aMutableArray = [@[] mutableCopy];
    

    这样的方式,在效率和可读性上都存在问题。

    效率:一个不必要的不可变数组被创建后马上被废弃,并没有必要。

    可读性:可读性并不好。


所有文章
【objc-zen-book】1.条件语句&Case语句的注意
【objc-zen-book】2.命名
【objc-zen-book】3.类
【objc-zen-book】4.Category & NSNotification
【objc-zen-book】5.美化代码 & 代码组织
【objc-zen-book】6.Block & self的循环引用

你可能感兴趣的:(【objc-zen-book】2.命名)