Should I accept the same object as a parameter and return it or just accept it as a parameter?
I have the following interface:
public IStateMachineConfigurator
{
??? Configure(StateMachine machine);
}
In the implementation I am calling some of the StateMachine methods to configure it like this:
machine.Configure(States.State1)
.Allow(Triggers.Trigger1);
The question is, can I rely on the fact that the StateMachine object is a reference or should I use a return v开发者_运维知识库alue or a return parameter like ref/out?
EDIT:
The state machine itself comes from a library and thus I cannot decide it's implementation.If you wanna go with the builder pattern then your effectivly return the mutable state that is being passed in. This is perfectly fine, if you wanna go down that road. This is how the StringBuilder class operates and on a somewhat different note jQuery. It can be very nice for building objects in a compact and readable fashion. However, those objects should be designated as such. Builder objects and preferably not take on more than necessary.
Yes, you can rely on the fact that StateMachine
is an object reference. Some people might choose to return a bool
or perhaps an enum
to give the programmer some kind of hint as to what happened in the Configure
method (ie. success/fail/no change/etc.). Others might choose to throw an exception in the event something goes wrong.
All are perfectly valid, just be careful how deep you chain the method together, as something like:
machine.Configure().Allow().someMethod().someOtherMethod()
Gets difficult to debug and trace.
Instead of creating a Configurator
, I would rather craete a Configuration
object and pass it in the StateMachine
constructor. This makes it cleare to the users of StateMachine
class that they have to provide it with a valid configuration before using it.
class StateMachineConfiguration
{
public IEnumerable<State> States { get; private set; }
public IEnumerable<Trigger> Triggers { get; private set; }
}
class StateMachine
{
public StateMachine(StateMachineConfiguration config)
{
if(config == null)
throw new ArgumentNullException();
this.Configure(config.States);
this.Allow(config.Triggers);
}
}
精彩评论