Question of replacement of if..else conditions with design pattern RRS feed

  • Question

  • User-1148431695 posted


    I am working on an application which contains code in lot of places where certain objects are created based on certain condition. The code is something like the following:

    if(affectedObject == "Customer")
         Customer c  = new Customer();
    else if(affectedObject == "Salesman")
         SalesMan s = new SalesMan();
    // or 
         case "Manager":
              // Do some processing.
         case "Employee":
              // Do another processing.


    I have gone through design patterns once but I am not able to figure out how I can use a pattern to replace my code.

    Can any one please help me with this? Any practical code sample would be of great help (code without refactoring and refactored code) so that I can understand it better.

    Thanks in advance.

    Wednesday, September 22, 2010 5:07 AM


  • User1444430368 posted

    The code you are using is a violation of the Open-Closed Principle (OCP):


    This means that when everytime there is a new object you need to modify your code especially for this new object. The Open-Closed Principle states that your code should be Open for extension but Closed for modification; in your case it is not.

    To refactor your code there are different ways, the most often used pattern to deal with this is Dependency Injection or DI:


    It is almost synonomous with the principle of Inversion of Control or IoC:


    The general idea behind IoC is giving away the responsability of creating objects during runtime to an IoC container.

    All this principles and patterns however will not all resolve your problem, because you are still using some magic strings in your code such as "Customer" and "SalesMan", ... these are coming from somewhere. If you can refactor them out and from your code and use Polymorphism, ...

    If you have any further questions please ask.


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 22, 2010 6:31 AM
  • User1444430368 posted

    If you are looking for a short term solution you can use one of overloads of Activator.CreateInstance() and pass the affectedObject:


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 22, 2010 7:07 AM

All replies