C++ – Interface design where functions need to be called in a specific sequence

cinterfaces

The task is to configure a piece of hardware within the device, according to some input specification. This should be achieved as follows:

1) Collect the configuration information. This can happen at different times and places. For example, module A and module B can both request (at different times) some resources from my module. Those 'resources' are actually what the configuration is.

2) After it is clear that no more requests are going to be realized, a startup command, giving a summary of the requested resources, needs to be sent to the hardware.

3) Only after that, can (and must) detailed configuration of said resources be done.

4) Also, only after 2), can (and must) routing of selected resources to the declared callers be done.


A common cause for bugs, even for me, who wrote the thing, is mistaking this order. What naming conventions, designs or mechanisms can I employ to make the interface usable by someone who sees the code for the first time?

Best Answer

It's a redesign but you can prevent misuse of many APIs but not having available any method that shouldn't be called.

For example, instead of first you init, then you start, then you stop

Your constructor inits an object that can be started and start creates a session that can be stopped.

Of course if you have a restriction to one session at a time you need to handle the case where someone tries to create one with one already active.

Now apply that technique to your own case.

Related Topic