dimanche 20 janvier 2019

Simplify code to nullify too many if-else-statements

I was trying to design a rewarding system in Java which will reward users based on their current transaction information. I have to return different reward weights based on the certain criteria the transaction meets.This is the code sample for the class that assigns reward weights.

class RewardWeight {

    #condition 1
    public boolean is50thTransactionOfDay(Transaction t){
        //logic to find 50th Transaction
    }

    #condition 2
    public boolean is200thTransactionOfWeek(Transaction t){
        //logic to find 200th Transaction
    }


    #condition 3
    public boolean isTransactionAbove2000(Transaction t){
        //logic goes here
    }

    #condition 4
    public boolean isTransactionRepeated(Transaction t){
        //logic goes here
    }

    public int getRewardWeight(){
        // if condition 1 and condition 2 satisfied return 1
        // if condition 2 and condition 3 satisfied return 2
        // if condition 1 and condition 3 satisfied return 3
        // if condition 3 and condition 4 satisfied return 4
        // if condition 3 and condition 4 satisfied return 8
        // if condition 1 , 2 and 3 satisfied return 5
        // if condition 1 , 2 and 3,4 satisfied return 6
    }
}

Is there any way to return different weights as in

getRewardWeight()

method without having too many if else conditions. Also , it should be flexible to support any new feature as well.( such as a new reward criteria ).

Aucun commentaire:

Enregistrer un commentaire