Direct Object Creation Problem – Who Cares about Pattern?

0
38

Design Pattern – Factory Method

Readers of the Topic – Developers, Architect

Coverage Topic

  • Direct object creation design
  • Direct object creation problem analysis
  • Connected to anti pattern
  • Concept of factory method
  • When, where and why to use
  • Benefit of factory method
  • Conditional factory method
  • Problem analysis of conditional factory method
  • Improvement of traditional factory method

Let’s Drill Down the Basic Concept

The Problem

Recently, I am working in a team. I have picked up a user-story. Technically, I need to create an object from a family of color objects on runtime according to the selected-colors.

Use-Case Diagram

Therefore, pick any color and create a color object from a family of color objects.

Direct Color-Object Creation Class Diagram

In the above code, a color-type is passing into the color-picker and it is creating the color-object. Finally it returns the color information.

Therefore, in the class diagram main focus points

  • ColorType: enum
  • ColorPicker: Direct color objects (red, green, blue) creator class.

Implementation according to Class Diagram

Program Class

Color-Picker Class Implementation

It was traditional implementation. The above code was functional and there was no compilation error. But team rejected the wonderful implementation. Why did they reject it?

Problem Analysis for Object Creation Directly

Unit Testing

Unit testing is impossible because of the tight-coupling dependency.

Explanation Why

First principle of unit testing states “Test the logic of the class only, nothing else”.

  • If you have dependencies in the class, then it should be loosely coupled; otherwise, object mocking is not possible.
  • If you call dependency directly inside the method of the class without object mocking, then this is not unit testing. This is something else, but not unit testing. Most of the time, this is the most common mistake.

Suppose, “GetColorByColorType()” is a candidate for the unit testing.

It has 3 direct tightly-coupled dependencies

GreenColor greenColor = new GreenColor();
RedColor redColor = new RedColor();
BlueColor blueColor = new BlueColor();

GetColorInformation is called by all of these 3 objects.  But we don’t want to test the logics of the GetColorInformation inside the GetColorByColorType method.

That’s why, we need object mocking. Object mocking of the interface/abstract class provides the dummy implementation of the GetColorInformation. That’s how, we don’t need to know the logic of the method of GetColorInformation.

Requirement before Making Mock

  • The class can’t be sealed
  • The method can’t be static; but if you need then use adapter pattern.
  • You can mock if Interfaces, Abstract methods or properties or Virtual Methods or properties on concreate classes.

Mock Framework

There are many object mock framework like Typemock Isolator, Rhino Mocks, Moq and NMock. You can use any one of them.

Code Duplication

The main problem for code duplication is that, if something goes wrong in the code, then you have to change everywhere. Somehow, if you forget to update the change, then it will break your code. Code duplication is an anti-pattern. So, avoid it.

Violation of Open-Closed Principle

Suppose, if I want to add another ultraviolet color, then I need to add one more if-else or switch case for the new extended color.

Open-Closed Principle

It states that “Modules and Methods should be open for extension but closed for modifications.

Therefore, additional if-else or switch-case statement is required for ultraviolet color. This modification is the violation of the open-closed principle. Because, new color extension is fine; but I shouldn’t touch the “ColorPicker” class.

What to Do: Extend new color, but don’t modify anything into ColorPicker class.

Self-Made Advantages and Immature Thoughts

  • Don’t need to be aware about the factory method pattern
  • Don’t need to be aware about the open-closed principle
  • Don’t need knowledge about the unit testing
  • Don’t need knowledge about tight coupling and loose coupling dependency.
  • Don’t need knowledge about the code duplication anti-pattern

Most Worst Reasons

  • Just because of the interview, I need to know about the factory method.
  • My code is still working well without factory method.
  • I don’t know when, where and why- it is really applicable.
  • I’m used to create object directly.
  • I just need to deliver the code as soon as possible.
  • I don’t need to write the unit testing.
  • I can test the methods without knowing the tight coupling and loose coupling. Therefore, if I write any test method, then it will be unit testing. Because, I don’t know the difference between the unit testing and the integration testing.

Solution: I need a solution to avoid these kinds of problems. Well, I’m dynamic; I have already learned how to fix this problem. Therefore, factory method is used to create an object from a family of classes.

Factory Method Pattern

Creates an instance of several derived classes

In the above class diagram, ColorFactory class is responsible to create the objects of the RedColor or GreenColor. RedColor and GreenColor are a family of classes.

Implementation of Factory Method Pattern

A parameter is passed into the GetInstance method in the ColorFactory class. It is called parameterized factory method. Therefore, an object is returned depending on the parameter passed into it.

For example, if I need the Green-Color object, then I should have to pass Green as a parameter. As a result, I will get back an object of GreenColor.

When, where and why to use

  • When I don’t know which object I must use at runtime. Dynamic way to create object at runtime.
  • I’m going to hide the object creation; so, I need it.
  • If you need to change any type, just change into factory class instead of changing it in multiple places.

Benefit

  • Unite Testing.
  • Removing code duplication.
  • Improving Readability.
  • Reusable
  • Extensibility

Solution with Conditional Factory Method Pattern

I have solved the problem using the factory method pattern.

Full Class Diagram according to Factory Method Pattern

Implementation according to Class Diagram

Factory Class:

ColorPicker Class

But again, the design is rejected. Why is the design rejected?

Improvement using Traditional Factory Method

Problem Analysis

If we want to add another color (say, Black-Color), then we need an if-else/switch-case statement into GetInstance method of factory class. This is the violation of open-closed principle. I shouldn’t modify the “Color Factory” class.

Factory Method Pattern without Conditional Statement

If-else or switch-case statement is killing me now. Well let’s try to get rid of this problem. There are several ways to solve the problem. I’m going to use reflection to solve the problem. Although, reflection is always expensive.

ColorFactory Class Implementation

  • LoadFrom: There is an assembly class in the System.Reflection namespace. I need it to load the assembly.

Assembly assembly = Assembly.LoadFrom(assemblyPath);

  • CreateInstance: I need another method of CreateInstance to create the object. I will get it into the Activator class of the System namespace.

Activator.CreateInstance(type);

Now I don’t need to modify the Color-Factory. So, now I’m not violating the open–closed principle.

ColorMapper Class Implementation

In the ColorMapper class, I have used a dictionary; because, there is a chance to make a mistake; if I use directly namespace in the code or I can forget the name of the namespace anytime.

The key of the dictionary is holding the Enum type of the color. The value of the key is the namespace of the implemented class of the IColor interface. 

The above the scenario describes where and why we need the factory method pattern. We have implemented factory method two different way using the traditional procedure and reflection. So, let’s go down in the factory method and start to think. Don’t let you down. Find out the limitation and wash it out from the design.

LEAVE A REPLY