0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

リーダブルコードを読んでの個人メモ(3)

0
Last updated at Posted at 2021-08-09

メモ

コメント
・コードを見れば理解できる内容はコメントには書かない。
・どんな処理をしているか、また今後起こり得そうなことをコメントに残す。
・コメントは短く簡潔に。
・質問されそうなことを書いておく。
・知らないと困る・ハマリそうなこと

制御フロー

・条件式

//肯定型をなるべく使う
//単純な条件を先に書く
//関心を引く・目立つ条件を先に書く

if(調査対象:変化する == 比較対象:あまり変化しない)

・三項演算子

//下記は短いから三項演算子で書いてもOK
time_str += (hour >= 12) ? "pm" : "am"

//三項演算子が長ければなるべくif文に変える
return exponent >= 0 ? mantissa * (1 << exponent) : mantissa / (1 << -exponent);

if(exponent >= 0){
        return mantissa * (1 << exponent);
    }else{
        return mantissa / (1 << -exponent); 
    }

・関数では早めにReturn

public void method() {
    if (よくあるケース/正常なケース) {
        // 通常の処理
    } else if (特殊なケース1) {
        // 特殊な処理1
    } else if (特殊なケース2) {
        // 特殊な処理2
    } else {
        // それ以外の処理
    }
}

修正後

public void method() {
    if (特殊なケース1) {
        // 特殊な処理1
        return;
    }

    if (特殊なケース2) {
        // 特殊な処理2
        return;
    }

    // 通常の処理
}

ネストを浅くする
ifやforをできる限り重ねないように書く

public int method(){
    if( current_user.id == 1 ){
        // 処理1
        if ( current_user.status == 1){
            // 処理2
        }
        // 処理3
        return 1;
    }else{
        return 2;
    }
}

修正後

public int method(){
    if( current_user.id != 1){
        return 2;
    }

    // 処理1
    if( current_user.status == 1){
        // 処理2
    }
    // 処理3
    return 1;
}

今更だけどめちゃめちゃ綺麗にまとめられている記事があった。。。神かよ。
https://qiita.com/falorse/items/7c0a368f88adf01d3fed
一部そのままパクったけど、自分がわかりやすいと思った記事をパクってメモに残すことは悪いことじゃないよね?笑

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?