0
1

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.

読みやすいコードを意識するために

Last updated at Posted at 2020-04-30

読みやすいコードを意識する

気を抜くと冗長なコードになりがちになるので、意識づけのために
可読性の高くなるポイントについてまとめました。

##条件式を簡潔化

java
if (a == 1 && b == 2 && c == 3 && d == 4){
  System.out.println("test");
}

//if 文の条件式を折り返す

if (a == 1 && 
   b == 2 &&
   c == 3 &&
   d == 4){
  System.out.println("test");
}

//メソッドを作り可読性をあげる
if (output()){
  System.out.println("test");
}

private boolean isValidType(){
//処理
return true;
}

##ネストが深すぎる

java
//NG
if(a == 1){
    if(b == 2){
        if(c == 3){
            if(d == 4){
                if(e == 5){
                   System.out.println("test");
                }
            }
        }
    }
}

//OK
////同じくメソッドを作り可読性をあげる
if (isValidType()){
  System.out.println("test");
}

private boolean isValidType(){
//処理
return true;
}

##変数名やメソッド名が不適切

命名規則にそって宣言

####スネークケース

java
String user_name = "太郎"

####ローワーキャメルケース

java
String userName = "太郎"

####アッパーキャメルケース

java
String UserName = "太郎"

####チェインケース

java
String user-name = "太郎"

####codicを使って自動で変数名を作成

##スコープ有効範囲の意識

java
//NG
class Calculator {
  public static int num = 0;
  public static void alterNumber(int _num) {
    num = _num;
  }
  public static void main(String args[]) {
    alterNum(23);
  }
}

//OK
//アクセス制御子によりクラスの中だけでしか実行できない
class Calculator {
  private static int num = 0;
  private static void alterNumber(int _num) {
    num = _num;
  }
  public static void main(String args[]) {
    alterNum(23);
  }
}

##コードの統合化

java
//NG
public class StandAction extends BaseAction {
  public void Stand(Account account) {
    if(account.getFirstName() == null || account.getFirstName().length()== 0) {
      return;
    }
    if(account.getLastName() == null || account.getLastName().length() == 0) {
      return;
    }
  }
}


//OK
//メソッドを追加したので可読性の向上
public class Stand extends BaseAction {
  public void Stand(Account account){
    if(isEmpty(account.getFirstName())){
      return;
    }
    if(isEmpty(account.getLastName())) {
      return;
    }
  }
  public boolean isEmpty(String str) { 
    return str == null || str.length() == 0;
  }
}
0
1
3

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?