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?
Consider using a while loop through an List or array of (salary) limits.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With