Introduction to modeling with Finite state machines

@farzad_yz

Farzad Yousef Zadeh

@farzad_yz

Senior software engineer @Futurice

International conference speaker.

Web and Mobile development.

Javascript, Typescript.

✈ 🚀 🔭 🌌

💻

What is a State Machine?

W T F?

What is a State Machine?

Mathematical model

Single explicitness source

Useful for modeling states

Finite amount of states

Starts from one of them

Transitions between them only by events

Executes side effects on transitions

state

state

event

event

event

event

Why is it relevant to Software Development then?

Client side applications are Stateful

Toggles

Tabs

Dropdowns

Modals

Pagination

Remote Data

Subscriptions

Observables

Asynchrony

Concurrency

I'm sorry that I long ago coined the term "objects" for this topic because it gets many people to focus on the lesser idea.

The big idea is MESSAGING

Client side applications are Event Driven

Push based

Pull based

Reactive

Data binding

(unidirectional, bidirectional)

Event >> Actions

element.addEventListener("click", clickHandler);

channel.on("message", readMessage);

Finite State Machine in Practice

Think in States

State ≠ State

type State = {
  isLoading: boolean;
  accounts: Account[];
  error?: any;
};
type State = 
| "Idle"
| "Loading"
| "Success"
| "Error";

We're acustomed to

in the FSM world

Where to apply?

const remoteDataState = 
 | "Idle"
 | "Pending"
 | "Success"
 | "Error"
const remoteDataState = {
  isPending: boolean;
}

Before

After

Promises/Futures

const formState = 
  | Idle
  | Touched
  | Validating
  | Submitting
const formState = {
  isTouched: boolean;
  isValidating: boolean;
  isSubmitting: boolean;
}

Before

After

Mutual Exclusivity

FSM tight couples States and Events

const formState = {
  initialState: "idle",
  states: {
    idle: {
      on: {
        INPUT_FOCUS: "touched"
      }
    },
    touched: {
      on: {
        INPUT_CHANGE: "validating"
      }
    }
  }
}
{
  initial: "idle",
  states: {
    idle: {
      on: {
        TYPE: "readyToSearch"
      }
    },
    readyToSearch: {
      on: {
        SUBMIT: "searching"
      }
    },
    submitting: {
      on: {
        SEARCH_SUCCESS: "itemsRendered",
        SEARCH_FAILURE: "errorShown"
      }
    }
  }
}

Concurrency Issues

Search

Search

Pizza and Beer

Additional Benefits of FSM

Visualized Logic

Onboarding new developers

Understanding legacy code

Faster feature iterations

Robust debugging

Cross Competence communication

Cross platform logic sharing

function HeadlessCarousel(props) {
  const {children, ...carouselProps} = props;
  const [state, sendEvent] = useMachine(carouselProps);
  
  return children({
    state: state.value,
    data: state.context,
    next() {
      sendEvent("NEXT")
    },
    prev() {
      sendEvent("PREV")
    },
    play() {
      sendEvent("PLAY");
    },
    pause() {
      sendEvent("PAUSE")
    }
  })
}
<HeadlessCarousel>
  {headlessCarousel => {
    <div>
      <button onClick={headlessCarousel.next}>
        Next
      </button>
    </div>
  }}
</HeadlessCarousel>
<HeadlessCarousel>
  {headlessCarousel => {
    <View>
      <TouchableOpacity onPress={headlessCarousel.next}>
        Next
      </TouchableOpacity>
    </View>
}}
</HeadlessCarousel>
stdin.on("keypress", (_, code) => {
  if (code === ARROW_RIGHT) {
    sendEvent("NEXT");
  }
});

Web

Mobile

Command Line 😱

Limitations of FSM

State Explosion

Conditional transitions

Conditional side effects

State Structure

StateCharts

extends FSM

What is StateChart then?

Make Nested machines

Make Parallel Machines

Conditional Transitions

Store Non-concrete state
&& data

Things can happen only if other things have happened before

Things can live independently in the same context

Guard against invalidity / Branching logic

Model non-concrete concepts e.g. Animations / Internal data store

Submit form only after the input is validated

Twitter Feed vs Side Widget

Red input when invalid / Green input when valid

Battery percentage / List of countries / Server Error

State Structure

What is StateChart then?

Support  Entry Actions

Support  Exit Actions

Actions to be executed when you enter a state (Good for initializing stuff)

Actions to be executed when you exit a state (Good for cleaning up)

Start off a fetch controller upon entering the pending state

Cancel the fetch upon exiting pending state

Different type of  

Side Effects

Fire and Forget, invoking async tasks, activities, streams, etc

Takeaways

Any state is worth a State Machine

State Machines bring up implicit / hidden / missing states to the surface

State Machines follow a (state, event) >> action

State Machines are easier to reason about

State Machines consider the dimension of time

Farzad Yousef Zadeh

@farzad_yz

#GDG #Elisa

@Futurice

Introduction to modeling with Finite state machines

By Farzad Yousefzadeh

Introduction to modeling with Finite state machines

Finite state machines are a mathematical means of computation. In this talk, we’ll go through why using them might help us simplify the challenges we face in day to day UI development and how they help us communicate better with people from different backgrounds in the same team. Although the talk will focus mostly on UI development, the concept is abstract and can apply to any problem solving process. Developers, Designers and even product related roles can take something out of this talk.

  • 1,281