Search code examples
c#open-closed-principle

Open / Closed Principle - How to deal with this Switch?


I have been looking into the open closed principle and it sounds good and so I wanted to exercise it's teachings. I looked at applying my new found knowledge to an existing project and have become a little stuck right away.

If a new UserType comes along (And this is Very likely), this will need to be changed, it is not yet closed to modification. How could one get round this?

From what I have read, it sounds like I should be implementing a factory here instead of applying the OCP?

Factory which breaks Open-closed principle

 private void BuildUserTree(User user)
    {
        switch (user.UserType)
        {
            case UserType.FreeLoader:
                BuildFreeLoaderTree();
                break;
            case UserType.Premium:
                BuildPremiumTree();
                break;
            case UserType.Unlimited:
                BuildUnlimitedTree();
                break;
            default:
                throw new Exception("No UserType set");

        }
    }

Thanks, Kohan


Solution

  • Like any 'principle' OCP is not a rule that you must obey on all occasions.

    We're told to 'Favour composition over inheritance', and yet patterns like decorator and composite openly promote inheritance.

    Similarly, we are told to 'Program to an interface, not an implemenation, and yet, at some point in our application we're going to have to instantiate a concrete object of some description.

    Your solution is a classic factory idiom (if not quite the full factory method or abstract factory pattern). This is what it is intended to do. Trying to apply OCP to it doesn't make sense.

    In fact, by creating this method, you may actually facilitate OCP in some other part of your code-base. Some other class or classes in your app could now obey OCP now you have separated the creation.