Design Patterns – Should Strategy Objects Have State?

design-patternsobject-oriented

I have an application object that needs to validate some data. The particular validation algorithm isn't known until runtime, so I pass a validation object to it, using the strategy pattern.

The application might need to reuse the validation object; for example, it might need to perform two validations simultaneously. So ideally, the validation object wouldn't contain any state; it would be purely an algorithm.

But what if the validation algorithm itself needs some state? For example, it might need to keep a list of validation errors.

What's a good approach in this situation? It seems like overkill to create a factory just for this specific validation object.

(Assume this is in a language like Java or PHP.)

Best Answer

I know I'm being pedantic here, but all objects can have state. The question is whether or not they should have state.

The answer to that question for strategies is the same as the answer for every other kind of inheritance relationship: Yes, as long as you're not violating the Liskov Substitution Principle.

The point of a strategy (or really any other inheritance-based design pattern) is that the caller/owner doesn't care about the implementation. So if the state is initialized either internally or through an instance constructor, and completely self-managed, then state is fine. On the other hand, if the outside world is supposed to be aware of this instance-specific state, then you've got a problem.

In a nutshell, if you find yourself needing to make this state public, then you've probably got a poor design; doubly so if you find yourself doing typecasts from the interface. But private state is, well, private; the whole point of patterns like Strategy is that the caller really doesn't care.

One other thing: Try to avoid sequential coupling. Even though it's OK for the strategy to have state, if the behaviour of the strategy depends significantly on that state then you are wading into dangerous territory, because you have no idea who else is going to try to use this strategy in the future and be unaware of the correct order of operations, so to speak.

Related Topic