{"path": "/posts/forget-about-state-think-about-events-commands/", "title": "forget about state; think about events/commands · Bruno Dias", "html": "<!doctype html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"description\" content=\"forget about state; think about events/commands\">\n  <title>forget about state; think about events/commands · Bruno Dias</title>\n  <link rel=\"canonical\" href=\"https://diasbruno.github.io/posts/forget-about-state-think-about-events-commands/\" data-post-metadata>\n  <meta name=\"author\" content=\"Bruno Dias\" data-post-metadata>\n  <meta property=\"og:type\" content=\"article\" data-post-metadata>\n  <meta property=\"og:title\" content=\"forget about state; think about events/commands\" data-post-metadata>\n  <meta property=\"og:url\" content=\"https://diasbruno.github.io/posts/forget-about-state-think-about-events-commands/\" data-post-metadata>\n  <meta property=\"article:published_time\" content=\"2023-03-12T19:58:55Z\" data-post-metadata>\n  <link rel=\"icon\" href=\"/assets/site/signature.svg\" type=\"image/svg+xml\">\n  <link rel=\"alternate\" type=\"application/atom+xml\" title=\"diasbruno\" href=\"/atom.xml\">\n  <link rel=\"alternate\" type=\"application/json\" href=\"/posts/forget-about-state-think-about-events-commands/content.json\">\n  <link rel=\"stylesheet\" href=\"/assets/site/tokens.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/site.css\">\n  <link rel=\"stylesheet\" href=\"/assets/site/footer.css\">\n\n</head>\n<body class=\"light\">\n<div id=\"site-page\">\n<a class=\"skip-link\" href=\"#content\">Skip to content</a>\n<header class=\"site-header\">\n  <a class=\"brand\" href=\"/\" data-site-navigation aria-label=\"Bruno Dias, home\">\n    <img src=\"/assets/site/signature.svg\" width=\"24\" height=\"34\" alt=\"\">\n  </a>\n  <nav aria-label=\"Main navigation\">\n    <ul>\n<li><a class=\"nav-vrn\" href=\"/vrn/\" data-site-navigation><span class=\"nav-label\">vrn</span> <span class=\"nav-badge\">research</span></a></li>\n<li><a class=\"nav-posts\" href=\"/posts/\" data-site-navigation aria-current=\"location\">Posts</a></li>\n<li><a class=\"nav-projects\" href=\"/projects/\" data-site-navigation>Projects</a></li>\n<li><a class=\"nav-about\" href=\"/about/\" data-site-navigation>About</a></li>\n</ul>\n  </nav>\n</header>\n\n<main class=\"section\" id=\"content\" tabindex=\"-1\">\n  <article class=\"post-detail\">\n    <header class=\"section-header\">\n      <p class=\"post-category\">Post</p>\n      <h1>forget about state; think about events/commands</h1>\n\n      <p><time datetime=\"2023-03-12T19:58:55Z\">2023-03-12</time></p>\n    </header>\n    <div class=\"post-columns\">\n      <section class=\"post-body\" aria-label=\"Article\">\n\n<h3>Why?</h3>\n<p>When managing state, it's easy to just\nthink about which knobs you need\nto change manually. This is a low-level view\nof how state management works.</p>\n<p>If the developer doesn't pay attention,\nthe number of small states increases\nand also the work to keep everything in sync\n(since there are additional states that needs\nto be updated together).</p>\n<p>There is only a finite number of commands\nand transitions an application really needs.</p>\n<p>We can imagine something like:</p>\n<ul>\n<li>route to some place</li>\n<li>select an item from a list</li>\n<li>submit a form to an endpoint</li>\n</ul>\n<p>And translate into code as:</p>\n<pre><code class=\"language-java\">class RouteTo implements Command {}\nclass SelectedItem implements Command {}\nclass SubmitForm implements Command {}\n</code></pre>\n<h3>The application state</h3>\n<p>State, specially in most mainstream front-end\ntechnologies, they are all just a union of\nall possible states in an object available\nat any time.</p>\n<p>This also means that you are adding cache or,\nat least, you need to set up and tear down,\nand, always at risk of having stale data.</p>\n<p>It also common to shard the state into modules\nto separate one from another, but in some cases,\nyou need to run actions for each of the states,\ncausing many requests to render for a single event.</p>\n<p>Instead, we can start using a state machine.</p>\n<pre><code class=\"language-java\">class ListingUsers implements State {}\nclass CreatingUser implements State {}\nclass EditingUser implements State {}\nclass ViewUser implements State {}\n</code></pre>\n<p><a href=\"/images/evstatemachine.png\"><img src=\"/images/evstatemachine.png\" alt=\"\" title=\"state machine\" /></a></p>\n<h3>Commands and state</h3>\n<p>To get everything together, we can use a simple\nreduce.</p>\n<pre><code class=\"language-js\">/**\n * Pattern matching objects by their contructor's\n * name.\n */\nfunction match(object, table) {\n  const name = object.constructor.name;\n  return (table[name] || table['_'])(object);\n}\n\n/**\n * Given a state and many commands,\n * integrate each and accumulate\n * the next commands each command\n * can issue.\n */\nfunction updateState(state, commands) {\n  let nextState = { state, commands };\n  do {\n    const commands = nextState.commands;\n    nextState.commands = [];\n    nextState = commands.reduce(\n      (currentState, command) =&gt; {\n        const { state, commands } = currentState;\n        const [s, cs] = command.apply(state);\n        currentState.state = s;\n        currentState.commands = commands.concat(cs);\n        return currentState;\n      },\n      nextState\n    );\n  } while (nextState.commands.length != 0);\n  return nextState.state;\n}\n\nclass ListingUsers {}\nclass ViewingUser {}\nclass CreatingUser {}\nclass EditingUser {}\n\nclass SelectedUser {\n  constructor(user) { this.user = user; }\n\n  apply(state) {\n    return match(state, {\n      ListingUsers: (s) =&gt; [new ViewingUser(this.user), []],\n      '_': () =&gt; {\n        throw new Error('cannot select if not on ListingUser state.');\n      }\n    })\n  }\n}\n\nclass EditUser {\n  constructor(user) { this.user = user; }\n\n  apply(state) {\n    return match(state, {\n      ViewingUser: (s) =&gt; [new EditingUser(this.user), []],\n      '_': () =&gt; {\n        throw new Error('cannot edit if on ViewUser state.');\n      }\n    })\n  }\n}\n\nclass CreateUser {\n  apply(state) {\n    return match(state, {\n      ListingUsers: (s) =&gt; [new CreatingUser({}), []],\n      '_': () =&gt; {\n         throw new Error('cannot create user if on ListingUser state.');\n      }\n    })\n  }\n}\n\nlet list = [{ user: 'me' }];\nlet state = new ListingUsers(list);\n\n// start at this state\nstate = new ListingUsers(list);\n\n// transitioned to ViewingUser\nstate = updateState(state, [new SelectedUser(list[0])]);\n\n// throws because ViewingUser\n// can't handle SelectedUser event\nstate = updateState(state, [new SelectedUser(list[0])]);\n</code></pre>\n<p>This is great! We can now test it separate without having\nto setup anything related to the library or framework\nor whatever.</p>\n<p>Also, if we use property-based testing, we can generate\nas many events as we can to test &quot;infinity&quot; scenarios.</p>\n<p>The application state becomes just a lot of commands\napplied to an initial state.</p>\n<p>It simplifies a lot because:</p>\n<ul>\n<li>everything is updated in a single pass</li>\n<li>user can issue as many commands as they want (still a single pass)</li>\n<li>most of the things are in a central place</li>\n<li>state transitions are clear</li>\n<li>this can be used to create feature/local state to control\ninner components on a use case</li>\n<li>it's also FRP-like (functional reactive programming)</li>\n</ul>\n<p>And this idea comes from way back:</p>\n<ul>\n<li>Functional reactive animation - Paul Hudak, Conal Elliott, 1997</li>\n<li>Event-Driven FRP - Zhanyong Wan, Walid Taha &amp; Paul Hudak, 2001</li>\n<li>Arrows, Robots, and Functional Reactive Programming - Paul Hudak, Antony Courtney, Henrik Nilsson, and John Peterson, 2002</li>\n</ul>\n<p>On applications, this is a very simple separation of concerns\nthat may help you develop large scale apps.</p>\n<p><a href=\"/images/event-architecture.png\"><img src=\"/images/event-architecture.png\" alt=\"\" title=\"event architecture\" /></a></p>\n<p>The application flow is like:</p>\n<p><a href=\"/images/ea-components.png\"><img src=\"/images/ea-components.png\" alt=\"\" title=\"event architecture\" /></a></p>\n\n      </section>\n      <aside class=\"post-links\" aria-labelledby=\"post-links-heading\">\n        <h2 id=\"post-links-heading\">Links</h2>\n        <ul>\n<li><a href=\"/posts/\" data-site-navigation>All posts</a></li>\n        </ul>\n      </aside>\n    </div>\n  </article>\n</main>\n\n<footer class=\"site-footer\">\n  <div class=\"site-footer-inner\">\n    <a class=\"site-footer-home\" href=\"/\" data-site-navigation>Bruno Dias</a>\n    <ul aria-label=\"Footer links\">\n      <li><a href=\"https://github.com/diasbruno\">GitHub</a></li>\n      <li><a href=\"/atom.xml\">Atom feed</a></li>\n    </ul>\n  </div>\n</footer>\n\n</div>\n<script type=\"module\" src=\"/assets/site/navigation.js\"></script>\n</body>\n</html>\n"}
