-1

I need some help if it is a way to the below. Scenario is that I have an incoming order on the backend machines. And before I can process it I need to do some stuff with the order before depending on customer needs. Could be anything from cleaning some phone numbers or adding data to the order. Anyway, the job that needs to be done for each customer is rather unique so I dont want to discuss that now.

Now I more wonder if I can handle the below in a different way, because when the customers piles up, so does the else if, else if, else if and I start to dislike it. Should I make switch statement or is there a better eye friendlier way?

private void SenderSpecificLogic(Order order)
    {
        if (order.Customer.IsEqualIgnoreCase("abc"))
            AbcCustomerOrderManipulationLogic(order);

        else if (order.Customer.IsEqualIgnoreCase("bcd"))
            BcdCustomerCustomerLogic(order);
      
        else if (order.Customer.IsEqualIgnoreCase("cde"))
            CdeCustomerOrderManipulationLogic(order);            
       
        else if (order.Customer.IsEqualIgnoreCase("def"))
            DefCustomerOrderManipulationLogic(order);

        // and the list goes on an on...

    }
  • _and I start to dislike it_ can you explain why? There are multiple different solutions, which serves different needs. What is your? – Fabio Oct 29 '21 at 20:04
  • @Fabio When I an debugging my Tests I see that I get to each and every if statement, that´s the main reason. Tried the same with switch and it looks like it is compiled in runtime and depending on my input string it goes directly to my case. – A Dumbledore Oct 29 '21 at 21:55

2 Answers2

0

Your IsEqualIgnoreCase seems to compare strings. The closest path is to override ToString() in your order.Customer, then put it in a switch case

Nhan Nguyen
  • 106
  • 1
  • 8
0

You could declare a Dictionary with keys of type string that would store actions.

private void SenderSpecificLogic(Order order)
{
    // Actions could be defined outside SenderSpecificLogic.
    var Actions = new Dictionary<string, Action<Order>>
    {
        { "abc", AbcCustomerOrderManipulationLogic },
        { "def", DefCustomerOrderManipulationLogic },
        { "ghi", GhiCustomerOrderManipulationLogic },
        { "jkl", JklCustomerOrderManipulationLogic },
        { "mno", MnoCustomerOrderManipulationLogic },
        // Etc...
    }

    var Customer = order.Customer.ToLower();

    if(Actions.ContainsKey(Customer))
    {
        Actions[Customer](Order);
    }
}
Laurent Gabiot
  • 1,251
  • 9
  • 15
  • And you can construct a Dictionary that can ignore case. Take a look at my answer to https://stackoverflow.com/questions/2334134/how-to-make-c-sharp-switch-statement-use-ignorecase – Flydog57 Oct 29 '21 at 21:02