Rocky Singh
Rocky Singh

Reputation: 15430

Avoid too many if else in the filters

I want the following code to execute when the myString is having either of these values A, B, C or D. Right now I know that I have these 4 values but in near future I can have more values in this set. My Code:

var result = MyBlRepository.MyBLMethod(myString);

The simple way to have n number of if else loops but it can grow when I have more values. What is the best way to handle this? Which design pattern should be best for it?

EDIT: I don't want to keep the filters here. I don't want want to modify the code of this file.

Upvotes: 2

Views: 2840

Answers (4)

03Usr
03Usr

Reputation: 3435

You need the Strategy pattern, as explained here

It allows you to handle multiple if statements nicely. There is a short and easy tutorial showing how to handle multiple if statements in the above link.

Hope this helps.

Upvotes: 1

anouar.bagari
anouar.bagari

Reputation: 2104

My seggestion is to use Regex with an external config file, you can use app.cofing or a custom xml file

you store possible values like this expression = "^(A|B|C|D)$" then in your program :

var expression = ReadFromConfigFile(); 
var regex = new Regex(expression);
if(regex.IsMatch(myString))
 // do work

Upvotes: 0

O. R. Mapper
O. R. Mapper

Reputation: 20750

If you are just checking whether myString has one of a set of constant values, you can simply use switch:

bool result;
switch (myString) {
    case "A":
    case "B":
    case "C":
    case "D":
        result = true;
        break;
    default:
        result = false;
        break;
}

Note that this is a particularly long version of this code:

  • If you want to return a value based on the result of the comparison, you can just write return true;/return false; and omit the break; lines.
  • If you want to check the value and throw an exception if it is not among the desired set of values (though an enum type might be more appropriate in this case), you do not need the result variable and just throw the exception in the default case (and break; is not needed in the default case any more).

Otherwise (if any of the values is not yet determined at compile time), do it the way described in the other answers with List<string>/HashSet<string>.

Upvotes: 2

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

var list = new List<string>
{
  "A", 
  "B", 
  "C",
  "D"
 };
 bool exists = list.Contains(myString);

Upvotes: 1

Related Questions