1. 使用函數(shù)式編程來提高可讀性
// 不好的代碼
NSMutableArray *numbers = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
[numbers addObject:@(i)];
}
NSMutableArray *filteredNumbers = [NSMutableArray array];
for (NSNumber *number in numbers) {
if (number.integerValue % 2 == 0) {
[filteredNumbers addObject:number];
}
}
// 好的代碼
NSArray *numbers = @[@0, @1, @2, @3, @4, @5, @6, @7, @8, @9];
NSArray *filteredNumbers = [numbers filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSNumber *number, NSDictionary *bindings) {
return number.integerValue % 2 == 0;
}]];
2. 使用常量和枚舉來避免魔法數(shù)字和字符串
// 不好的代碼
- (void)doSomethingWithStatus:(NSInteger)status {
if (status == 0) {
// do something
} else if (status == 1) {
// do something else
}
}
// 好的代碼
typedef NS_ENUM(NSInteger, Status) {
StatusNew = 0,
StatusInProgress,
StatusCompleted
};
- (void)doSomethingWithStatus:(Status)status {
if (status == StatusNew) {
// do something
} else if (status == StatusInProgress) {
// do something else
}
}
3. 避免使用過多的嵌套
// 不好的代碼
if (condition1) {
if (condition2) {
if (condition3) {
// do something
}
}
}
// 好的代碼
if (condition1 && condition2 && condition3) {
// do something
}
4. 使用宏來簡化代碼
// 不好的代碼
- (void)doSomethingWithArray:(NSArray *)array {
if (array && [array isKindOfClass:[NSArray class]] && array.count > 0) {
// do something
}
}
// 好的代碼
#define IsNonEmptyArray(array) (array && [array isKindOfClass:[NSArray class]] && array.count > 0)
- (void)doSomethingWithArray:(NSArray *)array {
if (IsNonEmptyArray(array)) {
// do something
}
}