State design Pattern: (Video call case study)

Ajibola Ojo
2 min readDec 29, 2021

--

So, after a long break, I decided to continue on the design pattern series, I gave a brief intro to design patterns, in this article, and I’m using this series as a systematic way to show how they feature in our day-to-day code.

So the state design pattern is one of the behavioral design patterns — it helps to solve problem that involve interaction between classes, the classes being the state of the object — used when objects behave in different ways based on the current state they are in.

One major note for visualising the implementation of this design pattern is finite state machines. Can this problem be visualized as a finite state machine (FSM)?

A Finite State Machine or Finite Automaton is an abstract machine that can be in exactly one of a finite number of states at any given time. While learning abstract stuff like automata theory in college, building stuff like this showed one of the practical applications of automata in software development.

So can our system be represented as having a finite number of states? Yes. For the sake of this case study, they include: IDLE, RECEIVING, CALLING, ONCALL.

FSM model for video calling

So this is the diagram of a finite state machine showing callers in their 4 possible states and the transitions that can occur.

Initially, Caller A and Caller B are IDLE. If Caller A attempts to call Caller B, Caller A state moves to CALLING, while Caller B moves to RECEIVING. At this point, either of the callers can decide to end the call, or Caller B can decide to receive the call. If the call is ended, both callers return to their IDLE state, in the case the call is received, both callers move to ONCALL state.

I’ll also show a brief code snippet in python to illustrate this:

Okay, so this may have been a whole lot, but it’s pretty simple once you understand the intuition. we have a Caller Class which stores the state and the other_person in a call. The caller’s state is one of the four classes implemented in the snippet, which all inherit from BaseCallerState.

  • An IDLE user can make_call or receive_call.
  • A RECEIVING user can accept_call or end_call.
  • A CALLING user can end_call or continue after the callee has_accepted_call.
  • An ONCALL user can only end_call.

So this wraps up the entire lesson about building using the state design pattern, we talked about the state design pattern, the usecase, finite state machines, visualised a problem as a finite state machine and translated the state machine to code.

If this article was helpful, please feel free to leave a clap🙂. You can leave comments to or reach out to me via Twitter.

--

--