Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to if else statement when using doubles

Based on the salaries, I need to assign a specific tax rate on my employee objects. The salary is defined by yearlySalary, which is a double, so I couldn't use a switch statement. I instead used if/else:

public int getSalaryRank() {
    if(yearlySalary <= 60000.00) {
        salaryRank = 1;
    } else if(yearlySalary > 60000.00 && yearlySalary <= 80000.00) {
        salaryRank = 2;
    } else if(yearlySalary > 80000.00 && yearlySalary <= 100000.00) {
        salaryRank = 3;
    } else if(yearlySalary > 100000.00 && yearlySalary <= 125000.00) {
        salaryRank = 4;
    } else {
        salaryRank = 5;
    } return salaryRank; }

I will assign tax rates later on based on the rank. Is there a better way to write this?

like image 621
Honinbo Shusaku Avatar asked May 23 '26 13:05

Honinbo Shusaku


2 Answers

Consider using a while loop through an List or array of (salary) limits.

like image 85
AlexWien Avatar answered May 26 '26 02:05

AlexWien


You can simplify it like this:

public int getSalaryRank() {
    int salaryRank;

    if(yearlySalary <= 60000.00) {
        return  1;
    } 

    if(yearlySalary <= 80000.00) {
        return 2;
    } 

    if(yearlySalary <= 100000.00) {
        return 3;
    } 

    if(yearlySalary <= 125000.00) {
       return 4;
    } 

    return 5

}

All the checks on the left side are unnecessary, because the statements are executed in order. Furthermore, you can remove the else statements and directly return the salaryrank . Also when you are dealing with money NEVER EVER use floating point numbers. Use BigDecimal instead

Edit: Taking into account @AlexWien's comment about the multiple exit points this might be a better solution:

public int getSalaryRank() {
        if(yearlySalary <= 60000.00) {
            salaryRank = 1;
        } else  if(yearlySalary <= 80000.00) {
            salaryRank = 2;
        } else if(yearlySalary <= 100000.00) {
            salaryRank = 3;
        } else if(yearlySalary <= 125000.00) {
           salaryRank = 4;
        } else {
           salaryRank = 5;
        }  

        return salaryRank;

    }
like image 21
Svetlin Zarev Avatar answered May 26 '26 04:05

Svetlin Zarev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!