Web制作、Web開発の歩き方

分かりやすいコードの書き方

第2話:分かりやすい命名規則

(最終更新日:2025.4.4)


分かりやすいコード

この記事は5分で読めます!
(絵が小さい場合はスマホを横に)

名前が最重要!

コードの中で最も多く目にするのは「名前」だ。 関数、変数、クラス、引数、定数……これらの名前が分かりにくいと、コードの意味は一気に不透明になる。 逆に、適切な名前をつけるだけで、コメントがなくても意図が自然と伝わるようになる。 今回は「分かりやすい命名」のために押さえておきたい原則、実際の良い/悪い例、そしてチームで統一するための指針を紹介する。




1.良い変数名・関数名・クラス名の特徴

良い名前には以下のような特徴がある。

  1. 役割がすぐに分かる
  2. 読み手が推測しなくても意味が明らか
  3. 誤解を招かない

つまり、名前は「誰が見ても迷わず意味がわかること」が最も重要だ。

2.命名の3つの原則

命名には3つの原則があります。「一貫性」「意図の明示」「適切な長さ」だ。 一貫性とは、同じ意味・用途には常に同じパターンの名前を使うことである。 下記に悪い例と良い例を示す。後者は同じルールで書かれていることが分かる。

一貫性(C++)

次に意図の明示である。最初の例は変数dが何を示しているか分からないが、 次の例では一年の日数を表していることが分かる。

一貫性(C++)

最後に適切な長さである。コープが短い変数は短くてOKだ。例えば、for文で使われる回数はiやjで構わない。 一方、スコープが広い、もしくは重要な意味を持つ変数は省略せずに書いた方が良い。正確に伝えよう。

3.禁止すべき命名パターン

ここでは使わない方が良い命名パターンを取り上げる。 以下のような名前は避けるべきだ。flagやtmp、data、calcあたりはつい使ってしまいそうだが、 consumptionTaxCalc(消費税の計算)などのように、具体的に命名するようにしよう。

名前 問題点
tmp, data, value 意味があいまい、何を指しているか分からない
flag1, flag2 何を意味するフラグか分からない
doIt(), handle() 何をする関数かが不明確
calc() 何を計算するか分からない(calcTotal, calcTax にすべき)
a, b, c 長いスコープでは意味を持たない

以下に悪い命名と、改善した良い命名を示す。 flagとisConnectedを比較すると、非常に具体的で、何を見ているかがハッキリしている。 また、calculateTotalPaymentは少し長いが、支払い総額を表していることが明らかだ。

目的 悪い例 良い例
ユーザーの年齢を保持する a userAge
支払い総額を返す関数 calc() calculateTotalPayment()
一時的なバッファ tmp tempBuffer
フラグ flag1 isConnected

4.命名規則を統一するためのガイドライン

命名を統一するには、チームやプロジェクトでルールを明文化しておくことが大切だ。 コーディング規約を作り、必ずその命名法に従わせるようにしよう。

    キャメルケース or スネークケースを統一
  • C++ → camelCase / PascalCase
  • 関数名は動詞から始める
  • getUserName(), sendMessage()
  • ブール値には is, has, can をプレフィックス
  • isActive, hasError, canRetry
  • 定数には全大文字 + アンダースコア
  • MAX_BUFFER_SIZE
5.まとめ

今回は分かりやすい命名規則について説明した。 名前は「機能」や「意図」を正しく伝えるための最重要要素であることが分かったと思う。 分かりやすい命名をするためには、一貫性、明確さ、長さのバランスを意識し、 曖昧な一般的な名前を避ける。命名規則はコーディング規約で明文化し、レビューやリントツールで徹底する。 このような工夫によって、分かりやすく、長く使われるコードになっていくはずだ。

▼参考図書、サイト

 「リーダブルコード」 Dustin Boswell、Trevor Foucher 著、角 征典 訳 オライリー

How to Write Understandable Code Episode 2: Clear Naming Conventions (Last Updated: 2025.4.4) Understandable Code This article takes only 5 minutes to read! (If the image looks small, try rotating your phone horizontally) Names are everything! The most frequently seen elements in code are names—of functions, variables, classes, parameters, and constants. If these names are unclear, the code becomes instantly harder to understand. On the other hand, appropriate naming can make code self-explanatory, even without comments. In this article, we’ll explore principles for clear naming, good and bad examples, and guidelines for unifying naming conventions across a team. [Contents] Characteristics of Good Names 3 Naming Principles Naming Patterns to Avoid Guidelines for Consistent Naming Summary 1. Characteristics of Good Variable, Function, and Class Names Good names have the following traits: Immediately convey their purpose Clearly understood without guessing Avoid misinterpretation In short, the most important thing is that *anyone* can instantly grasp the meaning of a name. 2. 3 Naming Principles There are three principles of naming: Consistency, Intent Revelation, and Appropriate Length. Consistency means using the same pattern for the same meaning or usage. See the bad and good examples below—the latter follows consistent rules. Consistency (C++) Next is intent revelation. The first example has a variable `d` that gives no clue to its meaning. In contrast, the next example clearly represents “number of days in a year.” Intent (C++) Lastly, use appropriate length. For short-lived loop counters, `i` or `j` is fine. But for broader-scope or important variables, use full descriptive names to avoid ambiguity. 3. Naming Patterns to Avoid Avoid names like the following. While tempting to use names like `flag`, `tmp`, `data`, or `calc`, you should instead choose descriptive names like `consumptionTaxCalc` to make the code meaningful. Name Issue tmp, data, value Too vague, unclear purpose flag1, flag2 Unclear what the flags represent doIt(), handle() Too generic, lacks specificity calc() Unclear what is being calculated (e.g., use calcTotal or calcTax) a, b, c Meaningless in wide scopes Below are bad and improved naming examples. Compare `flag` with `isConnected`—the latter is much clearer. `calculateTotalPayment` may be longer but explicitly conveys its purpose. Purpose Bad Example Good Example Hold user’s age a userAge Return total payment calc() calculateTotalPayment() Temporary buffer tmp tempBuffer Flag flag1 isConnected 4. Guidelines for Unifying Naming Conventions To maintain consistency, document naming rules at the team or project level. Create coding standards and require adherence. Unify CamelCase or snake_case C++ → camelCase / PascalCase Start function names with verbs getUserName(), sendMessage() Use prefixes for booleans: is, has, can isActive, hasError, canRetry Use ALL_CAPS with underscores for constants MAX_BUFFER_SIZE 5. Summary This article covered clear naming conventions. We’ve seen that names are the most essential factor in conveying the functionality and intent of code. Use consistent, descriptive, and appropriately long names. Avoid vague or generic names. Formalize naming rules in a coding standard and enforce them through reviews or linters. With these practices, your code will become clearer and more maintainable over time. ▼References  "Readable Code" by Dustin Boswell & Trevor Foucher, translated by Masanori Kado, published by O’Reilly Japan