Web制作、Web開発の歩き方

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

第6話:フレームワーク・静的解析による統一

(最終更新日:2025.4.17)


分かりやすいコード

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

書き方を強制しよう!

前回は「人間が意識して守る」スタイルのコーディング規約について紹介した。 しかし現場では「分かっていても書き方が人によってバラつく」ことがよくある。 そこで今回は、ツールや設計により、自然とコードが統一される仕組みを紹介する。



1.ツールを使った強制と静的解析ツールの活用例

「コーディング規約」は文書化するだけでは不十分だ。 開発ツールやCI(Continuous Integration)で自動チェック・整形することで初めて徹底される。 代表的な強制手段として、フォーマッター(自動整形)、リンター(静的解析)、 プルリクエスト、CI/CD パイプラインでの自動チェックを組み合わせることが重要だ。 下記にプログラミング言語とフォーマッター、リンターの例を示す。

言語ごとのフォーマッター、リンター

言語 フォーマッタ リンター
C++ clang-format clang-tidy, cpplint
JS/TS Prettier ESLint, TSLint(旧)
Python black flake8, pylint
Java google-java-format Checkstyle, SpotBugs

また、C++においてclang-formatを.clang-formatファイルで制御した例を示す。 下記の設定をyamlファイルで保存し、コマンドで「clang-format -i main.cpp」と実行することで、反映される。 統一されたインデント・スペース・改行・改行位置が強制される。

clang-formatの設定

2.フレームワークによるコード統一

現代のWebやアプリケーション開発では、フレームワークが“構造の型”を決めてくれるため、自然とコードが整う。 下記は、最近のWebアプリケーションフレームワークの例になる。

Webアプリケーションフレームワークの例

フレームワーク 特徴
React コンポーネントベースで関数単位に設計しやすい
Angular ファイル構成・DIパターン・ルーティングなど強制的に構造化
Django(Python) MVCが明確に分離されており、アプリ単位で統一できる

関数、変数、定数、クラスの書き方

要素 命名例
関数 getUserProfile()
変数 userName
定数 MAX_RETRY_COUNT
クラス UserManager

次に「コメントの書き方」を示す。 コメントは、//を使うか、/* */を使うかなどになる。 また、コメントタグを使うかなどである。

コメントの書き方

また、ファイル構成、ディレクトリ構成なども定義しておく。 どのディレクトリに何のファイルを置くかを決める。ディレクトリの名前で、何を置くディレクトリかが想像できると良い。 下記にdjangoの例を示す。フレームワークで大体指定されているが、下記のようになる。

ディレクトリ構成

3.関数型プログラミングの制約を活用

関数型プログラミングの考え方には「こう書けば統一される」スタイルが自然と備わっている。 下記がその特性と効果になる。副作用をなくす、データの影響範囲を小さくする、小さな関数に分割するといったことは特に重要だ。

関数型プログラミングの特徴

特性 効果
純粋関数 副作用をなくす(テストしやすくなる)
不変データ データ変更の影響範囲が限定される
関数合成 小さな関数に分割されやすくなる
高階関数の利用 共通処理を抽象化しやすい

下記にJavaScriptの例を示す。関数ごとに責務が明確で、構文も統一されているのが分かる。 「どう書くべきか」が言語・設計によって自然と制約されている=統一性を保てる状態になる。

関数型の書き方

4.リント・フォーマットツールの設定例

最後にリント・フォーマットツールの設定例を示す。 最初はeslintの設定だ。これは、文法やスタイルのルールが適用されているかをチェックするリンターだ。 例えば、ECMAスクリプトのバージョンを12で合わせる、使用しない変数を警告する('no-unused-vars': 'warn')などである。

ESLintによるチェックするルール

次にPrettierだ。こちらはコードを整えるフォーマットツールになる。 シングルクオートで囲む、セミコロンを必ずつける、インデントは2文字分の幅でということを指定している。

Prettierによるフォーマットの指定

これらのリント、フォーマットファイルを読むことで、ある程度自動でチェック、整形をしてくれる。

5.まとめ

今回はフレームワークや静的解析ツールを使ってコードを統一する方法を紹介した。 「フォーマッタ・リンターで形式を統一」(フォーマッタで修正) 「フレームワークやアーキテクチャで型を決める」(構造で強制) 「関数型によりコードの書き方を制約」(設計で強制) などの方法が有効である。色々試してみよう。

▼参考図書、サイト

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

How to Write Easy-to-Understand Code Episode 6: Standardization via Frameworks & Static Analysis (Last updated: 2025.4.17) Easy-to-understand code This article takes 5 minutes to read! (Turn your smartphone sideways if the image looks small) Enforce How Code is Written! In the last episode, we introduced coding standards that rely on individual discipline. However, in practice, code style often varies between developers, even when they "know" the rules. This time, we’ll look at how tools and architecture can naturally enforce code consistency. [Contents] Enforcement via Tools & Static Analysis Examples Code Unification Through Frameworks Using Functional Programming Constraints Linter & Formatter Configuration Examples Summary 1. Enforcement via Tools & Static Analysis Examples Merely documenting a coding standard is not enough. It must be enforced via tools and CI (Continuous Integration) to be effective. Key tools include formatters (auto-formatting), linters (static analysis), and PR/CI pipeline integrations. Below are examples of formatters and linters per language. Formatters and Linters by Language Language Formatter Linter C++ clang-format clang-tidy, cpplint JS/TS Prettier ESLint, TSLint (deprecated) Python black flake8, pylint Java google-java-format Checkstyle, SpotBugs Here's an example of using `.clang-format` in C++ to enforce code style. Save the following settings in a YAML file and run `clang-format -i main.cpp` to apply it. This enforces consistent indentation, spacing, and line breaks. clang-format Settings 2. Code Unification Through Frameworks In modern web or app development, frameworks define structural templates, which naturally unify code. Here are some common frameworks for web applications: Web Application Framework Examples Framework Features React Component-based; encourages function-level design Angular Enforces structure through DI, routing, file layout Django (Python) Clear MVC separation; enforces app-level consistency Naming Conventions for Functions, Variables, Constants, Classes Element Example Function getUserProfile() Variable userName Constant MAX_RETRY_COUNT Class UserManager Next is how to write comments—whether to use `//`, `/* */`, or tags. Here’s an example: How to Write Comments File and directory structure should also be defined. Decide what files go into which folders, with names that suggest their purpose. Here's a typical Django structure: Directory Structure Example 3. Using Functional Programming Constraints Functional programming inherently encourages consistency. Characteristics like pure functions and immutability reduce side effects and scope of data changes. Here are some core traits and their effects: Functional Programming Characteristics Characteristic Effect Pure Functions No side effects (easier testing) Immutable Data Limits scope of data changes Function Composition Encourages splitting into small functions Higher-order Functions Easier to abstract common logic Here’s a JavaScript example. Each function has a clear responsibility and consistent syntax. Design and language enforce uniformity naturally. Functional Style Example 4. Linter & Formatter Configuration Examples Let’s look at actual linter/formatter settings. First is ESLint, a linter that checks syntax and style rules. For example: setting ECMAScript version to 12, and warning about unused variables (`'no-unused-vars': 'warn'`). ESLint Rule Examples Next is Prettier, which auto-formats code. For instance, use single quotes, always include semicolons, and indent with 2 spaces. Prettier Formatting Rules These tools automatically check and fix code formats by reading their config files. 5. Summary This article showed how to unify code using frameworks and static analysis tools: - Format & lint to unify code style (e.g., auto-format) - Enforce structure with frameworks and architecture - Constrain code style via functional programming concepts Try experimenting with different approaches to see what works for your team! ▼ Reference Books & Websites  "Readable Code" by Dustin Boswell & Trevor Foucher, translated by Masanori Kado, O'Reilly Japan