uzla
uzla

Reputation: 525

Why avoiding conditional logic of Factory pattern is good?

One of Abstract factory pattern benefits is to avoid conditional logic of Factory pattern. However, such approach plods more classes, more code, more units tests and does not make code neither quicker nor readable, so as code class diagrams or documentation. So, what's the point in not having conditional logic on Factory pattern in such a case?

Upvotes: 0

Views: 835

Answers (2)

bcperth
bcperth

Reputation: 2291

In OOP there is a general "goal" to replace conditional logic (if-else,switch etc) with polymorphism. This usually involves creating an abstract class or interface and creating the range of objects you might need from there.

The benefit is that new derived classes can be added, without adding new code. The canonical example is different shape classes (square, circle, triangle etc) all derived from a base Shape class. Each new shape provides its own implementation of draw() for example.

The same applies in Abstract Factory whose purpose is to provide multiple "sets of objects" to a component or similar. The canonical (contrived) example is providing the correct set of UI objects for an application to work under Windows, Mac, X windows etc. The idea is to pass the correct factory object to the application and allow it to create the correct set of set of UI objects that it needs for the target environment.

Without this construct the application would need to be passed a parameter like "Windows" and the use the "dreaded" conditional logic to determine which objects to create using Factory Methods.

Most people will agree that if the number of "sets of objects" is small and fixed, then go ahead and use conditional logic and factory methods. But if that situation changes then you are faced with code changes.

If you use Abstract Factory to add a new "set of objects" you only have to create a new subclass of your Abstract Factory and not change your application code. This is more readable and more extendable, highly regarded attributes in large systems.

That is "the point in not having conditional logic on Factory pattern" but always judge in the context of your own business needs.

Upvotes: 2

Nghia Bui
Nghia Bui

Reputation: 3784

The benefit of Abstract Factory pattern is not to avoid conditional logic, but to make the code - that calls the factory - more abstract.

Imagine that code belongs to a very abstract layer in your software architecture (e.g., business domain layer). If you used Factory pattern, which involves a concrete Factory class that knows a lot of details (e.g., Database's APIs, 3rd party Framework/Library's APIs), then your business domain layer would depend on these details. This reduces the opportunity of reusing the layer since each time you reuse it, those details must be there. From the architectural point of view, you really don't want this dependency.

Upvotes: 1

Related Questions