mercredi 3 juillet 2019

How to replace an if-based logic with depends on boolean values using a better strategy? [duplicate]

This question already has an answer here:

I have a class responsible for returning which profile some data belongs to. It does its work but I am not happy with the design I used: lots of ifs, based on true/false values, barely testable. I am sure there's a better and saner way to accomplish that (perhaps using strategy pattern), but I don't know how to implement it.

This is a very close example to what I currently have:

public SomeProfileEnum getProfile(int someUniqueId) {

    if (isProfileNumberOne(someUniqueId))
        return SomeProfileEnum.PROFILE_NUMBER_ONE;

    if (isProfileNumberTwo(someUniqueId)
        return SomeProfileEnum.PROFILE_NUMBER_ONE;

    [...] //a few other if clauses to check other profiles...

    return SomeProfileEnum.DEFAULT_PROFILE;
}

private boolean isProfileNumberOne(int someUniqueId) {
    //some logic to decide if that Id belongs to a profile number one...
    return true or false;
}

private boolean isProfileNumberTwo(int someUniqueId) {
    //some logic to decide if that Id belongs to a profile number two...
    return true or false;
}

[...] //other private methods for each possible profile

How can I improve it?

Aucun commentaire:

Enregistrer un commentaire