[JAVA] About 2-variable, 4-branch if statement

When variables min_value and max_value exist, I want to change the processing according to each condition

For example ...

min_value max_value processing
null null do nothing
null not null Verify that it is less than the upper limit
not null null Verify that it is greater than the lower limit
not null not null Verify that it is within range

Usually like this

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) {
            //do nothing
            return "";
        }
        if (min_value == null) {
            //Upper limit check
            return "";
        }
        if (max_value == null) {
            //Lower limit check
            return "";
        }
        //Range check
        return "";
    }

}

――It's hard to understand at first glance --There are cases where there is one comparison and cases where there are four comparisons, and the speed differs depending on the data. --It looks bad

I want to solve this somehow ...

main.swift


func hoge(_ value: Int, _ min_value: Int?, _ max_value: Int?) -> String {
    //Optional does not come off
    switch(min_value != nil, max_value != nil) {
        case (true,  true):
            return ""   //Range check
        case (true,  false):
            return ""   //Upper limit check
        case (false, true): 
            return ""   //Lower limit check
        case (false, false):
            return ""   //do nothing
    }
}

For Pytyon3

main.py


def hoge(value, min_value, max_value):
    command = {
        (True, True): lambda: "",    #Range check
        (True, False): lambda: "",   #Lower limit check
        (False, True): lambda: "",   #Upper limit check
        (False, False): lambda: "",  #do nothing
    }
    
    return command[(min_value is not None, max_value is not None)]()

If there is a better way, please let me know.

Recommended Posts

About 2-variable, 4-branch if statement
About variable scope. .. ..
Unfamiliar if statement
About variable of chainer
Python basic if statement
Julia quick note [05] if statement
Addition with Python if statement
[python] Correct usage of if statement
[Python] File operation using if statement
[Super basic] Compare Python, Java and JavaScript (variable, if statement, while statement, for statement)