sonar規(guī)則-次要

次要規(guī)則

Redundant conditional operator (冗余的條件判斷會(huì)造成一些錯(cuò)誤,應(yīng)該讓它變得簡(jiǎn)潔)

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的新的表達(dá)方式)

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的簡(jiǎn)寫(xiě)形式)

Replace with number literal (替換numberWithInt和numberWithBOOL的簡(jiǎn)寫(xiě)形式)

Replace with object subscripting (替換objectAtIndex和objectForKey的簡(jiǎn)寫(xiě)形式)

Unnecessary else statement (如果if中已經(jīng)帶有return,則不需要寫(xiě)else語(yǔ)句)

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 (檢查無(wú)用的括號(hào))

int example(int a) {
        int y = (a + 1);    // int y = a + 1;
        if ((y > 0))        // if (y > 0)
        {
            return a;
        }
        return (0);         // return 0;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容