LoginSignup
2
0

More than 3 years have passed since last update.

リファクタリング

Posted at

リファクタリング

実装した機能に影響を与えずに、ソースコードを読みやすい状態に改善すること

例A
const getYear = (year) => {
  if (year % 4 == 0){ 
    if (year % 100 == 0 && year % 400 != 0){
      console.log(`${year}年は閏年ではありません`);
    } else {
      console.log(`${year}年は閏年です`);
    }
  }else {
    console.log(`${year}年は閏年ではありません`);
  }
};
例B
const isLeapYear = (year) => {
  if (year % 400 == 0) {
      // 400で割り切れる年は閏年
      return true;
  }
  if (year % 100 == 0) {
      // 400で割り切れず、100で割り切れる年は平年
      return false;
  }
  if (year % 4 == 0) {
      // 400でも100でも割り切れず、4で割り切れる年は閏年
      return true;
  }

  // それ以外は平年
  return false;
};

if (isLeapYear(year)) {
  console.log(`${year}年は閏年です`);
} else {
  console.log(`${year}年は閏年ではありません`);
}

どちらの方が見やすいでしょうか?おそらく後者の方が見やすいと思います

変数名や関数名は具体的な命名をする必要があること。条件分岐を実装する際は、if文の中にif文を記述することを避けること。条件式はなるべく少ない記述で書くこと。コメントは残すべきものと残すべきでないものがあること

現場からは以上です!

2
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
2
0