(Using Python 3.2, though I doubt it matters.)
I have class Data, class Rules, and class Result. I use lowercase to denote an instance of the class.
A rules object contains rules that, if applied to a data object, can create a result object.
I’m deciding where to put the (rather complicated and evolving) code that actually applies the rules to the data. I can see two choices:
-
Put that code inside a class
Resultmethod, sayparse_rules.Resultconstructor would take as an argument arulesobject, and pass it ontoself.parse_rules. -
Put that code inside a new class
ResultFactory.ResultFactorywould be a singleton class, which has a method, saybuild_result, which takesrulesas an argument and returns a newly builtresultobject.
What are the pros and cons of the two approaches?
The GRASP design principles provide guidelines for assigning responsibility to classes and objects in object-oriented design. For example, the Creator pattern suggests: In general, a class B should be responsible for creating instances of class A if one, or preferably more, of the following apply:
In your example, you have complicated and evolving code for applying rules to data. That suggests the use of the Factory Pattern.
Putting the code in Results is contraindicated because 1) results don’t create results, and 2) results aren’t the information expert (i.e. they don’t have most of the knowledge that is needed).
In short, the ResultFactory seems like a reasonable place to concentrate the knowledge of how to apply rules to data to generate results. If you were to try to push all of this logic into class constructors for either Results or Rules, it would lead to tight coupling and loss of cohesion.