0

I have next code:

private static final List<String> VALUES =
  ImmutableList.of("15", "545", "856", "5", "4558"); 

public int getAmountOfUnits(String value, int duration) {

    if (VALUES.contains(value)) {

        if (duration >= 1 && duration <= 7) 
            return 0;

        if (duration >= 8 && duration <= 82) {
            return getUnitAmount(duration, 22, 15, 1);
        }

        if (duration >= 83 && duration <= 90) 
            return 7;

        if (duration >= 91) {
            return getUnitAmount(duration, 114, 24, 7);
        }
    }


    if (value.equalsIgnoreCase("3") && duration >= 0) {
        return getUnitAmount(duration, 15, 16, 1);
    }

    if (value.equalsIgnoreCase("4") && duration >= 0) {
        return getUnitAmount(duration, 59, 60, 0);
    }

    return 1;
}

List item

private int getUnitAmount(int input, int startRange, int increment, int startUnit) {
  while (startRange < input) {
    startUnit++;
    startRange += increment;
  }
  return startUnit;
}

How I can avoid this multile line if statments?

4
  • 3
    This Kind of questions is better asked at Code Review. Because it is about runnig code Commented Jul 30, 2018 at 11:50
  • 1
    I'd use guava's RangeMap here Commented Jul 30, 2018 at 11:51
  • Read pls this stackoverflow.com/questions/7721332/… Commented Jul 30, 2018 at 11:57
  • 1
    You can also simplify your getUnit method, it's simply a : startUnit + (input-startRange)/increment; Commented Jul 30, 2018 at 12:34

2 Answers 2

0

IMO there is really little that you can spare, as the different conditions involve different code anyway. You can reorganize the four tests on duration as a dichotomic search, but the gain is quite marginal...

Sign up to request clarification or add additional context in comments.

Comments

0

You will need those if conditions, however you can reduce some checks and produce a more compact code. Performance difference though is very negligible.

public int getAmountOfUnits(String value, int duration) {
    if(duration < 0) return 1; // here you can return whatever you intend to do.
    if (VALUES.contains(value)) {    
        if (duration <= 7){ 
            return 0;
        }else if (duration <= 82) {
            return getUnitAmount(duration, 22, 15, 1);
        }else if (duration <= 90){ 
            return 7;
        }else{
            return getUnitAmount(duration, 114, 24, 7);
        }
    }



        if(value.equals("3")){
            return getUnitAmount(duration, 15, 16, 1);
        }else if(value.equals("4")){
            return getUnitAmount(duration, 59, 60, 0);
        }


    return 1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.