Web制作、Web開発の歩き方

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

第9話:現場でのベストプラクティス

(最終更新日:2025.5.02)


分かりやすいコード

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

実際の現場では‥‥

これまで、命名、関数分割、コメント、テスト、変更容易性と、分かりやすいコードのための技術や原則を見てきた。 今回は、実際の開発現場でどう活用するか、どうやってチームで徹底するか、レビューでどう育てるかなど、実践的なベストプラクティスを紹介する。




1.実際のプロジェクトでの成功例

1.1 後から読んでも迷わないバッチ処理のコード
複雑なCSV処理ロジックを、小さな関数に分けて「読み込み」「検証」「変換」「登録」を明確に分離した。 関数名とログメッセージに同じ用語を使うことで、処理の流れとログが一致し、障害対応もスムーズになった。 下記にその例を示す。読み込ませるCSVデータは以下の通りである。

CSVデータ

これに対し、4つの分解した関数とそれをまとめた関数で処理する。

「読み込み」と「検証」

「変換」と「登録」、および順番に処理する関数

実際の処理結果が以下のようになる。最初のAliceのデータだけが登録され、他の2つはデータが不十分であることを注意されている。 4つの関数に分けて、名前も揃えたおかげで、各処理が非常に分かりやすい。そして、現在どの処理をしているのかが一目瞭然である。

処理結果

1.2 データ駆動設計による拡張性の確保
これは、前回紹介したデータ駆動設計の例である。 「割引ルール」などをJSONで定義し、コードではそれを読み込んで処理する。 これにより、仕様変更のたびにロジックを書き換えなくても済む設計になる。変えるのはJSONデータだけで良い。

2.チームでコードを統一するための実践的な工夫

チームでコードを統一するための実践的な工夫を以下に箇条書きで示す。 ツールを上手く活用することで、書き方を矯正させることが大事だ。

  • コーディング規約を軽量にまとめる:
      全員が読める形(例:README.md内、Notion、Confluence)に。
      必要最小限のルール(命名、インデント、コメント、ファイル構成など)に絞る。
  • ESLint / Prettier / clang-format などを導入:
      自動整形・自動検出ツールをプロジェクトに組み込むことで、人が指摘しなくても良くなる
  • フォルダ構成と命名に一貫性を持たせる:
      components/, services/, utils/ など役割ごとに明確に分類する。
      命名にプレフィックス・サフィックス(例:ButtonList, UserService)を共通化する。
  • Git フックでコミット前にフォーマット/リント:
      husky + lint-staged で強制整形・静的解析を自動化する。

3.レビュー時に気をつけるポイント

レビューで気をつけるのは「構造」と「意図の伝わりやすさ」である。 ポイントは以下の通りだ。 コーディングスタイルの指摘は極力ツールに任せて、レビューでは意図や設計レベルの指摘に集中できるようにしよう。 これにより、コード品質が高まるはずだ。

  • 関数の責務が明確か? : 1関数1目的になっているか
  • 命名が具体的か?: handleClick より submitOrder のような意図が伝わる名前か
  • 条件分岐が読みやすいか?: ネストが浅く、早期returnを活用しているか
  • コメントが必要な場所にあるか?: 「なぜそうしたのか」が書かれているか
4.「悪いコード」を書かないためのチェックリスト

悪いコードを書かないためのチェックリストは以下の通りになる。 今までの復習にはなるが、全て大事なことなので、漏れずにチェックしよう。

  • 命名は、処理の意図を明確に表しているか?
  • 関数の長さは長すぎないか(目安:20行以内)?
  • コメントで「なぜ?」を補足しているか?
  • if文が深すぎないか? 早期リターンで整理できないか?
  • Magic Number(謎の数値)が埋まっていないか?
  • ロジックが再利用可能な形になっているか?
  • 将来的に仕様変更に強い設計になっているか?
5.まとめ

今回は実際のプロジェクトでの成功例を中心に説明した。 そのほかの部分は、今までのまとめになる。このように、「分かりやすいコード」は チーム全員で作り上げる文化だ。 規約・命名・構成・レビューを通じて、少しずつ育てていくことが大事だ。 そして、ツールに任せられる部分は任せて、人間は設計と意図の共有に集中する。 この分かりやすさの先にあるのが、安全・高速・拡張しやすいソフトウェア開発になる。 つまり、リファクタリングし続けられるSDGsなプログラミングコードだ。これを目指していこう。

▼参考図書、サイト

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

How to Write Readable Code Episode 9: Best Practices in the Field (Last updated: 2025.5.02) Readable Code This article takes 5 minutes to read! (If the image is small, try rotating your phone sideways) In real-world projects… So far, we've looked at techniques and principles for writing readable code: naming, function decomposition, comments, testing, and ease of modification. In this episode, we’ll explore how to apply these concepts in real development environments—how to make them part of your team's workflow, how to reinforce them through reviews, and practical best practices from the field. [Contents] Success Stories from Real Projects Practical Tips to Standardize Code in a Team Key Points to Watch During Code Reviews Checklist to Avoid Writing “Bad Code” Summary 1. Success Stories from Real Projects 1.1 Easy-to-follow Batch Processing Code A complex CSV processing routine was broken down into small, focused functions: “load,” “validate,” “transform,” and “store.” By using the same terminology in both function names and log messages, the flow became easier to understand, and debugging was smoother. Below is an example. The input CSV data looks like this: CSV Data The processing is handled using four functions and one controller function. "Load" and "Validate" "Transform" and "Store", and the orchestrating function Here’s the output. Only the data for Alice gets registered; the others are flagged due to insufficient data. Thanks to the clear separation and consistent naming, the process is highly readable and easy to trace. Processing Output 1.2 Extensibility Through Data-Driven Design This was introduced in the previous article. Define things like discount rules in JSON and read them into your code. This means that future spec changes only require editing the JSON—not rewriting the logic. The result is a flexible and maintainable system. 2. Practical Tips to Standardize Code in a Team Below are some practical steps to help your team maintain consistent coding styles. By using tools effectively, you can enforce good practices automatically. Create a lightweight coding guideline: Make it easily accessible (e.g., in README.md, Notion, or Confluence). Focus only on essentials: naming, indentation, comments, folder structure, etc. Use ESLint / Prettier / clang-format: These tools automate formatting and linting, reducing the need for human intervention. Be consistent with folder structures and naming: Group by function, like components/, services/, utils/. Use prefixes/suffixes consistently (e.g., ButtonList, UserService). Use Git hooks to enforce formatting before commit: Tools like husky + lint-staged can automate this step. 3. Key Points to Watch During Code Reviews During code reviews, focus on “structure” and “clarity of intent.” Let tools handle style issues so humans can focus on the deeper design and purpose. This raises the overall code quality. Is each function’s responsibility clear? Stick to one purpose per function. Are names specific? Use intent-revealing names like submitOrder instead of handleClick. Are conditionals easy to read? Keep nesting shallow and use early returns. Are comments used where needed? Especially for explaining *why* something is done. 4. Checklist to Avoid Writing “Bad Code” Here's a checklist to help avoid writing problematic code. While these may be reviews of past points, each one is crucial. Are names clearly expressing the intent of the logic? Are functions short enough? (Guideline: under 20 lines) Are there comments explaining the “why” behind decisions? Are if-statements too deeply nested? Could you simplify with early returns? Are there any unexplained “magic numbers”? Is the logic reusable? Is the design future-proof and adaptable to spec changes? 5. Summary In this episode, we focused on real-world success cases. In essence, writing readable code is a team culture that grows over time. Through shared conventions, naming, structure, and reviews, the entire team contributes to maintainability. Automate what you can, and let developers focus on design and intent. The result is safer, faster, and more extensible software—a sustainable, continuously refactorable codebase. Let’s aim for that kind of SDG-friendly programming. ▼ References  “The Art of Readable Code” by Dustin Boswell and Trevor Foucher, translated by Masanori Kado, O'Reilly Japan