user3761541
user3761541

Reputation: 147

Avoid multiple if/else conditions

using java 6

Have 70+ attributes to check as below. What is the best way to refactor the code as below?

    if(0 == compareField1) {            
        if(0 == compareField2) {
            if(0 == compareField3) {
                if(0 == compareField4) {
                    if(0 == compareField5) {
                        ......
                    } else {
                        return compareField5;
                    }
                } else {
                    return compareField4;
                }
            } else {
                return compareField3;
            }               
        } else {
            result = compareField2;
        }           
    } else {
        result = compareField1;
    }

Upvotes: 0

Views: 124

Answers (3)

Gergely M
Gergely M

Reputation: 733

Without giving an actual code sample.

You have said that:

Have 2 lists. looping thru those lists and comparing objects using comparator for all attributes to check if they are equal. Need to get only objects that are not in the list1.

I would convert both lists to a set (list1 > set1 and list2 > set2), HashSet if the order is irrelevant or TreeSet if you need the objects in order. Eg.

Set<whatevertype> set1 = new HashSet<whatevertype>(list1);

Then you can simply use removeAll() items of set1 from set2, like:

set2.removeAll(set1);

What left is set2', a truncated set of objects those aren't in set1.

Upvotes: 0

crizzis
crizzis

Reputation: 10716

Ummm... something like this?

for (int result : Arrays.asList(compareField1, compareField2, ..., compareField5)) {
    if (result != 0) return result;
}

Also, have a look at this

Upvotes: 1

m.antkowicz
m.antkowicz

Reputation: 13581

You can use an integer array where cell with index X will keep value for field numer X

final int fieldsCount = 60;
int[] fields = new int[fieldsCount ];
fields = loadFields(); // here you are populating fields

for(int i = 0; i < fieldsCount ; i++) if(fields[i] != 0) return fields[i];

// further logic (else)

Upvotes: 7

Related Questions