LoginSignup
44
30

More than 3 years have passed since last update.

Clean Codeの初めの一歩

Last updated at Posted at 2017-08-07
1 / 9

はじめに

"Clean Code"って何だろう?と興味を持った人達に捧ぐ言葉たちを纏めました。
具体的な例も記載しているので、Clean Codeを始めるための第一歩としてご活用ください。


クリーンコードとは

クリーンコードって何だろう?

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand. "
by Robert C. Martin

「コンピュータが理解できるコードを書くことは誰でもできる。優秀なプログラマーは、人間が理解できるコードを書く。」


何故クリーンコードが必要か?

"Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. ...[Therefore,] making it easy to read makes it easier to write."
by Robert C. Martin

「実際、コードを読む時間と書く時間の比率は10:1を優に上回る。私たちは新しいコードを書くための努力の一環として、絶えず既存のコードを読んでいる。(中略)それゆえに、読みやすくすることは、書きやすくすることに繋がる。」


ボーイスカウトから学ぶ

"the Boy Scout Rule tells us we should leave the code cleaner than we found it."
by Robert C. Martin

「ボーイスカウトルールは、コードを見つけた時よりもキレイにしてからその場を去るべきであることを教えてくれる。」

※ボーイスカウトルール・・・たとえ自分が来た時には既にキャンプ場が汚かったとしても、たとえ汚したのが自分ではなかったとしても、きれいにしてからその場を去る、というボーイスカウトの思想。


具体的なTips

コメントを書いたら負け

"Every time you write a comment, you should grimace and feel the failure of your ability of expression."
by Robert C. Martin

「コメントを書くたびに、自分の表現力の無さに顔をしかめなさい。」

UglyCode.java
// 運転免許を取得可能かどうかを判定
if((user.age >= 18) 
    && (user.leftVision >= 0.3 || user.rightVision >= 0.3)
    && (user.visionInBothEyes >= 0.7)
  ) {
    ...
  }
AwesomeCode.java
if (user.canObtainDriversLicense()) {
    ...
}

識別子は「正しく」名前を付ける

"A name in java, or any other language, is too long when a shorter name exists that equally conveys the behavior of the method."
by Anonymous(stackoverflow)

「javaまたは他の言語において、その振る舞いを等しく伝えることが可能な「より短い名前」が存在する場合、それは長すぎることを意味する。」

UglyCode.java
boolean doesShorterNameExistThatEquallyConveysTheBehaviorOfTheMethod‌​(String string);
AwesomeCode.java
boolean isTooLong(String string);

言いたいことを記述する

"Easily the most frustrating thing for another developer looking at your code is seeing a variable with a misleading name or, worse, named with a single letter."
by Code School blog

「別の開発者があなたのコードを見て一番イライラするのは、誤解を招くような名前のついた変数、さらには、一文字だけの変数を見ることだ。」

UglyCode.java
int check(int n, int max) {
    if(n < max) {
        return -1;
    }else {
        return 1;
    }
}
AwesomeCode.java
boolean hasTakenDamage(Player player) {
    return(player.currentHealth < player.maxHealth);
}

おわりに

"Keeping code consistent throughout the scope of a project will help reduce logical errors and improve readability. "
by Joe Hewitson(SmartShift)

プロジェクト全体にわたってコードの一貫性を保つことで、論理的なエラーが削減され、読みやすさが向上する。

いくら自分だけがClean Codeを実践出来ていても、他のメンバが実践出来ていなければ、それはさらなる混乱を招くに過ぎません。
ぜひプロジェクト全体でClean Codeを実践してみてください。

44
30
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
44
30