Instantiation of a composite object with lots of validation rules - oop

I have an object that I would like to create. This object is composed of other objects that I don't want the client class to be responsible for creating. There are lots of validation rules that must pass before the object can be created.
So I would like to abstract away the creation of this complex object into a "factory" class. I have 2 questions really, the first is purely about semantics:-
What should I call the class which is creating my object? The factory method pattern and abstract factory pattern are both related to abstracting away creation of concrete classes of different types. However, I'm creating an object of a single type, so using the term factory might be confusing?
Is this an appropriate solution? Are there any patterns/examples of this being done?
Thanks in advance for any help/guidance.

You can use the term factory because we all use it in its broadest sense unless we use a more unique name like Factory Method design pattern or Abstract Factory design pattern.
Builder pattern is typically used if you have an object build process that should still be used if the same master steps should be used in creating different types of objects. But in your case you just have one type. So there's no need for a better solution since there's no special problem to solve. Just do the validation in the simplest form you can.

Related

Singleton toolbox vs factory method

Apparently, singletons are bad, and a factory method is recommended. I'm wondering if a singleton toolbox is any better than a singleton.
In my opinion, It's really weak to think that singletons are bad,factory methods are good.
Each of them has preferences. As consequence, I'm sure that there is misunderstanding here.
I know that wikipedia is not the best source. But check out the definition of them. The range of situations are not the same for these patterns.
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.
In class-based programming, the factory method pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the exact class of object that will be created. This is done by creating objects via calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

What problems does the Abstract Factory design pattern solve?

The intent of the Abstract Factory design pattern is to
"Define an interface for creating families of related or dependent objects
without specifying their concrete classes." [GoF]
This is a short statement of what the design pattern does (solution),
but it isn't clear what particular design problems it solves.
I would define the
following design, refactoring, and test problems,
but I am not sure whether this list is complete.
Design Problems
Creating Objects and Object Families
How can a system support creating different families of objects
so that which family to create can be selected and changed dynamically?
How can a system be configured with a family of objects?
And how can the whole family of objects be exchanged dynamically?
How can the way objects are created (which classes are instantiated)
be changed independently?
How can a system be independent of how its objects are created?
Creating Consistent Object Families
How can be ensured that a system creates objects from only one of different
families at a time?
Refactoring Problems
Distributed Creation Code
How can instantiating concrete classes throughout an application be refactored?
How can creation code that is distributed across many classes be centralized?
Testing Problems
Unit Tests
How can creating objects and object families be designd
so that object creation can be mocked easily for unit testing?
Keeping the long story short - if in the future a new group of objects is introduced in your current OO design, a new factory will be derived from AbstractFactory, encapsulating creation of all concrete objects related to that group. It’s that simple.
As addition is also important to say that
“This pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses".
In short we need a class here which will do all the common tasks and expose a virtual or abstract function.
So creating AbstractFactory will encapsulate common functionalities with an additional overridable (virtual or abstract) method and then recreate our SubFactoryA and SubFactoryB. By doing so - you'll achieve common architecture, propagate minimum/default set of practices, standards etc. Here is a very good article about all this.

Creating objects with the same arguments across the system

I have an object that performs a very specific task. To be created, this object needs some parameters. I create a new instance in some parts of my system. But there is the problem. What if a parameter or argument must be changed in the future? I will need to change it everywhere. Then I thought: "Well, maybe I can encapsulate its creation in a class, if some argument changes, I will need to change it just in a single place!".
It does make perfect sense to me. The real question is, is this "wrapper" object a factory? Its responsibility would be "Create a new object with specific parameters and return it". Consumers would just use this object ...
You a refactoring code to avoid duplication, that is itself likely to improve your overall maintainability.
If this piece of refactored code is creating objects then, yes, it is a factory. It really doesn't matter what you call it - is your code better structured now you have it? Then do it!
However, given that it is a factory study the classic design patterns concerning factories and understand what leads people to use more sophisticate forms of this pattern. Decide whether you have any of the forces that lead them to use "clever" factories.
The problem you describe is that all clients of your class have to change when the constructor parameters of that class change. Introducing a factory could help prevent recompilation of the clients. But does this really solve the problem? If you modify the class to be constructed with another parameter that parameter has to be determined somewhere, probably in the context of the clients that initiate the construction. How should the factory class know? Would the clients have to pass any context information to the factory?
What parameters are needed to construct the object? Do the clients provide them or could the objects be created beforehand and then injected into the clients as you would inject the factory (as I understand your question the latter seems to be the case)? Consider using a DI framework. This oftentimes makes factories obsolete.
Why are you afraid that your class is likely to be changed? Could it be that your class just does too much? Mind the Single Responsibility Principle. In your case also the Open/Closed Principle is an interesting study.
As I understand a factory does not necessarily address the problem you describe. Factories take the responsibility of creating objects away from clients so the client doesn't have to know the concrete type of the object. Just preventing that signatures remain stable can also be done by wrapping parameters in a single object. This is also a well known refactoring pattern. But it also doesn't solve the question where the new parameters come from.

When to use the abstract factory pattern?

I'm trying to succinctly describe when to use a factory, for both myself and my team. I ran across the following related questions, which helped somewhat:
When to use factory patterns?
(useful pdf link is broken)
How do you create your Factories?
(more 'how' rather than 'when')
What is your threshold to use factory instead of a constructor to create an object?
(some general answers)
Factory Pattern. When to use factory methods?
(more about factory methods than factory classes)
When to use Factory method pattern?
(again more about factory methods)
Based on these links, and a bunch of other sources (listed at the bottom), I've come up with the following:
When to use the abstract factory pattern:
when you use an interface var or the 'new' operator
e.g. User user = new ConcreteUserImpl();
and the code you are writing should be testable / extensible at some point
Explanation:
interfaces by their very nature imply multiple implementations (good for unit testing)
interface vars imply OCP- and LSP-compliant code (support sub-classing)
use of the 'new' operator breaks OCP/DI, because highly-coupled classes are hard to test or change
"Do I create a factory for every object type? That seems excessive."
no, you can have one (or a few) factories that produce a lot of (usually related) object types
e.g. appFactory.createUser(); appFactory.createCatalog(); etc.
When NOT to use a factory:
the new object is very simple and unlikely to be sub-classed
e.g. List list = new ArrayList();
the new object is not interesting to test
has no dependencies
performs no relevant or long-running work
e.g. Logger log = new SimpleLogger();
References:
http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html
http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/
http://en.wikipedia.org/wiki/Dependency_Injection
http://en.wikipedia.org/wiki/Open_Closed_Principle
http://en.wikipedia.org/wiki/Liskov_substitution_principle
My question is: is my summary accurate, and does it make sense? Is there anything I've overlooked?
Thanks in advance.
I'd also say don't use a factory when you have a particular implementation that you want. To continue the List example, I know that I want an ArrayList because I'm doing random access. I don't want to rely on a factory getting this right when I can do it myself.
Conversely, when I don't want to know about the concrete subclass then I can use a factory and let it worry about which object to actually instantiate.
I guess I'd suggest that you add a bullet to the "when to use the abstract factory pattern" that says "and you don't really care which concrete subclass you get", and the converse to "when not to use a factory".
EDIT: Be careful to avoid the general-purpose tool-building factory factory factory.
In general, use it when you want to be able to switch of implementation by external configuration.
JDBC and JAXP are excellent examples. For more examples, check this answer.
Abstract Factory pattern provides with a way to encapsulate concrete factories that share some commonality with each other, meaning they implement same interface/abstract class.
You need to use factory pattern whenever you want to control the initialization of your objects, instead of giving the control to the consumer.

How do you fight growing parameter list in class hierarchy?

I have a strong feeling that I do not know what pattern or particular language technique use in this situation.
So, the question itself is how to manage the growing parameter list in class hierarchy in language that has OOP support? I mean if for root class in the hierarchy you have, let's say 3 or 4 parameters, then in it's derived class you need to call base constructor and pass additional parameters for derived part of the object, and so forth... Parameter lists become enormous even if you have depth of inheritance more than two.
I`m pretty sure that many of SOwers faced this problem. And I am interested in ways how to solve it. Many thanks in advance.
Constructors with long parameter lists is an indication that your class is trying to do too much. One approach to resolving that problem is to break it apart, and use a "coordinator" class to manage the pieces. Subclasses that have constructor parameter lists that differ significantly from their superclass is another example of a class doing too much. If a subclass truly is-a superclass, then it shouldn't require significantly more data to do its job.
That said, there are occasional cases where a class needs to work on a large number of related objects. In this situation, I would create a new object to hold the related parameters.
Alternatives:
Use setter injection instead of constructor injection
Encapsulate the parameters in a separate container class, and pass that between constructors instead.
Don't use constructors to initialize the whole object at once. Only have it initialize those things which (1) are absolutely required for the existence of the object and (2) which must be done immediately at its creation. This will dramatically reduce the number of parameters you have to pass (likely to zero).
For a typical hierarchy like SalariedEmployee >> Employee >> Person you will have getters and setters to retrieve and change the various properties of the object.
Seeing the code would help me suggest a solution..
However long parameter lists are a code-smell, so I'd take a careful look at the design which requires this. The suggested refactorings to counter this are
Introduce Parameter Object
Preserve Whole Object
However if you find that you absolutely need this and a long inheritance chain, consider using a hash / property bag like object as the sole parameter
public MyClass(PropertyBag configSettings)
{
// each class extracts properties it needs and applies them
m_Setting1 = configSettings["Setting1"];
}
Possibilities:
Perhaps your class(es) are doing too much if they require so much state to be provided up-front? Aim to adhere to the Single Responsibility Principle.
Perhaps some of these parameters should logically exist in a value object of their own that is itself passed in as a parameter?
For classes whose construction really is complex, consider using the builder or factory pattern to instantiate these objects in a readable way - unlike method names, constructor parameters lack the ability to self document.
Another tip: Keep your class hierarchy shallow and prefer composition to inheritence. That way your constructor parameter list will remain short.