次要规则
Redundant conditional operator (冗余的条件判断会造成一些错误,应该让它变得简洁)
void example(int a, int b, int c) {
bool b1 = a > b ? true : false; // true/false: bool b1 = a > b;
bool b2 = a > b ? false : true; // false/true: bool b2 = !(a > b);
int i1 = a > b ? 1 : 1; // same constant: int i1 = 1;
float f1 = a > b ? 1.0 : 1.00; // equally constant: float f1 = 1.0;
int i2 = a > b ? c : c; // same variable: int i2 = c;
}
redundant if statement (多余的if判断,可以省略)
bool example(int a, int b) {
if (a == b) // this if statement is redundant
{
return true;
} else {
return false;
} // the entire method can be simplified to return a == b;
}
Redundant local variable (冗余的局部变量,可以省略,直接return)
int example(int a) {
int b = a * 2;
return b; // variable b is returned immediately after its declaration,
}
Replace with boxed expression (可以迁移到object-c的新的表达方式)
void aMethod()
{
NSNumber *fortyTwo = [NSNumber numberWithInt:(43 - 1)];
// NSNumber *fortyTwo = @(43 - 1);
NSString *env = [NSString stringWithUTF8String:getenv("PATH")];
// NSString *env = @(getenv("PATH"));
}
Replace With Container Literal (替换arrayWithObjects和dictionaryWithObjects的简写形式)
Replace with number literal (替换numberWithInt和numberWithBOOL的简写形式)
Replace with object subscripting (替换objectAtIndex和objectForKey的简写形式)
Unnecessary else statement (如果if中已经带有return,则不需要写else语句)
bool example(int a) {
if (a == 1) // if (a == 1)
{ // {
cout << "a is 1."; // cout << "a is 1.";
return true; // return true;
} // }
else //
{ //
cout << "a is not 1." // cout << "a is not 1."
} //
}
Useless parentheses (检查无用的括号)
int example(int a) {
int y = (a + 1); // int y = a + 1;
if ((y > 0)) // if (y > 0)
{
return a;
}
return (0); // return 0;
}