変数名・関数名の付け方ルールを日本一わかりやすく解説【2025年版】
プログラミングにおける変数や関数の命名には、いくつかの重要なルールと慣習があります。
目次
変数名・関数名の命名が重要な理由
プログラミングにおける変数名・関数名は、コードの看板のようなものです。お店の看板が「何のお店か」を表すように、良い名前は「何をする変数・関数か」を一目で伝えます。
悪い命名の例 😵
// 何をしているか全然わからない
let a = 25;
let b = "田中太郎";
function c(d, e) {
return d * e * 0.08;
}
良い命名の例 ✨
// 一目で理解できる
let userAge = 25;
let userName = "田中太郎";
function calculateTax(price, quantity) {
return price * quantity * 0.08;
}
基本的な命名規則
🎯 共通の基本ルール
- 英語を使う:日本語ローマ字は避ける
- 意味が伝わる名前:略語は最小限に
- 一貫性を保つ:同じプロジェクト内で統一
- 予約語を避ける:言語の特別な単語は使わない
📝 変数命名の基本パターン
キャメルケース(camelCase)
let firstName = "太郎";
let totalPrice = 1500;
let isUserLoggedIn = true;
スネークケース(snake_case)
first_name = "太郎"
total_price = 1500
is_user_logged_in = True
パスカルケース(PascalCase)
string FirstName = "太郎";
int TotalPrice = 1500;
bool IsUserLoggedIn = true;
言語別の命名規則
JavaScript の命名ルール
// 変数・関数:キャメルケース
let userName = "田中";
let itemCount = 5;
function getUserName() {
return userName;
}
function calculateTotal(price, tax) {
return price * (1 + tax);
}
// 定数:大文字スネークケース
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = "https://api.example.com";
// クラス:パスカルケース
class UserManager {
constructor(name) {
this.name = name;
}
}
Python の命名ルール
# 変数・関数:スネークケース
user_name = "田中"
item_count = 5
def get_user_name():
return user_name
def calculate_total(price, tax):
return price * (1 + tax)
# 定数:大文字スネークケース
MAX_RETRY_COUNT = 3
API_BASE_URL = "https://api.example.com"
# クラス:パスカルケース
class UserManager:
def __init__(self, name):
self.name = name
Java の命名ルール
// 変数・メソッド:キャメルケース
String userName = "田中";
int itemCount = 5;
public String getUserName() {
return userName;
}
public double calculateTotal(double price, double tax) {
return price * (1 + tax);
}
// 定数:大文字スネークケース
public static final int MAX_RETRY_COUNT = 3;
public static final String API_BASE_URL = "https://api.example.com";
// クラス:パスカルケース
public class UserManager {
private String name;
public UserManager(String name) {
this.name = name;
}
}
C# の命名ルール
// パブリック:パスカルケース
public string UserName = "田中";
public int ItemCount = 5;
public string GetUserName() {
return UserName;
}
// プライベート:キャメルケース
private string userName = "田中";
private int itemCount = 5;
// 定数:パスカルケース
public const int MaxRetryCount = 3;
public const string ApiBaseUrl = "https://api.example.com";
C++ の命名ルール
// 変数・関数:スネークケース(Google Style)
std::string user_name = "田中";
int item_count = 5;
std::string get_user_name() {
return user_name;
}
double calculate_total(double price, double tax) {
return price * (1 + tax);
}
// 定数:kで始まるキャメルケース
const int kMaxRetryCount = 3;
const std::string kApiBaseUrl = "https://api.example.com";
// クラス:パスカルケース
class UserManager {
private:
std::string name_; // プライベートメンバは末尾に_
public:
UserManager(const std::string& name) : name_(name) {}
};
変数命名のベストプラクティス
✅ 良い変数名の例
// 目的が明確
let userAge = 25;
let productPrice = 1500;
let isEmailVerified = true;
// 単位を含める
let delayTimeMs = 3000; // ミリ秒
let fileSizeBytes = 1024; // バイト
let temperatureCelsius = 36.5; // 摂氏
// 配列・リストは複数形
let userNames = ["田中", "佐藤", "鈴木"];
let orderItems = [item1, item2, item3];
// ブール値はis/has/canで始める
let isLoggedIn = true;
let hasPermission = false;
let canEdit = true;
❌ 避けるべき変数名
// 意味不明な略語
let u = "田中"; // userNameにする
let p = 1500; // priceにする
let flg = true; // isActiveにする
// 数字だけの名前
let data1 = "田中"; // firstNameにする
let info2 = 1500; // totalPriceにする
// 曖昧すぎる名前
let data = "何のデータ?";
let info = "何の情報?";
let temp = "何の一時的な値?";
関数命名のベストプラクティス
✅ 良い関数名の例
// 動詞で始める
function getUserName() { return userName; }
function setUserAge(age) { userAge = age; }
function deleteUser(userId) { /* 削除処理 */ }
// 処理内容を明確に
function calculateTax(price) { return price * 0.08; }
function validateEmail(email) { return email.includes("@"); }
function formatDate(date) { return date.toISOString(); }
// ブール値を返す関数
function isUserActive(user) { return user.status === "active"; }
function hasPermission(user, action) { return user.permissions.includes(action); }
function canUserEdit(user, document) { return user.role === "editor"; }
関数の種類別命名パターン
# 取得系:get/fetch
def get_user_by_id(user_id):
return database.find_user(user_id)
def fetch_latest_news():
return api.get_news()
# 設定系:set/update
def set_user_name(user_id, name):
user.name = name
def update_user_profile(user_id, profile):
database.update(user_id, profile)
# 作成系:create/make/generate
def create_new_user(name, email):
return User(name, email)
def generate_random_password():
return random_string(12)
# 削除系:delete/remove
def delete_user(user_id):
database.delete(user_id)
def remove_expired_sessions():
sessions.cleanup()
# 検証系:validate/check/verify
def validate_password(password):
return len(password) >= 8
def check_user_permissions(user, action):
return action in user.permissions
特殊な場面での命名ルール
ループ変数
// シンプルなループ:i, j, k
for (int i = 0; i < items.length; i++) {
System.out.println(items[i]);
}
// 意味のあるループ:わかりやすい名前
for (int userIndex = 0; userIndex < users.length; userIndex++) {
User currentUser = users[userIndex];
processUser(currentUser);
}
// 拡張for文:単数形
for (User user : users) {
processUser(user);
}
一時変数
# 計算の途中結果
base_price = get_base_price()
tax_amount = base_price * TAX_RATE
total_price = base_price + tax_amount
# ファイル処理
temp_filename = "processing_" + original_filename
processed_data = process_file(temp_filename)
イベントハンドラー
// on + 動詞 + 対象
function onButtonClick() { /* ボタンクリック時 */ }
function onUserLogin() { /* ユーザーログイン時 */ }
function onDataReceived() { /* データ受信時 */ }
// handle + 対象 + 動詞
function handleFormSubmit() { /* フォーム送信処理 */ }
function handleUserRegistration() { /* ユーザー登録処理 */ }
function handleErrorResponse() { /* エラーレスポンス処理 */ }
業界別・用途別の命名例
Web開発
// フロントエンド
let currentPage = 1;
let totalPages = 10;
let isLoading = false;
function showLoadingSpinner() { /* ローディング表示 */ }
function hideLoadingSpinner() { /* ローディング非表示 */ }
function navigateToPage(pageNumber) { /* ページ遷移 */ }
// API関連
let apiResponse = null;
let requestTimeout = 5000;
async function fetchUserData(userId) { /* ユーザーデータ取得 */ }
async function postUserUpdate(userData) { /* ユーザー更新 */ }
ゲーム開発
// ゲーム要素
int player_health = 100;
int player_score = 0;
bool is_game_over = false;
void move_player(int dx, int dy) { /* プレイヤー移動 */ }
void spawn_enemy(int x, int y) { /* 敵キャラ生成 */ }
bool check_collision(Player& player, Enemy& enemy) { /* 衝突判定 */ }
// ゲーム状態
enum GameState { MENU, PLAYING, PAUSED, GAME_OVER };
GameState current_state = MENU;
データ分析
# データ処理
raw_data = load_csv_file("data.csv")
cleaned_data = remove_null_values(raw_data)
normalized_data = normalize_values(cleaned_data)
# 統計情報
mean_value = calculate_mean(data)
standard_deviation = calculate_std(data)
correlation_coefficient = calculate_correlation(x_data, y_data)
def analyze_sales_trend(sales_data):
return trend_analysis(sales_data)
def generate_monthly_report(transaction_data):
return create_report(transaction_data)
モバイルアプリ
// UI関連
boolean isKeyboardVisible = false;
int screenWidth = getScreenWidth();
int screenHeight = getScreenHeight();
public void showKeyboard() { /* キーボード表示 */ }
public void hideKeyboard() { /* キーボード非表示 */ }
public void rotateScreen() { /* 画面回転 */ }
// センサー関連
float accelerometerX = 0.0f;
float accelerometerY = 0.0f;
boolean isLocationPermissionGranted = false;
public void requestLocationPermission() { /* 位置情報許可要求 */ }
public void startLocationTracking() { /* 位置情報追跡開始 */ }
よくある命名の間違いと改善例
間違い1:略語の乱用
// ❌ 悪い例
let usr = "田中";
let pwd = "password123";
let btn = document.getElementById("submit");
function calc(a, b) {
return a + b;
}
// ✅ 良い例
let currentUser = "田中";
let userPassword = "password123";
let submitButton = document.getElementById("submit");
function calculateSum(firstNumber, secondNumber) {
return firstNumber + secondNumber;
}
間違い2:日本語ローマ字
# ❌ 悪い例
namae = "田中"
nenrei = 25
def keisan(kakaku, zeiritsu):
return kakaku * zeiritsu
# ✅ 良い例
name = "田中"
age = 25
def calculate_tax(price, tax_rate):
return price * tax_rate
間違い3:曖昧すぎる名前
// ❌ 悪い例
String data = "ユーザー情報";
int number = 5;
boolean flag = true;
public void process() {
// 何を処理するの?
}
// ✅ 良い例
String userProfileData = "ユーザー情報";
int maxRetryAttempts = 5;
boolean isEmailVerified = true;
public void processUserRegistration() {
// ユーザー登録処理だとわかる
}
命名規則の統一管理
プロジェクト設定ファイルの例
// .eslintrc.js(JavaScript)
module.exports = {
rules: {
'camelcase': 'error', // キャメルケース強制
'no-underscore-dangle': 'error', // アンダースコア禁止
'func-names': 'error', // 関数名必須
}
};
// naming-convention.md(プロジェクトドキュメント)
/*
## 命名規則
### 変数
- キャメルケース:userName, itemCount
- ブール値:is/has/canで始める
### 関数
- 動詞で始める:getUserName, setUserAge
- ブール値を返す:isValid, hasPermission
### 定数
- 大文字スネークケース:MAX_RETRY_COUNT
*/
チーム開発での統一
# style_guide.py(チームスタイルガイド)
# ✅ 推奨パターン
def get_user_profile(user_id: int) -> dict:
"""ユーザープロフィールを取得する"""
pass
def calculate_shipping_cost(weight: float, distance: int) -> float:
"""送料を計算する"""
pass
# ❌ 避けるパターン
def getUserProfile(userId): # キャメルケースは使わない
pass
def calc_ship_cost(w, d): # 略語は使わない
pass
実践的な命名のコツ
🎯 名前を付ける時の思考プロセス
何をするか考える
// ❌ function doSomething() // ✅ function validateEmailFormat()誰が使うか考える
// ❌ let data // ✅ let customerOrderDataいつ使うか考える
// ❌ let time // ✅ let lastLoginTime
📚 命名に困った時の解決法
// 辞書を活用した命名例
let wordList = [
"create", "generate", "build", // 作成系
"get", "fetch", "retrieve", // 取得系
"update", "modify", "change", // 更新系
"delete", "remove", "clear", // 削除系
"validate", "check", "verify", // 検証系
"calculate", "compute", "process", // 計算系
"format", "convert", "transform" // 変換系
];
// 名前の長さのバランス
let shortButClear = "userId"; // 短く明確
let longButDescriptive = "userEmailVerificationStatus"; // 長いが説明的
// 文脈に応じた省略
function getUserById(id) { // 関数内ではidで十分
let userId = id; // より明確にしたい場合
return database.findUser(userId);
}
🔍 コードレビューでチェックすべき点
// レビューチェックリスト例
function reviewNamingConventions(code) {
// ✅ チェック項目
// 1. 変数名から用途がわかるか?
let userName = "太郎"; // ✅ 良い
let x = "太郎"; // ❌ 悪い
// 2. 関数名から動作がわかるか?
function calculateTotal() { /* */ } // ✅ 良い
function process() { /* */ } // ❌ 悪い
// 3. 一貫性があるか?
let userAge = 25; // キャメルケース
let userName = "太郎"; // キャメルケース(一貫性あり)
let user_email = "..."; // スネークケース(一貫性なし)
// 4. 略語が適切か?
let url = "https://..."; // ✅ 一般的な略語
let usr = "太郎"; // ❌ 不必要な略語
}
まとめ:良い命名のための黄金ルール
🏆 絶対に守るべき5つのルール
意味が伝わる名前を付ける
// ❌ let a = 25; // ✅ let userAge = 25;一貫性を保つ
// プロジェクト全体で同じ命名規則を使用 let userName, userAge, userEmail; // 統一されている適切な長さにする
// 短すぎず、長すぎず let userId = 123; // ちょうど良い let userIdentificationNumber = 123; // 長すぎる let id = 123; // 短すぎる(文脈による)言語の規則に従う
# Python:スネークケース user_name = "太郎"// JavaScript:キャメルケース let userName = "太郎";将来の自分が理解できる名前にする
// 6ヶ月後に見ても理解できる名前 function processUserPaymentTransaction() { // 処理内容が明確 }
🎯 命名で迷った時の判断基準
- チームメンバーが理解できるか?
- 3ヶ月後の自分が理解できるか?
- その名前で検索した時に見つけやすいか?
- 似たような機能と区別できるか?
良い命名は、コードの可読性を大幅に向上させ、バグの減少と開発効率の向上につながります。最初は時間がかかっても、丁寧に名前を付ける習慣を身につけることで、必ず良いプログラマーになれるでしょう!
■「らくらくPython塾」が切り開く「呪文コーディング」とは?
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座


