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?

【要約】リーダブルコード - 読みやすいコードを書くためのシンプルなテクニック

Posted at

プログラマーにとって、コードは書くだけではなく「読む」ことが必須です。しかし、自分や他の開発者が読みやすいコードを書くことは意外と難しいですよね。

そこで『リーダブルコード』は、読み手の負担を減らし、知的コストを低減させるための実用的なテクニックを紹介しています。

☞ より良いコードを書くための基本原則

  1. コードは動けばいいわけではない
    → 「読む人」が知的コストなしに理解できることが大事
  2. コードはコメントで説明するのではなく、そのもので明確にする
    → 意図が伝わるような名前を付け、過度なコメントは使わない
  3. 複雑さを出しても、隠してはいけない
    → 作者だけが理解できるコードはNG

☞ 読みやすいコードを書くポイント

1. いい名前をつける

  • 曖昧な名前を避ける
    NG: d, tmp, processData
    OK: elapsedTime, formattedUserName, calculateTotalPrice
  • 動詞を使う
    例: getUser(), fetchData(), updateStatus()
  • 同じ意味のものに同じ名前を使う
    (一緒に使われる名前を統一する)

2. 知的コストを低減する

  • ネストを深くしすぎない
    NG:
    if user.is_admin:
        if user.has_permission:
            if user.is_active:
                perform_task()
    
    OK:
    if is_authorized(user):
        perform_task()
    
  • コードを短くする
    (関数やクラスは一つのことだけするようにする)

3. 早めに脱出する

  • 重いネストを避けるために returnbreak を活用
    NG:
    def validate(user):
        if user:
            if user.is_active:
                return True
        return False
    
    OK:
    def validate(user):
        if not user:
            return False
        return user.is_active
    

☞ あとがき

『リーダブルコード』は、簡単な実装テクニックでも、いかに読み手に伝わりやすくするかを紹介しています。

実際のコードを見ながら、どんな要素があると読みやすいのかを検討してみましょう。


この記事が良かったら、スキ、コメントよろしくお願いします🙏

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?