1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

#0043(2024/02/11)ガード節

Last updated at Posted at 2025-02-11

ガード節(Guard Clause)とは?

ガード節は、関数やメソッドの冒頭で前提条件や入力の検証を行い、条件が満たされない場合に早期に処理を終了(または例外を発生)するためのテクニックです。
これにより、ネストが深くなるのを防ぎ、コードの可読性や保守性を向上させることができます。

ガード節のメリット

  • 早期リターン: 不適切な入力やエラー条件の場合、すぐに処理を中断できる。
  • コードの簡潔化: 不必要な入れ子の if-else 構造を避け、ロジックを明確にする。
  • 保守性向上: 条件ごとのエラーハンドリングが分離され、修正や拡張が容易になる。

Pythonでのガード節の例

以下は、入力値が適切でない場合にガード節を利用して早期にエラーを発生させる例です。

class DataProcessor:
    def __init__(self, data):
        # ガード節: dataがNoneの場合はエラーを発生させる
        if data is None:
            raise ValueError("data cannot be None")
        self.data = data

    def process(self):
        # ガード節: dataが空の場合は早期に処理を終了する
        if not self.data:
            return "No data to process"

        # 主要な処理ロジック
        result = [d * 2 for d in self.data]
        return result

# 使用例
try:
    processor = DataProcessor(None)
except ValueError as e:
    print(e)  # "data cannot be None"

processor = DataProcessor([])
print(processor.process())  # "No data to process"

processor = DataProcessor([1, 2, 3])
print(processor.process())  # [2, 4, 6]

TypeScriptでのガード節の例

TypeScriptでも同様に、コンストラクタやメソッドの最初にガード節を用いて入力値や状態をチェックします。

class DataProcessor {
  private data: number[];

  constructor(data: number[] | null) {
    // ガード節: dataがnullまたはundefinedの場合はエラーを投げる
    if (data === null || data === undefined) {
      throw new Error("data cannot be null or undefined");
    }
    this.data = data;
  }

  process(): number[] | string {
    // ガード節: dataが空の場合は早期に処理を終了する
    if (this.data.length === 0) {
      return "No data to process";
    }

    // 主要な処理ロジック
    const result = this.data.map(d => d * 2);
    return result;
  }
}

// 使用例
try {
  const processor1 = new DataProcessor(null);
} catch (error) {
  console.error(error.message); // "data cannot be null or undefined"
}

const processor2 = new DataProcessor([]);
console.log(processor2.process());  // "No data to process"

const processor3 = new DataProcessor([1, 2, 3]);
console.log(processor3.process());  // [2, 4, 6]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?