Manage Frontend Status with Table-Driven Methods and State Pattern

Kenneth Cheung
< />
Published in
2 min readAug 28, 2021
Photo by @shawnanggg on Unsplash

The purpose of this article is to share a pattern to manage state branching logic in you component.

In the frontend development, one common case is switching different UI or behavior based on different status. For examples:

  • A campaign page displays different UI based on Campaign Status, Login Status and etc.
  • A product component is rendered differently by Product Status, Review Status, Violation Status and so on.

If we do not handle it carefully, it will end up a complex logic in the our code. It will become harder to maintain and error-prone.

To mitigate it, we can make use of the following 2 approaches,

  1. Table-Driven methods
  2. State Pattern

Table Driven methods

This is a programing method from the book Code Complete to manage if else branching logic in a more concise way (sometimes).

Let’s take a look at an example:

Although the second approach has a duplicate action3 declaration. It is still more straightforward in this case. But keep in mind that if you only have a few action be with a bunch of states, the table driven approach could be quite redundant and verbose. It is up to us to find the balance of when to use which.

Here is simple tool to create such a table driven JS code, you might want to take a look of it. Feel free to provide any opinion for this tool :)

https://playground.kenneth.pro/easy-state

State pattern

To my understanding, the main idea of GOF state pattern is:

Select a predefined set of methods and variables by given state at the first place and provide the same interface, so its dependent can use the interface without knowing the details.

If we utilize state pattern, the implementation would be:

  • Predefining all the variables and methods which need to be switched at the very beginning, and select the set by given state.

Let’s see a real life example in Typescript and combined with the table driven method we just talked about.

In this example, CampaignComponent displays different UI based on different LoginStatus, CampaignStatus, UserCampaignStatus:

In the example, although some of the state branch is redundant and verbose, it separates the business logic from your UI component. It is somehow more testable and maintainable.

Take React as an example, we can prepare our props in our custom hooks or redux containers.

Furthermore, you can wrap the States object in a function to make it more straightforward or less verbose for given business needs, like

As long as the code is understandable, testable, consistent and working correctly. It doesn’t matter which paradigm we are using. It is good code that everyone can work with it.

Hope this post helps you more or less, happy developing!

--

--