はじめに
皆さんはコードのコメントにどのようなことを書いていますか?
コメントはコードを読む上で重要な要素ですが、書き方によってはコードを読みにくくしてしまうことがあります。
この記事では、コメントを書く際の注意点と、より良いコードのためのコメントの書き方について解説します。
当たり前のコメントを書かない
const name = "cat"; // 猫
こちら例で示してるのが、 cat
という変数に対して、 猫
というコメントをつけています。
これをわざわざコメントを残す必要がありません。
全てのプロパティのコメントを残す現場が稀にありますが、そういう場合以外は、コメントを残す必要はありません。
// 100回ループさせる
for (let i = 0; i 100; i++) {
...
}
// スコアが60以上
if (score >= 60) {
console.log('合格');
}
初学者で自分用のメモとして書くのは良いですが、他の人が読むコードにこのようなコメントは不要です。
もしこの 60 や 100 という数字の意味を表したい場合は、定数を使うべきです。
例えば、スコアの合格点を表す場合、以下のように定数を使うと良いでしょう。
const PASS_SCORE = 60;
if (score >= PASS_SCORE) {
console.log("合格");
}
悪いコメント
以下のようなコメントは、コードを読みにくくするだけでなく、誤解を招く可能性があります。
- 冗長なコメント
- コメントアウトされたコード
- なんの付加情報ももたないコメント
具体例を出すと以下のようなものですね。
こちらは、ユーザーの記事を取得するコードですが、コメントが冗長であったり、不要なものが含まれています。
import axios from "axios";
// ユーザーID
const userId = "tsubasa_K0814"; // ユーザー名
// 記事取得
async function fetchUserArticles() {
// ユーザーの記事を取得する
const res = await axios.get(`https://qiita.com/api/v2/users/${userId}/items`); // Qiitaのユーザー記事
// 結果
return res.data; // 記事
}
// 呼び出し
fetchUserArticles().then((data) => {
// ログ出力
console.log(data); // 表示
});
良いコメント
以下のようなコメントは、コードの意図や背景を理解するのに役立ちます。
- TODOコメント
- 使用上の注意
- 引数や戻り値の型情報
- APIの仕様や制約
- パフォーマンスなどに関わる理由
- 書き方がややこしくなるをのを避けられない場合(例:正規表現)
import axios from "axios";
/**
* Fetches a list of articles for the specified Qiita user.
* @param {string} userId - Qiita user ID
* @returns {Promise} List of articles
* @throws Throws an error if the API request fails
* @see https://qiita.com/api/v2/docs#get-apiv2usersuser_iditems
*/
async function fetchUserArticles(userId) {
// See: https://qiita.com/api/v2/docs#get-apiv2usersuser_iditems
const res = await axios.get(`https://qiita.com/api/v2/users/${userId}/items`);
return res.data;
}
(async () => {
try {
const userId = "tsubasa_K0814";
const articles = await fetchUserArticles(userId);
// Notify if no articles were found (operation note)
if (articles.length === 0) {
console.warn("No articles found. Please check the user ID and article visibility settings.");
} else {
// For development: output article titles only
articles.forEach((item, idx) => {
// The article title is stored in item.title (see API spec)
console.log(`${idx + 1}: ${item.title}`);
});
}
} catch (error) {
console.error("Failed to fetch articles from the Qiita API", error);
}
})();
おわりに
この記事では、コードのコメントについて、良い例と悪い例を示しながら解説しました。
コメントはコードを理解する上で重要な要素ですが、書き方によっては逆に読みにくくなることもあります。
良いコメントを書くためには、コードの意図や背景を理解し、必要な情報だけを提供することが大切です。
参照
Views: 0