Search for the range in which the number is

I have the following method:

private static final int OPEN_FOR_RAISE_RANGE = 35;
private static final int OPEN_FOR_CALL_RANGE = 25;

public void foo(double num){
    if(num <= OPEN_FOR_RAISE_RANGE){
        //do something
    }
    else if(num <= (OPEN_FOR_RAISE_RANGE + OPEN_FOR_CALL_RANGE)){
        //do something else 
    }
    //etc
}

which basically checks which range the number falls in and acts accordingly. I was wondering if there is a better / more efficient way to do this, besides many, if?

thank

+3
source share
4 answers

Discard NumberRange from commons-lang.

NumberRange range = new NumberRange(
  OPEN_FOR_RAISE_RANGE,
  OPEN_FOR_RAISE_RANGE + OPEN_FOR_CALL_RANGE
);

if(range.containsNumber(num)) {
  // do this
} else {
  // do something else
}
+3
source

This is as good as it sounds.

Note that the compiler will replace the calculation with a OPEN_FOR_RAISE_RANGE + OPEN_FOR_CALL_RANGEvalue 60at compile time so that you do not calculate it with every call.

+1
source

, , , if- :

if (...) {
   if (...) ...;
   else (...) { ... }
   if (...)
      if (...)
         if (...) ...;
         else (...) ...;
}

, .

+1

if/ifelse/ifelse/.../else, - :

public interface Choice {
    public boolean check(int value);
    public void action(int value);
}

public class BelowRange implements Choice {
    public static boolean check(int value) {
        return (value < 10);
    }
    public void action(int value) {
        // Do something;
    }
}

public class Range1 implements Choice {
    public boolean check(int value) {
        return (value > 10 && value < 50);
    }
    public void action(int value) {
        // Do something;
    }
}

...

:

List<Choice> choices = new ArrayList<Choice>();
choices.add(new BelowRange());
choices.add(new Range1());

...

for (Choice choice : choices) {
    if (choice.check(value)) {
        choice.action(value);
    }
}

, , , .

, , , if/else .

0

Source: https://habr.com/ru/post/1731569/


All Articles