「自分のコード、読みにくいと言われる」と悩んでいませんか?
現役WEBエンジニアとして、クリーンコードを心がけています。
この記事では、読みやすいコードの原則を解説します。
目次
なぜクリーンコードが重要か
読む時間 > 書く時間
- コードは書くより読む時間が長い
- 保守のしやすさがコストに影響
- 未来の自分も読む
命名
良い命名のルール
// NG: 意味が分からない
const d = new Date();
const arr = [];
const data = fetchData();
// OK: 意図が明確
const currentDate = new Date();
const userList = [];
const userProfile = fetchUserProfile();
命名規則
| 種類 | 規則 | 例 |
|---|---|---|
| 変数 | camelCase | userName |
| 定数 | UPPER_SNAKE | MAX_COUNT |
| クラス | PascalCase | UserService |
| 関数 | camelCase + 動詞 | getUserById |
関数
小さく、1つのことだけ
// NG: 1つの関数で複数のこと
function processUser(user) {
// バリデーション
if (!user.name) throw new Error('Name required');
// 保存
db.save(user);
// メール送信
sendEmail(user.email, 'Welcome!');
}
// OK: 分離
function validateUser(user) {
if (!user.name) throw new Error('Name required');
}
function saveUser(user) {
db.save(user);
}
function sendWelcomeEmail(email) {
sendEmail(email, 'Welcome!');
}
引数は少なく
// NG: 引数が多い
function createUser(name, email, age, address, phone) {}
// OK: オブジェクトで渡す
function createUser({ name, email, age, address, phone }) {}
コメント
良いコメント vs 悪いコメント
// NG: コードを説明(コードで分かる)
// ユーザー名を取得
const userName = user.name;
// OK: なぜそうするのかを説明
// キャッシュ有効期限切れ時は再取得が必要
if (Date.now() > cacheExpiry) {
data = fetchFreshData();
}
// OK: 複雑なロジックの意図
// 閏年の計算: 4で割り切れ、100で割り切れない、または400で割り切れる
コメントより良いコード
// NG: コメントで説明
// ユーザーが管理者かどうかチェック
if (user.role === 'admin') {}
// OK: 関数名で説明
if (isAdmin(user)) {}
構造
早期リターン
// NG: ネストが深い
function process(user) {
if (user) {
if (user.isActive) {
if (user.hasPermission) {
// 処理
}
}
}
}
// OK: 早期リターン
function process(user) {
if (!user) return;
if (!user.isActive) return;
if (!user.hasPermission) return;
// 処理
}
マジックナンバーを避ける
// NG
if (status === 1) {}
setTimeout(fn, 86400000);
// OK
const STATUS_ACTIVE = 1;
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
if (status === STATUS_ACTIVE) {}
setTimeout(fn, ONE_DAY_MS);
DRY原則
Don't Repeat Yourself
// NG: 重複
function formatUserName(user) {
return `${user.firstName} ${user.lastName}`;
}
function formatAdminName(admin) {
return `${admin.firstName} ${admin.lastName}`;
}
// OK: 共通化
function formatFullName(person) {
return `${person.firstName} ${person.lastName}`;
}
まとめ
クリーンコードのポイント:
- 命名を分かりやすく
- 関数は小さく1つのこと
- コメントより良いコード
- DRYで重複を避ける
