(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 Result
method, say parse_rules
. Result
constructor would take as an argument a rules
object, and pass it onto self.parse_rules
.
Put that code inside a new class ResultFactory
. ResultFactory
would be a singleton class, which has a method, say build_result
, which takes rules
as an argument and returns a newly built result
object.
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.
You may want to consider a third scenario:
Rules.__call__
.Result
like: result = rules(data)
Pros:
Result
s can be totally unaware of the Rules
that generates them (and maybe even of the original Data
).Rules
sub-class can customize its Result
creation.Rules
applied to Data
yield Result
.Rules
have the initializing information for instances of Result
and pass it on creation.Side effects:
Rules
and Data
:
Rules
Rules
should be able to decide on which data it'll be applied.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With