{"data":{"prismic":{"blog_article":{"article_type":"Tech","title":[{"type":"heading1","text":"Great state machines","spans":[{"start":0,"end":20,"type":"strong"}]}],"summary_text":[{"type":"paragraph","text":"Lead Frontend Engineer, Gavin, explains what a boolean explosion is, and why state machines should become the norm in front end development. ","spans":[]}],"seodescription":null,"seotitle":null,"author":{"__typename":"PRISMIC_Person","name":"Gavin Thomas","job_title":"Lead Frontend Engineer","profile_picture":{"dimensions":{"width":200,"height":200},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/35128144-f6ac-41f6-a2ad-5fc7b33875c3_me.png?auto=compress,format"}},"published":"2022-08-02","image":{"dimensions":{"width":1808,"height":1016},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state+machines.jpg?auto=compress,format"},"programming_language":"Javascript","singleAspectRatioImage":{"childImageSharp":{"fluid":{"aspectRatio":1.779527559055118,"src":"/static/85db108287552a4573ec32a82ebecf3c/d47f1/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg","srcSet":"/static/85db108287552a4573ec32a82ebecf3c/b5b92/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg 200w,\n/static/85db108287552a4573ec32a82ebecf3c/3ff6e/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg 400w,\n/static/85db108287552a4573ec32a82ebecf3c/d47f1/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg 800w,\n/static/85db108287552a4573ec32a82ebecf3c/86173/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg 1200w,\n/static/85db108287552a4573ec32a82ebecf3c/a5547/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg 1600w,\n/static/85db108287552a4573ec32a82ebecf3c/1bd97/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.jpg 1808w","srcWebp":"/static/85db108287552a4573ec32a82ebecf3c/0c129/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp","srcSetWebp":"/static/85db108287552a4573ec32a82ebecf3c/0e93d/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp 200w,\n/static/85db108287552a4573ec32a82ebecf3c/2259f/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp 400w,\n/static/85db108287552a4573ec32a82ebecf3c/0c129/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp 800w,\n/static/85db108287552a4573ec32a82ebecf3c/45222/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp 1200w,\n/static/85db108287552a4573ec32a82ebecf3c/1f191/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp 1600w,\n/static/85db108287552a4573ec32a82ebecf3c/70720/bd084a3c-2d6c-47ea-b7b7-5a523baa8870_state%2Bmachines.webp 1808w","sizes":"(max-width: 800px) 100vw, 800px","presentationWidth":800}}},"link":{"uid":"great-state-ui-engineering"},"related_blogs":[{"blog":{"__typename":"PRISMIC_Blog_article","title":[{"type":"heading1","text":"Has Figma been ultimate remote working solution?","spans":[{"start":0,"end":48,"type":"strong"}]}],"summary_text":[{"type":"paragraph","text":"Like most digital agencies we transitioned to using Figma as our primary tool for UI/UX design around the start of the pandemic. But, where are we now?","spans":[]}],"author":{"__typename":"PRISMIC_Person","name":"Jon Thorne","job_title":"Lead Experience Designer"},"thumbnail":{"dimensions":{"width":1808,"height":1016},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/be87b523-4bdd-4423-aa98-8c4b03009961_FIGMA+2.png?auto=compress,format"},"article_type":"Opinion","published":"2022-04-19","link":{"uid":"is-figma-the-collaborative-cure"},"image":{"dimensions":{"width":1808,"height":1016},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/be87b523-4bdd-4423-aa98-8c4b03009961_FIGMA+2.png?auto=compress,format"},"_meta":{"uid":"is-figma-the-collaborative-cure"}}},{"blog":{"__typename":"PRISMIC_Blog_article","title":[{"type":"heading1","text":"Bicep - Flexing our Infrastructure as Code muscle","spans":[{"start":0,"end":49,"type":"strong"}]}],"summary_text":[{"type":"paragraph","text":"Great State have been using Microsoft technologies for over 20 years. In March 2021, a domain specific language for ARM moved out of alpha and immediately came to our attention - Bicep.","spans":[]}],"author":{"__typename":"PRISMIC_Person","name":"Dale Greenhood","job_title":"Technical Architect"},"thumbnail":{"dimensions":{"width":904,"height":508},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/52df09ce-83ab-46f8-97de-1b2c799cb0e8_colored-portrait-of-funky-young-man-with-showing-bicep-picture-id1227544662.jpg?auto=compress,format&rect=0,0,844,474&w=904&h=508"},"article_type":"Tech","published":"2022-01-07","link":{"uid":"bicep-flexing-our-infrastructure-as-code-muscle"},"image":{"dimensions":{"width":904,"height":508},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/52df09ce-83ab-46f8-97de-1b2c799cb0e8_colored-portrait-of-funky-young-man-with-showing-bicep-picture-id1227544662.jpg?auto=compress,format&rect=0,0,844,474&w=904&h=508"},"_meta":{"uid":"bicep-flexing-our-infrastructure-as-code-muscle"}}},{"blog":{"__typename":"PRISMIC_Blog_article","title":[{"type":"heading1","text":"Proxying Legacy Authentication Methods","spans":[{"start":0,"end":38,"type":"strong"}]}],"summary_text":[{"type":"paragraph","text":"Authenticating users in a modern browser-based application against a legacy identity provider can involve juggling technologies from different eras... so how do we manage it? ","spans":[]}],"author":{"__typename":"PRISMIC_Person","name":"Andrew McKaskill","job_title":"Lead Technical Architect"},"thumbnail":{"dimensions":{"width":904,"height":508},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/4f3b3043-24a2-48fc-970e-f65a7feb8410_iStock-1041476372.jpg?auto=compress,format&rect=0,0,4333,2435&w=904&h=508"},"article_type":"Tech","published":"2022-02-03","link":{"uid":"proxying-legacy-authentication-methods"},"image":{"dimensions":{"width":904,"height":508},"alt":null,"copyright":null,"url":"https://images.prismic.io/greatstate/4f3b3043-24a2-48fc-970e-f65a7feb8410_iStock-1041476372.jpg?auto=compress,format&rect=0,0,4333,2435&w=904&h=508"},"_meta":{"uid":"proxying-legacy-authentication-methods"}}}],"body":[{"__typename":"PRISMIC_Blog_articleBodyText","type":"text","primary":{"text":[{"type":"paragraph","text":"UI engineering involves building various sorts of components with interactivity. These include modals, buttons, login forms, toggles and search inputs, amongst others. What they all have in common is that they handle logic and the ability to show and hide controls or information to the user.","spans":[],"direction":"ltr"},{"type":"paragraph","text":"This problem is often modelled with the use of boolean flags. Engineers will create boolean flags to represent if something appears or is loading data from a server.","spans":[],"direction":"ltr"},{"type":"preformatted","text":"isModalOpen: false isLoading: false, isError:false","spans":[],"direction":"ltr"},{"type":"paragraph","text":"So what's the issue with this? Let’s take a look at the common example of a login form. Where the flow looks like this:","spans":[],"direction":"ltr"},{"type":"paragraph","text":"1. Account for a valid email and password ","spans":[],"direction":"ltr"},{"type":"paragraph","text":"2. Authenticate credentials with a server ","spans":[],"direction":"ltr"},{"type":"paragraph","text":"3. If the user is valid, then display a logged in page","spans":[],"direction":"ltr"},{"type":"paragraph","text":"Typically this would be modelled using boolean flags in the following way:","spans":[],"direction":"ltr"},{"type":"preformatted","text":"isLoading, isError, isSuccess","spans":[],"direction":"ltr"},{"type":"paragraph","text":"In order to render each of these scenarios we would combine these booleans:","spans":[],"direction":"ltr"},{"type":"preformatted","text":"!isLoading && !isError && !isSuccess ? 'idle'   \nisLoading && !isError && !isSuccess ? ‘Loading’ : ‘’ \n!isLoading && !isError && isSuccess ? 'Success'  : ''  \n!isLoading && isError && !isSuccess ? 'ErrorMessage' : '' ","spans":[],"direction":"ltr"},{"type":"heading3","text":"Implicit states","spans":[],"direction":"ltr"},{"type":"paragraph","text":"This would give us loading, error and success states which we can use to render or load those scenarios. The main issue we find is that the states are implicit and there’s a chance it could lead to an impossible state, so it’s up to the engineer to ascertain the correct logic to move forward. With the three boolean flags theres the possibility of eight states! Two for the first, times two for the second and times two for the third. This is known as boolean explosion.","spans":[{"start":349,"end":354,"type":"em"},{"start":453,"end":470,"type":"hyperlink","data":{"link_type":"Web","url":"https://egghead.io/lessons/javascript-eliminate-boolean-explosion-by-enumerating-states","target":"_blank"}}],"direction":"ltr"},{"type":"paragraph","text":"So what happens now if we want to display information to the user about an invalid password? There are other questions that arise when designing a form like this:","spans":[],"direction":"ltr"},{"type":"list-item","text":"What happens if the login fails?","spans":[],"direction":"ltr"},{"type":"list-item","text":"Where do errors from the form show up?","spans":[],"direction":"ltr"},{"type":"list-item","text":"Should we disable the submit button when the form is logging in?","spans":[],"direction":"ltr"},{"type":"list-item","text":"Should we validate the username and password before submission?","spans":[],"direction":"ltr"},{"type":"list-item","text":"When should we validate the username and password? As they type, when they move to another field or when they click submit?","spans":[],"direction":"ltr"},{"type":"list-item","text":"Does the button show a loading spinner when pending?","spans":[],"direction":"ltr"},{"type":"list-item","text":"How does the user cancel a logged in request?","spans":[],"direction":"ltr"},{"type":"paragraph","text":"How do we account for all these states using booleans?","spans":[],"direction":"ltr"},{"type":"preformatted","text":"isLoading: false \nisError:false \nisSuccess:false \nisUserValid:false \nisPasswordValid:false \nisCancelled:false","spans":[],"direction":"ltr"},{"type":"paragraph","text":"At this point it becomes onerous to decipher which state the application is in, and which combination of boolean flags to determine which state to expose to the user. What if we want to disable the submit button when the user has clicked submit (as we want to stop multiple attempts for impatient users) but also, what if an error is returned? We need to apply those conditions.","spans":[],"direction":"ltr"},{"type":"heading3","text":"Modelling behaviour with state machines","spans":[],"direction":"ltr"},{"type":"paragraph","text":"How do we address this problem? A much more robust approach is to use state machines to model the behaviour of an app or component. State machines, or more specifically finite state machines, describe a pattern where applications can only be in one of a number of finite states at any given time. State machines have been around for decades but often used in embedded systems, hardware, electronics automotive and games development. State machines adhere to the following criteria:","spans":[{"start":98,"end":107,"type":"strong"}],"direction":"ltr"},{"type":"list-item","text":"Have one initial state","spans":[],"direction":"ltr"},{"type":"list-item","text":"A finite number of states","spans":[],"direction":"ltr"},{"type":"list-item","text":"A finite number of events","spans":[],"direction":"ltr"},{"type":"list-item","text":"And a mapping of state transitions triggered by events","spans":[],"direction":"ltr"},{"type":"paragraph","text":"So how do we make the app logic for our login form better? Firstly, we identify the states and make them explicit:","spans":[],"direction":"ltr"},{"type":"preformatted","text":"const loginState = { \nIDLE:'IDLE', // not submitted yet \nPENDING:'PENDING', // Submitted and logging in \nSUCCESS:'SUCCESS' // Logged in successfully \nERROR:'ERROR', // login failed \n}","spans":[],"direction":"ltr"},{"type":"paragraph","text":"It's now impossible for the app to be in the loading and success state at the same time. We only allow these discrete states.","spans":[],"direction":"ltr"},{"type":"paragraph","text":"We can go one step further with this and use Object.freeze which stops modification, so any other engineers working on the codebase can’t accidentally change them. These events cause the app to change state.","spans":[],"direction":"ltr"},{"type":"preformatted","text":"const loginState = Object.freeze({ \nIDLE:'IDLE', // not submitted yet \nPENDING:'PENDING', // Submitted and logging in \nSUCCESS:'SUCCESS' // Logged in successfully \nERROR:'ERROR', // login failed \n})","spans":[],"direction":"ltr"},{"type":"paragraph","text":"If we go back to our button, we now don’t necessarily need to add a disabled attribute as the state machine constrains what events are allowed in the explicit state. In this instance, the ‘SUBMIT’ event is only valid in the ‘IDLE’ state. When we transition to the ‘PENDING’ state we only have ‘RESOLVE’ or ‘REJECT’, which are fired from the promise.","spans":[],"direction":"ltr"},{"type":"heading3","text":"Visualisation","spans":[],"direction":"ltr"},{"type":"paragraph","text":"The other added benefit of using state machines is it's easier to visualise this logic. A leading library for managing state machines is XState.","spans":[{"start":137,"end":143,"type":"hyperlink","data":{"link_type":"Web","url":"https://xstate.js.org/","target":"_blank"}}],"direction":"ltr"},{"type":"image","url":"https://images.prismic.io/greatstate/b3813dab-74b4-4731-a5ea-6302ff461ee0_statemachine-ui.png?auto=compress,format","alt":null,"copyright":null,"dimensions":{"width":1182,"height":496},"linkTo":{"link_type":"Web","url":"https://https://stately.ai/viz/19c76871-5785-4995-8acb-3fe5be2732a1"}},{"type":"paragraph","text":"This visualiser can be used alongside your app in development mode. They've also just released a state machine editor to visually create state machines. Being able to onboard to a project and visualise and interact with the logic is a huge win for comprehension. This can be shared amongst members of the project team like QA testers, developers and project owners.","spans":[{"start":0,"end":66,"type":"hyperlink","data":{"link_type":"Web","url":"https://www.youtube.com/watch?v=U47JNs4L9r4","target":"_blank"}}],"direction":"ltr"},{"type":"paragraph","text":"The other benefit of XState is that it's both library and framework agnostic. You can port the logic and use with most frameworks/libraries like React, Vue, Angular and Svelte. This is an extremely powerful paradigm and in fact there is a new UI library, called Zag, that uses this exact principle. State machines are used to manage the component logic which means it can be easily implemented for different frameworks and libraries. Write once, use everywhere. The component interactions are modelled in a framework agnostic way. We provide adapters for JS frameworks like React, Solid, or Vue. ","spans":[{"start":262,"end":265,"type":"hyperlink","data":{"link_type":"Web","url":"https://zagjs.com/","target":"_blank"}},{"start":434,"end":462,"type":"strong"}],"direction":"ltr"},{"type":"heading3","text":"Bugs","spans":[],"direction":"ltr"},{"type":"paragraph","text":"So what about bugs? How do state machines help minimise them? Firstly it forces you to think about the explicit states of the app or component up front and model the events needed (including edge-cases) and make it virtually impossible to end up in an impossible state.","spans":[],"direction":"ltr"},{"type":"heading3","text":"Use cases","spans":[],"direction":"ltr"},{"type":"paragraph","text":"Great State have used the XState library extensively for complex forms and workflows, application state management and component logic. It has helped us visual the application logic, help onboard new developers the codebase and expose states and events up front. When you consider the benefits of engineering in this way, I think that state machines to build user interfaces will become more and more prevalent over the next few years.","spans":[],"direction":"ltr"}]}}],"_meta":{"uid":"great-state-ui-engineering"}}}},"pageContext":{"isCreatedByStatefulCreatePages":false,"rootQuery":"\n  query PrismicBlogArticleByDocumentID($uid: String!) {\n    prismic {\n      blog_article(uid: $uid, lang: \"en-gb\") {\n        ...prismicBlogArticleFields\n      }\n    }\n  }\n","id":"Yk1P4REAACIAKDuC","lang":"en-gb","uid":"great-state-ui-engineering","alternateLanguages":[]}}