Let's assume I have an object a of a class A. It has a method that needs an argument in form of another object of a particular type - but the argument should also be in particular state, because the operation performed by the method (let's say it's querying an external service, but it could be something else) requires it.
class A(object):
def action(self, argument):
return do_something(argument)
The first solution that comes to my mind is simple: the method should enforce a condition on the input data. It should test it for required state and then either raise an exception or modify the state:
class A(object):
def action(self, argument):
if argument.state == False:
raise Exception()
return do_something(argument)
class A(object):
def action(self, argument):
if argument.state == False:
argument.change_state()
return do_something(argument)
However, the instance we are talking about is only one of many instances of the A. All these instances should perform the same operation on input data: testing it for a particular state and then enforcing it, or just raising an exception. It seems they could use a shared instance of parameter whose required state is already enforced by an external caller, instance of class B:
class B(object):
def action(self, argument):
argument.change_state()
for a in self.instances_of_A:
yield a.action(argument)
Because I think the operation performed by the method wouldn't be properly encapsulated without enforcing the required state of argument inside the method, I think it should be moved to the former caller. The object a and all other instances of class A would just provide data necessary for performing the operation.
class B(object):
def action(self, argument):
argument.change_state()
for a in self.instances_of_A:
yield do_something(argument, a.data)
However, there is another problem: the operation returns a value that could be interpreted in a way related to instance of A to get another piece of data - and now it seems like the operation do_something should be encapsulated in a method of class A.
How should I solve this problem? Should I simply keep the current design and make object a return data that could be used to interpret return code provided by the operation? Perhaps I should use chain of command pattern and modify class A to delegate the operation to other instances of A? What are the other ways I could handle it?
needs to be in a particular state
meanhas to be set up correctly
? Then you probably want a builder.