LoginSignup
0
2

More than 3 years have passed since last update.

2変数、4分岐の if 文について

Posted at

変数 min_value, max_value が存在するとき、それぞれの条件で処理を変えたい

例えば…

min_value max_value 処理
null null なにもしない
null not null 上限より小さいことを検証
not null null 下限より大きいことを検証
not null not null 範囲内にあることを検証

普通はこんな感じ

Main.java

class Main {

    public static void main(String[] args) {

    }

    private static String hoge(int value, Integer min_value, Integer max_value) {
        if (min_value == null && max_value == null) {
            // なにもしない
            return "";
        }
        if (min_value == null) {
            // 上限チェック
            return "";
        }
        if (max_value == null) {
            // 下限チェック
            return "";
        }
        // 範囲チェック
        return "";
    }

}

  • パッと見、分かりづらい
  • 比較が一つの場合と、四つの場合が存在し、データによっては速度に違いが出る
  • 見た目が悪い

これをなんとか解消したい…

main.swift
func hoge(_ value: Int, _ min_value: Int?, _ max_value: Int?) -> String {
    // Optional が外れない
    switch(min_value != nil, max_value != nil) {
        case (true,  true):
            return ""   // 範囲チェック
        case (true,  false):
            return ""   // 上限チェック
        case (false, true): 
            return ""   // 下限チェック
        case (false, false):
            return ""   // 何もしない
    }
}

Pytyon3 の場合

main.py
def hoge(value, min_value, max_value):
    command = {
        (True, True): lambda: "",    # 範囲チェック
        (True, False): lambda: "",   # 下限チェック
        (False, True): lambda: "",   # 上限チェック
        (False, False): lambda: "",  # なにもしない
    }

    return command[(min_value is not None, max_value is not None)]()

もっと良い方法がありましたら、教えていただきたいです。

0
2
3

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
0
2