Prefer Absence of State

I included settable state when I designed an interface for a software component. It goes something like this:


SetThing(thing Thing); // keep a copy of Thing.

GetState(state &State); // depends on internal Thing
DoAction(); // do action with Thing

At the time, it was a natural design. The problem with this is that I now have multiple clients that want to use the component. But they want to use it in different ways, simultaneously, with their own Things. So they have to create their own private copies of the component. This costs. The component is expensive to create and to keep alive. Multiple components now have to arbitrate for any internal shared resources.

A better design would have been not to have the component own a copy of the settable choice, the Thing. Simply to have the client code pass in a reference to a thing to each call that depends on a particular thing.


GetState(thing Thing, state &State);
DoAction(thing Thing); // use supplied Thing

There’s a trade-off here too, of course. The client code now has to own the Thing. And for the asynchronous calls in my component, the client code has to manage the Thing for the duration of the call.

But this does remove the fear of cross talk if multiple clients want to use the same software component, while supporting the use of multiple components if there’s a desire for them.

Even at the cost of making interfaces a little unwieldy with numerous parameters, I’d recommend avoiding internal state when reasonable.

Advertisements
Explore posts in the same categories: Code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: