Michał Kowalczyk February 2016

The cleanest way to avoid multiple if-statements - object creation dependent on many params

I'm looking for the cleanest way to determine value without using multiple if-statements (or switch-case).

For example, I have following mapping table: enter image description here

As you see, I need to consider 5 variables before I will be able to determine the exact value.

Using if-statements leads to embedded ifs nightmare.

I have two solutions in mind:

Very dirty - map of maps of maps of maps, etc. :

Map<String, Map<String, Map<String,...>>> myMappings;

Involving a lot of code: Factory with sub-factories leading to final value - practically this is better for readability, but still this is if-statements encapsulated in classes.

What are your ideas?


Dmitry P. February 2016

You can solve this by introducing a composite key. Just add all your fields into it and override hashCode and equals properly. After that you can put and get necessary values from some kind of Map<CompositeKey, TaxCode>. As an illistration, not all fields are included and it's better to come up with a more meaningful name:

public class CompositeKey {

private final int companyNumber;
private final String sweepType;
private final int vatRate;

public CompositeKey(int companyNumber, String sweepType, int vatRate) {
    this.companyNumber = companyNumber;
    this.sweepType = sweepType;
    this.vatRate = vatRate;

public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    CompositeKey that = (CompositeKey) o;

    if (companyNumber != that.companyNumber) return false;
    if (vatRate != that.vatRate) return false;
    return Objects.equals(this.sweepType, that.sweepType);


public int hashCode() {
    int result = companyNumber;
    result = 31 * result + (sweepType != null ? sweepType.hashCode() : 0);
    result = 31 * result + vatRate;
    return result;

So then you can:

Map<CompositeKey, String> map = new HashMap<>();
map.put(new CompositeKey(200, "SLT", 0), "Value 1");
String value = map.get(new CompositeKey(200, "SLT", 0));

C.Champagne February 2016

Personally, I'd rather keep all those value in a table and only consider the final value I could obtain with a simple SQL query. You can chose other options but you should always keep those mapping in an external source (table, properties file...) you could modify if the requirements change.

Post Status

Asked in February 2016
Viewed 1,786 times
Voted 4
Answered 2 times


Leave an answer