注釋
讀沒有注釋代碼的痛苦你我都體會過,好的注釋不僅能讓人輕松讀懂你的程序,還能提升代碼的逼格。注意注釋是為了讓別人看懂,而不是僅僅你自己。
文件注釋
每一個(gè)文件都必須寫文件注釋,文件注釋通常包含
- 文件所在模塊
- 作者信息
- 歷史版本信息
- 版權(quán)信息
- 文件包含的內(nèi)容,作用
一段良好文件注釋的栗子:
/*******************************************************************************
Copyright (C), 2011-2013, Andrew Min Chang
File name: AMCCommonLib.h
Author: Andrew Chang (Zhang Min)
E-mail: LaplaceZhang@126.com
Description:
This file provide some covenient tool in calling library tools. One can easily include
library headers he wants by declaring the corresponding macros.
I hope this file is not only a header, but also a useful Linux library note.
History:
2012-??-??: On about come date around middle of Year 2012, file created as "commonLib.h"
2012-08-20: Add shared memory library; add message queue.
2012-08-21: Add socket library (local)
2012-08-22: Add math library
2012-08-23: Add socket library (internet)
2012-08-24: Add daemon function
2012-10-10: Change file name as "AMCCommonLib.h"
2012-12-04: Add UDP support in AMC socket library
2013-01-07: Add basic data type such as "sint8_t"
2013-01-18: Add CFG_LIB_STR_NUM.
2013-01-22: Add CFG_LIB_TIMER.
2013-01-22: Remove CFG_LIB_DATA_TYPE because there is already AMCDataTypes.h
Copyright information:
This file was intended to be under GPL protocol. However, I may use this library
in my work as I am an employee. And my company may require me to keep it secret.
Therefore, this file is neither open source nor under GPL control.
********************************************************************************/
文件注釋的格式通常不作要求,能清晰易讀就可以了,但在整個(gè)工程中風(fēng)格要統(tǒng)一。
代碼注釋
好的代碼應(yīng)該是“自解釋”(self-documenting)的,但仍然需要詳細(xì)的注釋來說明參數(shù)的意義、返回值、功能以及可能的副作用。
方法、函數(shù)、類、協(xié)議、類別的定義都需要注釋,推薦采用Apple的標(biāo)準(zhǔn)注釋風(fēng)格,好處是可以在引用的地方alt+點(diǎn)擊自動彈出注釋,非常方便。
有很多可以自動生成注釋格式的插件,推薦使用VVDocumenter:
一些良好的注釋:
/**
* Create a new preconnector to replace the old one with given mac address.
* NOTICE: We DO NOT stop the old preconnector, so handle it by yourself.
*
* @param type Connect type the preconnector use.
* @param macAddress Preconnector's mac address.
*/
- (void)refreshConnectorWithConnectType:(IPCConnectType)type Mac:(NSString *)macAddress;
/**
* Stop current preconnecting when application is going to background.
*/
-(void)stopRunning;
/**
* Get the COPY of cloud device with a given mac address.
*
* @param macAddress Mac address of the device.
*
* @return Instance of IPCCloudDevice.
*/
-(IPCCloudDevice *)getCloudDeviceWithMac:(NSString *)macAddress;
// A delegate for NSApplication to handle notifications about app
// launch and shutdown. Owned by the main app controller.
@interface MyAppDelegate : NSObject {
...
}
@end
協(xié)議、委托的注釋要明確說明其被觸發(fā)的條件:
/** Delegate - Sent when failed to init connection, like p2p failed. */
-(void)initConnectionDidFailed:(IPCConnectHandler *)handler;
如果在注釋中要引用參數(shù)名或者方法函數(shù)名,使用||將參數(shù)或者方法括起來以避免歧義:
// Sometimes we need |count| to be less than zero.
// Remember to call |StringWithoutSpaces("foo bar baz")|
定義在頭文件里的接口方法、屬性必須要有注釋!
編碼風(fēng)格
每個(gè)人都有自己的編碼風(fēng)格,這里總結(jié)了一些比較好的Cocoa編程風(fēng)格和注意點(diǎn)。
不要使用new方法
盡管很多時(shí)候能用new代替alloc init方法,但這可能會導(dǎo)致調(diào)試內(nèi)存時(shí)出現(xiàn)不可預(yù)料的問題。Cocoa的規(guī)范就是使用alloc init方法,使用new會讓一些讀者困惑。
Public API要盡量簡潔
共有接口要設(shè)計(jì)的簡潔,滿足核心的功能需求就可以了。不要設(shè)計(jì)很少會被用到,但是參數(shù)極其復(fù)雜的API。如果要定義復(fù)雜的方法,使用類別或者類擴(kuò)展。
#import和#include
#import是Cocoa中常用的引用頭文件的方式,它能自動防止重復(fù)引用文件,什么時(shí)候使用#import,什么時(shí)候使用#include呢?
- 當(dāng)引用的是一個(gè)Objective-C或者Objective-C++的頭文件時(shí),使用
#import - 當(dāng)引用的是一個(gè)C或者C++的頭文件時(shí),使用
#include,這時(shí)必須要保證被引用的文件提供了保護(hù)域(#define guard)。
栗子:
#import <Cocoa/Cocoa.h>
#include <CoreFoundation/CoreFoundation.h>
#import "GTMFoo.h"
#include "base/basictypes.h"
為什么不全部使用#import呢?主要是為了保證代碼在不同平臺間共享時(shí)不出現(xiàn)問題。
引用框架的根頭文件
上面提到過,每一個(gè)框架都會有一個(gè)和框架同名的頭文件,它包含了框架內(nèi)接口的所有引用,在使用框架的時(shí)候,應(yīng)該直接引用這個(gè)根頭文件,而不是其它子模塊的頭文件,即使是你只用到了其中的一小部分,編譯器會自動完成優(yōu)化的。
//正確,引用根頭文件
#import <Foundation/Foundation.h>
//錯(cuò)誤,不要單獨(dú)引用框架內(nèi)的其它頭文件
#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
BOOL的使用
BOOL在Objective-C中被定義為signed char類型,這意味著一個(gè)BOOL類型的變量不僅僅可以表示YES(1)和NO(0)兩個(gè)值,所以永遠(yuǎn)不要將BOOL類型變量直接和YES比較:
//錯(cuò)誤,無法確定|great|的值是否是YES(1),不要將BOOL值直接與YES比較
BOOL great = [foo isGreat];
if (great == YES)
// ...be great!
//正確
BOOL great = [foo isGreat];
if (great)
// ...be great!
同樣的,也不要將其它類型的值作為BOOL來返回,這種情況下,BOOL變量只會取值的最后一個(gè)字節(jié)來賦值,這樣很可能會取到0(NO)。但是,一些邏輯操作符比如&&,||,!的返回是可以直接賦給BOOL的:
//錯(cuò)誤,不要將其它類型轉(zhuǎn)化為BOOL返回
- (BOOL)isBold {
return [self fontTraits] & NSFontBoldTrait;
}
- (BOOL)isValid {
return [self stringValue];
}
//正確
- (BOOL)isBold {
return ([self fontTraits] & NSFontBoldTrait) ? YES : NO;
}
//正確,邏輯操作符可以直接轉(zhuǎn)化為BOOL
- (BOOL)isValid {
return [self stringValue] != nil;
}
- (BOOL)isEnabled {
return [self isValid] && [self isBold];
}
另外BOOL類型可以和_Bool,bool相互轉(zhuǎn)化,但是不能和Boolean轉(zhuǎn)化。
在init和dealloc中不要用存取方法訪問實(shí)例變量
當(dāng)init``dealloc方法被執(zhí)行時(shí),類的運(yùn)行時(shí)環(huán)境不是處于正常狀態(tài)的,使用存取方法訪問變量可能會導(dǎo)致不可預(yù)料的結(jié)果,因此應(yīng)當(dāng)在這兩個(gè)方法內(nèi)直接訪問實(shí)例變量。
//正確,直接訪問實(shí)例變量
- (instancetype)init {
self = [super init];
if (self) {
_bar = [[NSMutableString alloc] init];
}
return self;
}
- (void)dealloc {
[_bar release];
[super dealloc];
}
//錯(cuò)誤,不要通過存取方法訪問
- (instancetype)init {
self = [super init];
if (self) {
self.bar = [NSMutableString string];
}
return self;
}
- (void)dealloc {
self.bar = nil;
[super dealloc];
}
按照定義的順序釋放資源
在類或者Controller的生命周期結(jié)束時(shí),往往需要做一些掃尾工作,比如釋放資源,停止線程等,這些掃尾工作的釋放順序應(yīng)當(dāng)與它們的初始化或者定義的順序保持一致。這樣做是為了方便調(diào)試時(shí)尋找錯(cuò)誤,也能防止遺漏。
保證NSString在賦值時(shí)被復(fù)制
NSString非常常用,在它被傳遞或者賦值時(shí)應(yīng)當(dāng)保證是以復(fù)制(copy)的方式進(jìn)行的,這樣可以防止在不知情的情況下String的值被其它對象修改。
- (void)setFoo:(NSString *)aFoo {
_foo = [aFoo copy];
}
使用NSNumber的語法糖
使用帶有@符號的語法糖來生成NSNumber對象能使代碼更簡潔:
NSNumber *fortyTwo = @42;
NSNumber *piOverTwo = @(M_PI / 2);
enum {
kMyEnum = 2;
};
NSNumber *myEnum = @(kMyEnum);
nil檢查
因?yàn)樵贠bjective-C中向nil對象發(fā)送命令是不會拋出異?;蛘邔?dǎo)致崩潰的,只是完全的“什么都不干”,所以,只在程序中使用nil來做邏輯上的檢查。
另外,不要使用諸如nil == Object或者Object == nil的形式來判斷。
//正確,直接判斷
if (!objc) {
...
}
//錯(cuò)誤,不要使用nil == Object的形式
if (nil == objc) {
...
}
點(diǎn)分語法的使用
不要用點(diǎn)分語法來調(diào)用方法,只用來訪問屬性。這樣是為了防止代碼可讀性問題。
//正確,使用點(diǎn)分語法訪問屬性
NSString *oldName = myObject.name;
myObject.name = @"Alice";
//錯(cuò)誤,不要用點(diǎn)分語法調(diào)用方法
NSArray *array = [NSArray arrayWithObject:@"hello"];
NSUInteger numberOfItems = array.count;
array.release;