Should the factory pattern contain validation logic

design-patterns, factory, java

Solution

When using the factory pattern, should the factory itsel contain validation logic or should that be left up to the calling classes to take care of validation before passing the context data in?

There are two distinct alternatives to organize validation:

- Validation as a separate process

There is a separate validation method `Validate(Config)`. This method is called before construction method and returns information whether `Config` is valid or not. If `Validate` method returns that `Config` is valid, then construction method is called. Any error during construction process is considered to be an exception.

- Validation as part of construction process

There is no separate validation method. Instead validation happens inside construction method when needed. Construction method is allowed to fail and to return either a constructed object or a result indicating an error.

The second variant can be nicely implemented using monads with almost zero code and performance overhead.

Problem

When using the factory pattern, should the factory itsel contain validation logic or should that be left up to the calling classes to take care of validation before passing the context data in? I have a simple factory method but it relies on a config tree being passed to it to decide what object to instantiate. There could be a situation where the config xml might be well formed, but not in the correct format the factory is expecting and I dont know where this should be validated.

Original source

Related problems