mercredi 28 juin 2017

Avoiding ifs using patterns

I know that you can remove if blocks by using polymorphism with Strategy or Command patterns. However, let's say my code looks something like this:

ArgumentObject arg = getArg();

if (arg.getId() == "id2" || arg.getId() == "id3" || arg.getId() == "id4") {
    //do something
}
if (arg.getId() == "id2") {
    //do something
}
if (arg.getId() = "id2" || arg.getId() = "id3") {
    //do something
}
if (arg.getId().startsWith("id1") || arg.getId().startsWith("id4")) {
    //do something
}

I am not sure how can I use Strategy pattern here? If I create one Strategy to handle first if statement, then how can I proceed handling the second statement? The problem is that the ifs aren't mutually exclusive. Should I just move the relevant ifs to Strategy classes? Any pattern that would help me refactor this so its easier to test?

Aucun commentaire:

Enregistrer un commentaire