Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am currently implementing a class for a network protocol. The protocol uses a

ID: 639449 • Letter: I

Question

I am currently implementing a class for a network protocol. The protocol uses a quite complex and extensive finite state machine. A pair of an event plus a state is mapped to a function, which does some work and sets the new state.

As there are about 150 valid state/event combinations and 28 distinct functions to be called, I refactored the whole state machine logic away from the associating/sending/receiving/... (let's call it service class) into a separate statemachine class. The problem is, that some of these 28 functions need access to the service class, for example to reset a deadline timer.

What I could do is befriend the statemachine class and the service class, so they can access each other's internals. This would introduce a very tight coupling (albeit natural, as they belong together). I could also just leave both these classes in one, but this would result in a huge class.

But since I doubt that I am the first one running into this problem, I assume that there exists a more or less canned solution to this I haven't found yet.

Explanation / Answer

The classic approach for decoupling two components is by defining a clear interface between them and let them communicate only by this interface (opposed to giving direct access to any internals).

So in your case: create an interface class (in C++ typically an abstract base class) for your service class, defining the interface you want to make public. Any access by the state machine or the 28 functions should be done only through this interface. So the state machine and the service class become decoupled, you now can easily replace it by a mock implementation for testing purposes, if you like.

This works the other way round as well: if your service class needs to access the state machine, define a public interface for your state machine, and access the state machine from outside only through this interface.