Do This Instead Of Representing State With Booleans

Learn how to go from using booleans to represent state to writing a reducer and a simple state machine in Svelte to using XState to avoid impossible states and have more confidence your code works as expected.
👉️ Support
▶️ KZread Membership
youtube.com/@joyofcodedev/join
🔴 Patreon
/ joyofcode
👉️ Links:
XState
🔗 xstate.js.org/
Stately
🔗 stately.ai/
Introduction To State Machines Using XState
🔗 egghead.io/courses/introducti...
How To Tell A Bad Boolean From A Good Boolean
🔗 dev.to/mattpocockuk/state-man...
How To Stop Making Horcruxes In Your Code
🔗 dev.to/mattpocockuk/state-mac...
You Don't Need A Library For State Machines
🔗 dev.to/davidkpiano/you-don-t-...
👉️ Uses:
🔗 joyofcode.xyz/uses
👉️ Socials:
🐦️ / joyofcodedev
💬 / discord
🔖 Timestamps
0:00 Intro
0:29 Booleans
2:32 Enums
3:38 State Machines
5:14 Reducer Pattern
6:22 Faux State Machine
8:47 Using XState
11:52 Outro
#svelte #xstate #joyofcode

Пікірлер: 163

  • @JoyofCodeDev
    @JoyofCodeDev11 ай бұрын

    🔴 Patreon: www.patreon.com/joyofcode 💬 Discord: joyofcode.xyz/invite

  • @lm5050
    @lm505010 ай бұрын

    As a hobby enthusiast I often hit this wall on small projects: As the code base expands the number so too does the number of state based booleans which cause an exponential number of issues... This was super helpful!

  • @cyrusol
    @cyrusol10 ай бұрын

    Wait until you find out that calling methods on an object is the same as passing events. The cycle of software development probably is the endless reinvention of things that already exist but under a different name.

  • @anon_y_mousse

    @anon_y_mousse

    10 ай бұрын

    Yep, it's why we have long-lasting fad programming languages. Java, Python and JavaScript still exist and are used by millions decades after they should have died, and now we've got Go and Rust trying to infiltrate. None of these languages are good, nor were they needed and yet we're saddled with them and they're going to be around for decades because most people don't have working brains.

  • @AetherMomon
    @AetherMomon10 ай бұрын

    State Machines are definitely very useful! I created a state machine once where each state is it's own class, and each state class has it's own events like "Enter State", "On State Ended", etc which can be overridden in child classes with functionality added about a particular state. I created a state manager system which manages the state classes as well as which state is currently active and calls the on state end, enter state functionalities. Really nice way of handling things for complex projects & also happens to be fairly modular.

  • @marcomoreno6748

    @marcomoreno6748

    10 ай бұрын

    I made a very rudimentary state stack machine in Lua. I used it in some roblox projects as well as love2d. I didn't bother with OOp I just tried to make it compact, readable, and added and refined features as I went. It's surprisingly versatile and performant. A nice little helper library I've used it in everything from handling ui, game "states, tool/weapon logic in roblox, and even basic bot ai.

  • @cluelessdev3851

    @cluelessdev3851

    9 ай бұрын

    ​@@marcomoreno6748 Oh nice fellow roblox dev, I think the heavy use of OOP in Ryu's approach could be simply because the language he chose to dev in is conductive to OOP. But in luau a heavy OOP state machine is frankly nuts. Would love to know how you handled recursion, if you even did! Cause that's what really preventing me from releasing my state machine library ;-;.

  • @francopascual6958
    @francopascual695811 ай бұрын

    Clean video, liking this format!

  • @kirillvoloshin2065
    @kirillvoloshin206510 ай бұрын

    Great video! State machines are great for covering all possible states of a simple app: such as a video player or weighing system of cargo trucks (saw one and wrote one 🙂), but I feel like mobx class stores would be a more suitable state handling solution for an actual game

  • @asatorftw
    @asatorftw9 ай бұрын

    Used this video today to build a onboarding/tutorial process for my app. If I had done it with booleans I would have probably thrown it away at some point, so those tips were gold haha

  • @ibrahimkoz1983
    @ibrahimkoz198310 ай бұрын

    OOP is the exact application of what you illustrated in this video. OOP is about events and messages. The state pattern is the application of this, but better in expandability because it eschews switch cases.

  • @pedrokalil4410

    @pedrokalil4410

    10 ай бұрын

    On my universities course on oop, I was surprised that the teacher didn't teach about state machines as an oop pattern. He talked about singleton, factory and such but not state machines

  • @andreilucasgoncalves1416

    @andreilucasgoncalves1416

    10 ай бұрын

    ​@@pedrokalil4410I've never seen a university teach state machine

  • @askeladden450

    @askeladden450

    10 ай бұрын

    ​@@andreilucasgoncalves1416its part of an automata course in most universities

  • @ToJak91

    @ToJak91

    3 ай бұрын

    We were taught state famines.. But that was in a version of Java, which couldn't handle switch on strings..

  • @smithrockford-dv1nb
    @smithrockford-dv1nb10 ай бұрын

    I've struggled with understanding how Redux works in React for ages, it just made no sense. This video unintentionally explained the reducer pattern so well in a minute or so (and I didn't even have to slow down the video from 2x).

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    I also didn't understand it when I used it to be honest. 😂

  • @IvanKleshnin
    @IvanKleshnin10 ай бұрын

    Among non-boolean examples XState version felt the worst. Replacing a normal code with declarative JSON-like blob of configs is a typical antipattern IMO. I also didn't get why for Reducer-based version you switched to boolean flag again. Reducer pattern can totally be used together with state enums.

  • @ade_eda

    @ade_eda

    10 ай бұрын

    I totally agree with you, but I feel like a lot of react/other js web framework like using JSON-like code

  • @lukekurlandski7653

    @lukekurlandski7653

    10 ай бұрын

    I think the spirit of the the video is to use these patterns when state becomes complex. For the first example with three booleans, obviously a state machine is not warranted. However, if your state is extremely complicated the state machine would probably be simpler than having like 10 booleans. The video admittedly does not do a great job at describing when these patterns would be appropriate…

  • @kassios

    @kassios

    10 ай бұрын

    Why is it an antipattern? State libraries in Frontend frameworks are usually a place to store data and some conditionals, leaving the flow of the application vague as a mental model which isn't explicitly described on state. It mainly lives in the mind of the developer. Finite State Machines (like xState) enforce a clear representation of steps (which are confusingly called states) that a user can make. The flow of the application is clear, the conditions and restrictions are clear and you cannot land in a bad state. Every single time I create a component and skip starting with a Finite State Machine I regret it soon after when the complexity rises and new features creep in.

  • @ivensauro

    @ivensauro

    10 ай бұрын

    @@kassios i liked your arguments, but i prefer the kiss and yagni, better make the components the most simple way first, and when need complexity, change/refactor fast (if is a nightmare to refactor, maybe the code was not simple, and not good)

  • @jeffwells641

    @jeffwells641

    10 ай бұрын

    IMO the only reason it felt this way was because the example was so simple. If you look at what the JSON is actually doing, there is room for multiple on X events, multiple actions per state, etc. that were all only used once because of the simple example. That makes the JSON a really bloated and cumbersome solution for what it's supposed to do. So the XState's JSON structure does indeed make a simple state machine harder to read, and it certainly IS an anti-pattern to use JSON when a simple switch/case block will do instead. However, it seems just as clear to me that the JSON structure would make a very complex state machine MUCH easier to understand and manage. For example, what if you needed to manage the behavior of multiple simultaneous keypresses as well as clicks in your game loop? This is not unusual for a game, and the JSON structure you complain about is immediately beneficial for code organization and understandability in that case. A lot of effective programming is choosing the right tool for the job. XState is obviously not the right tool for a simple JS cardflip game, Matia even says this in the video. However, it might be the right tool for a complicated browser based MMO, or something else more complicated than a simple card flip game.

  • @alexismandelias
    @alexismandelias10 ай бұрын

    This video does a great job of introducing me to new concepts. However, I found that I need to dig a bit deeper to understand **why** I might want to use a reducer over a state machine for example. I get (more or less) *how* each pattern works, but it's not at all clear *why* I would want to use each one, I don't know what its pros and cons are. A better way to go about doing this might be starting from the problem (representing state) and then working towards the solution (each different pattern). This way, the benefits of each pattern arise effortlessly from the nature of the problem and the process with which we try to solve it. The visuals are top-notch, I would recommend looking a bit more into the script and pacing of the video.

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    I only show the reducer example because people conflate them when they're not the same and I never use it.

  • @AK-vx4dy
    @AK-vx4dy11 ай бұрын

    @0:57 there are 8(eight) possible states on 3 booleans 2^3 2**3

  • @JoyofCodeDev

    @JoyofCodeDev

    11 ай бұрын

    I'm bad at math.

  • @AK-vx4dy

    @AK-vx4dy

    11 ай бұрын

    @@JoyofCodeDev In current days binary is not mandatory for programmers, math also. You clearly understand logic, state machines and readable and maintainable code and really can infect other people with joy of coding, keep going !!!

  • @fredbcruz
    @fredbcruz10 ай бұрын

    Thank you! just stumbled in exact this problem coding a simple snake game on svelte

  • @bjul
    @bjul11 ай бұрын

    You're da bomb! Thanks.

  • @rogue.ganker
    @rogue.ganker10 ай бұрын

    Very well done!

  • @alfredlotsu950
    @alfredlotsu95010 ай бұрын

    At 1:01 I would have personally set playing = !gameOver, to prevent that impossible state, but great tutorial overall! Subbed!

  • @JoseWaldier
    @JoseWaldier11 ай бұрын

    Underrated Channel. Keep it up bro. You'll grow fast Q: how do you edit your videos with those effect?

  • @JoyofCodeDev

    @JoyofCodeDev

    11 ай бұрын

    It's made with Svelte and I plan to release it when it's ready. 🙂

  • @ste-fa-no
    @ste-fa-no11 ай бұрын

    Great content! 👏

  • @zachmanifold
    @zachmanifold10 ай бұрын

    (NOTE: I’m on mobile so I have no idea if this will format properly) For more complicated state management I sometimes use bitmasks. Each state is represented by one specific bit (1

  • @talkysassis

    @talkysassis

    10 ай бұрын

    This helps saving memory too. Very good for embedded systems

  • @ImperiumLibertas

    @ImperiumLibertas

    10 ай бұрын

    This is a good pattern but it is so easy for a new developer to not use the named values for the bitwise state and instead set the state to a non named value making the code difficult to read and debug. This pattern in my opinion is useless unless the devs strictly use the named values because the relationship between the bits state and what they represent is usually abstract. Just something to consider. Names values are so important.

  • @anon_y_mousse

    @anon_y_mousse

    10 ай бұрын

    @@ImperiumLibertas So because some developers are idiots the language should hold everyone's hand and slap them across the face every time they misbehave? I guess that's one way to push people into being obedient slaves, leave no room for creativity or mistakes. Not that you'll understand this point, but language designers that think they can foresee every possibility ahead of time make our programming languages worse by enforcing strict rules that cause problems in an attempt to solve quasi-problems.

  • @zachmanifold

    @zachmanifold

    10 ай бұрын

    @@talkysassis I actually think embedded is where I picked this up from. It was either some embedded code or some really ancient library code I was reading, and I was like huh... that's really clever. And it's been incredibly useful in some cases

  • @idktbh4004
    @idktbh400411 ай бұрын

    Didn’t know you can declare variables inside the markup like that. Always a feature I wished svelte had. I just didn’t know lol

  • @JoyofCodeDev

    @JoyofCodeDev

    11 ай бұрын

    Local constants were added a while ago: svelte.dev/docs/special-tags#const.

  • @redumptious2544

    @redumptious2544

    10 ай бұрын

    Can you elaborate why exactly? I’ve seen it around a bit but I don’t really see the point that much… (or maybe I just haven’t seen a convincing example)

  • @TheNewton

    @TheNewton

    10 ай бұрын

    @@redumptious2544 to set information of the local context, such as when in a for loop you may want to keep track of the item from the previous loop.

  • @KorhalKk
    @KorhalKk9 ай бұрын

    I try to avoid any two States with boolean values. But I use the same boolean for different methods which will act together, like styling and form hiding.

  • @NedCollyer
    @NedCollyer11 ай бұрын

    I miss my "Hey friends" :) Thanks for the vids.

  • @elatedbento
    @elatedbento10 ай бұрын

    The video quality is absolutely awesome. Is there a tool that you use? Fantastic content.

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    I use Animotion: kzread.info/dash/bejne/lnaavMyvXc_aYs4.html.

  • @09lilkiller
    @09lilkiller10 ай бұрын

    I usually never comment or like videos. But this was very well done.

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    Thank you! 😄

  • @detaaditya6237
    @detaaditya623710 ай бұрын

    Great video! I agree that booleans shouldn't be overused for representating states. I always prefer enums/reducer. The problem with enums is language support. TypeScript lacks expression-based if & switch control structure and type constructors, which makes working a bit boilerplate-y and verbose

  • @br3nto
    @br3nto10 ай бұрын

    7:37 so for each function, in this case our function returns a string describing the current state, we need to check and handle each game state? It would be easier in this case to encapsulate the functionality of each game state in a subclass, then simply rely on polymorphism. Each state state would have an associated instance, so each state change would simply return the associated instance. Super simple. To check which state were in we just check the type of the instance. This also allows us to decouple all the logic of all the states, and also decouple the state transition logic. The only drawback is not all functions exist or should be implemented for each state. Eg no point in being able to pick a card when the game is over. But this says more about the design than the state machine pattern. It would indicate the state machine is encompassing too much. Perhaps a separate state machine is needed for a running game. But that's another discussion al together.

  • @ImperiumLibertas

    @ImperiumLibertas

    10 ай бұрын

    That's exactly what Akita or Elf does for typescript. It's the reducer/redux pattern with separate stores and services depending on the use. Typically these are separated on the domain/feature that way it clearly outlines shared state in separate stores/services. It creates a state hierarchy. The separation of state while breaking out shared state creates a very slick state implementation.

  • @ahasdasetodu6304
    @ahasdasetodu630410 ай бұрын

    I never even thought that booleans could be used to represent states if there are more than two. My default go to was just an integer but then I had to remember what each value represents, I suppose enums slove that problem.

  • @DanielCarvalho2
    @DanielCarvalho29 ай бұрын

    i love your videos, thank you! :)

  • @JoyofCodeDev

    @JoyofCodeDev

    9 ай бұрын

    My pleasure! 😄

  • @igeoerre
    @igeoerre9 ай бұрын

    I was following until I got to the state machine part things got too abstract, but the explanation is very good, thanks.

  • @markcahalan5698
    @markcahalan56989 ай бұрын

    Big fan of function pointers/delegates for state based interactions - removes most of the if's associated with state management Not sure if Javascript has those though, I do C# and am trying to pick C++ up again

  • @jsonkody
    @jsonkody9 ай бұрын

    Nice video, thanks. State machines are awesome, I know about them for a long time but didn't use them yet. I've learnt about them when I looked at how to program regex engine. Maybe in game project I plan to do .. PS: 6:26 ... 🤣🤣🤣

  • @Der_Yoloist
    @Der_Yoloist9 ай бұрын

    this got from simple math to rocket science pretty quick

  • @erickmoya1401
    @erickmoya14018 ай бұрын

    I dont know if you are the same who writes in the website. But I love it. For this case: I really hate react, and thats why I switched to svelte. So I feel like going back to the ugly redux days. For me is a no-go

  • @JoyofCodeDev

    @JoyofCodeDev

    8 ай бұрын

    It's me! 😄

  • @yash1152
    @yash11529 ай бұрын

    1:16 1:52 first time -seeing- noticing font ligatures enabled in a video... which application are u using to show this code?

  • @JoyofCodeDev

    @JoyofCodeDev

    8 ай бұрын

    I use Animotion which is a presentational framework I made for creating educational content at animotion.pages.dev/.

  • @yash1152

    @yash1152

    8 ай бұрын

    @@JoyofCodeDev awesome +1

  • @dane4ka474
    @dane4ka47410 ай бұрын

    I definitely should revisit my code for image processing Telegram Bot using a state machine and draw a proper diagram (even though existing code works well enough)

  • @TheFoxstory
    @TheFoxstory10 ай бұрын

    love your videos man! are you going to do a pocketbase auth crud app tutorial anytime?

  • @doxologist
    @doxologist11 ай бұрын

    Awesome video! What theme do u use?

  • @JoyofCodeDev

    @JoyofCodeDev

    11 ай бұрын

    joyofcode.xyz/uses

  • @doxologist

    @doxologist

    11 ай бұрын

    @@JoyofCodeDev damn you're so organised. Thanks

  • @zhanezar
    @zhanezar11 ай бұрын

    What is your views on using reactive statements? mainly in regards to performance , do you think it hinders it vs just calling a function at a time you want to check something like if matches is = to emojis etc . I get nervous using reactive statements as it seems like magic , not sure if there is a negative side to too many reactive statements

  • @JoyofCodeDev

    @JoyofCodeDev

    11 ай бұрын

    It probably compiles to something similar, so I don't think performance is ever a problem with Svelte. You can go to the Svelte REPL and look at the compiled code. Magic is great as long as it works as expected.

  • @willsterjohnson

    @willsterjohnson

    11 ай бұрын

    It does indeed compile down to simple function calls, however because it's compiled its probably more efficient than what most of us would write without a compiler

  • @SahilP2648

    @SahilP2648

    11 ай бұрын

    @@willsterjohnson yes as I understand it at least, Svelte's compiler takes care of all possibilities of variable states and code affected, and then at compile time generates all those possibilities internally and in multiple .js files then based on need these small .js files are downloaded from the server. The only drawback would be slower compile times for your project, but thanks to quite literally limitless compute nowadays, it doesn't seem like a problem. I am not sure if Svelte does any caching but if it does it should be possible to share the cache between developers so even the build doesn't need to happen again and again when working inside a team.

  • @MikeNugget
    @MikeNugget11 ай бұрын

    Nice.

  • @mz00956
    @mz0095610 ай бұрын

    Why would I make a boolean "isPlaying" and use that to check instead of checking the Enum directly? Is there any obvious advantage that I overlook?

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    It's just an example.

  • @Metruzanca
    @Metruzanca10 ай бұрын

    Typescript enums have a sluw of issues, I would strongly recommend avoiding them and just use objects with "as const" at the end if in typescript

  • @amaraw9893
    @amaraw989310 ай бұрын

    If you're using a OO language (like java, Python, C#, etc) and have a lot of states, and your program will constantly be changing states, then you should just use the State design pattern. You have a parent class called State and that class has all the child states. That way all the kids can extend the parent class, implement common methods in their own ways, reduce conditionals, and it uses the open/close principle since you can add other states without messing with previous code.

  • @raffimolero64

    @raffimolero64

    10 ай бұрын

    If you put all the state logic in each of the individual child States, you'll typically use different files to store the logic. The Data-Oriented approach of "state is an enum that can be different values" means that your state transition code has to live in one function and one file, separate from the definition. I personally use Rust, which encourages the latter if I don't have complex logic. I only split it up into multiple functions (rather than classes/traits) when things get big.

  • @SEOTADEO

    @SEOTADEO

    10 ай бұрын

    Hahahaha this is the first time I have heard someone refering to children as kids (in programming). But good point.

  • @amaraw9893

    @amaraw9893

    10 ай бұрын

    @@SEOTADEO 😅 i use em interchangeably

  • @amaraw9893

    @amaraw9893

    10 ай бұрын

    @@raffimolero64 yeah... I can definitely see where this design method could get messy. I see the value in the inheritance though, so it's really only useful if there is common functions and data within those states and it being a big program. On the otherhand, it helps maintain single responsibility because you'd have a separate class for the states instead of one class in charge of several functions that don't necessarily need to know each other. It also helps you control what each state knows (in terms of global vars and such).

  • @user-on2rx4si7g
    @user-on2rx4si7g10 ай бұрын

    1/3: Hey there! 👋 I just watched the course you mentioned, and I must say it was 🔥! The hands-on approach really made a difference. I've seen a few other courses too, but yours definitely stands out. I'd give it a solid 10/10. 😄 2/3: By the way, I checked out your website and your other works, and I have to say, you're quite the artist! 🎨👌 I have a suggestion for your next video: How about creating a video on designing a system using Svelte? 🎥✨ It would be awesome if you could dive into the key elements of building a top-notch design system. 💪 3/3: And to wrap it up, it would be fantastic if you could even compare different design systems or component libraries towards the end of the video. 🔄🔍 I think it would provide great insights for designers and developers alike. Looking forward to more amazing content from you! 🙌😊 ❤❤

  • @eastcoastpizza784
    @eastcoastpizza78411 ай бұрын

    Wow ! 👍👍

  • @allendover7480
    @allendover74808 ай бұрын

    How do you get === and => to look like they do? That's a nice touch.

  • @JoyofCodeDev

    @JoyofCodeDev

    8 ай бұрын

    Make sure your font supports font ligatures and enable them in your editor.

  • @allendover7480

    @allendover7480

    8 ай бұрын

    ​@@JoyofCodeDev That looks so elegant. Thanks for the answer!

  • @k98killer
    @k98killer10 ай бұрын

    7:40 where the hell do matches and emoji come from? Am I just stupid and missing something obvious? Or was it just pseudocode that I inspected too closely?

  • @kmemz
    @kmemz8 ай бұрын

    Why not use an integer as a state system? 1 is menu, 2 is playing, 3 is paused, 4 is game over. The code for the menu and game over states wipes data from the playing state, while the pause state retains it. The pause and playing states have bindings to the pause key to call each other, but the binding doesn't exist outside of that, so there is no need to check for an invalid state in the menu and game over codes. There are no impossible state setups here, you don't have to do defensive programming, and you avoid unnecessarily complicated state machines where they're not needed.

  • @acharafranklyn5167
    @acharafranklyn51678 ай бұрын

    please is there a blog or an article i can go read about this more

  • @JoyofCodeDev

    @JoyofCodeDev

    8 ай бұрын

    I included some resources in the description.

  • @k98killer
    @k98killer10 ай бұрын

    I do not see the point of the XState configuration using string names to index callbacks that could have just been passed as function pointers -- they are already effectively doing that with the "actions" object literal. Is this some specific issue with JavaScript garbage collection or is it a quirk of the library? (Genuinely curious about this. I've spent the past several years getting intimately familiar with Python and some mathematical stuff, and very recently learned Go, but I haven't been keeping up with EcmaScript for a few years.)

  • @covle9180
    @covle918010 ай бұрын

    I don't understand what a reducer adds when you already have a store. Granted i don't understand reducers at all, every time I've looked at them for state management they just seem like a great way to obfuscate control flow and add tons of boilerplate. The reason svelte is awesome is because all of that noise isn't really needed.

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    I only included a reducer example because there's always someone who equates it to a state machine when it's not the same.

  • @gabrieljose7041
    @gabrieljose704110 ай бұрын

    I totally agree with using state machines, but I personally don't like the way x-state works, and as you said, it's just an example of how it can be done, I would recommend the usage of the design pattern State and its variants, are so useful and don't need any library

  • @davidkhourshid4450

    @davidkhourshid4450

    10 ай бұрын

    What don't you like about it? (Creator here, would love suggestions to improve it)

  • @gabrieljose7041

    @gabrieljose7041

    10 ай бұрын

    ​@@davidkhourshid4450 its not something with the x-state itself, is more about the API usage, I don't like big and complex definitions using plain objects and properties. That's why I chose to say that I personally don't like it, because its not necessarily a problem

  • @ethernet764

    @ethernet764

    10 ай бұрын

    @@gabrieljose7041You don’t like that it’s declarative? You want it to be imperative instead?

  • @gabrieljose7041

    @gabrieljose7041

    10 ай бұрын

    @@ethernet764 no, it's just not the tool me for

  • @DefinitelyNotAMachineCultist
    @DefinitelyNotAMachineCultist7 ай бұрын

    🎯 Key Takeaways for quick navigation: 00:00 🚀 Introduction to State Management Issues - Introduction to the complexities of managing state in user interfaces, focusing on the problem of using booleans. - The example of a game is given, highlighting hidden complexities that could also apply to other UI elements like multi-step forms. 00:30 ❗ The Problem with Booleans - Explains the limitations of using booleans for state management, including how they can lead to impossible states. - Demonstrates a Svelte example using booleans to manage game states, showing the issues that can arise. 02:19 🎯 Good vs Bad Booleans - Differentiates between good and bad booleans, stating that good booleans are derived from state. - Provides examples where booleans might still be useful. 02:35 🔠 Enumerated Values to the Rescue - Introduces the concept of enumerated values (enums) for more explicit state management. - Shows how to replace booleans with enums in TypeScript, reducing errors and making the code less prone to impossible states. 03:49 🤖 State Machines as a Solution - Discusses the advantages of state machines in modeling complex state transitions. - Utilizes stately's visual editor to demonstrate a card game as a state machine. 05:27 💡 Implementing Reducers in Svelte - Describes how to implement a reducer pattern in Svelte, comparing it to state machines. - Provides code examples to create a custom `useReducer` hook in Svelte. 06:37 🛠 DIY Simple State Machine - Walks through creating a simple, event-driven state machine using Svelte. - Demonstrates how this approach eliminates the need for defensive programming. 08:56 🎛 Exploring XState -Discusses when to use and when not to use XState, a state machine library. - Demonstrates how to set up a state machine using XState, detailing actions, guards, and transitions. 11:32 🌟 Benefits and Conclusion - Summarizes the benefits of using state machines and enumerated values over booleans for state management. - Encourages the audience to avoid using booleans for representing complex state in their applications. 12:01 🎵 Outro - Thanks the viewers and invites them to like, subscribe, and join the Discord server. Made with HARPA AI

  • @BenRangel
    @BenRangel10 ай бұрын

    I often start out with an enum for State. Then realise some states aren't exclusive: if gameover plays a cutscene the user should also be able to pause. So end up doing a pause bool

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    You can have intermediary states.

  • @BenRangel

    @BenRangel

    10 ай бұрын

    @@JoyofCodeDev True. But I don't think most would know how to intuitively structure a list of states to show which stages are intermediary unless they're really into state machines Not saying it's super complicated but takes more thinking

  • @talkysassis
    @talkysassis10 ай бұрын

    Is it faster to execute?

  • @razt3757
    @razt375711 ай бұрын

    No, please don't. I'll be the first one to say I enjoy your channel, but please for the love of god don't promote state machine in Svelte. I understand this is not a Svelte tutorial, but at least explain the cons of state machines in general as well. The reality is that in a real world application nobody will bother to put the whole state in 1 single file much less type the state using string literals as types. This system quickly devolves into actions management, selectors and reducers, for the low low cost of useless mind fuck abstractions. It's a non zero cost abstraction that looks nice on paper which was meant to solve a series of problems in a declarative way for context free grammars. At least that's how they will introduce it to you in school or university. Yes it's useful in general. Yes there are better alternatives to state management. Which brings me back to Svelte. Reactive statements are already solving the state problem in a much better way. And there are some clever ways of using them without losing readability at all. If you really want to express your state in a more declarative way use derived stores or plain inline named functions invocations in reactive statements, instead of nesting your conditionals inside your reactive statements. And there are even more cons to state machines in UIs. It even encourages code duplication: Say for example you've been hired to build an application for a company. 6 months into the project you're being told the application will go open source but parts of it will remain proprietary, so you have to make an open source library and use it in the proprietary application. Guess what? Some of the proprietary state for some features will have not just extra things, some times the state will work differently, meaning a state refactory. What would logically need to be a feature enhancement will turn into a whole new component. If you're thinking about using this approach in your work application, do yourself a favor and build an Angular application with ngrx, throw in 50-ish containers/components and then admire the useless complexity. If you use state machines you will have many regrets, coming from someone using them everyday without the luxury of ditching them.

  • @RisalFajar

    @RisalFajar

    11 ай бұрын

    Thanks, it's good to have different opinions.

  • @Mark-wz9uh

    @Mark-wz9uh

    10 ай бұрын

    This is a classical example of overengineering for no benefit. Especially with 4 states: See how the enum solution took the least time to implement (the video segment is very short) and compare it with the later parts. Also it's readable/obvioius code, you don't have to be a genius & it's easy to change.

  • @AlainPilon
    @AlainPilon10 ай бұрын

    State Machines are not the holy grail of state management. I my experience, they work great when you have complete control over the business rules around how the object can switch between states. But as soon as you hit the real world, it often happen that new states keep popping up or the business rules surrounding the associated events change/complexify to the point where you have to by pass the validation/events completely. This is why I am now using enums in most cases and move the validation/state switching into a service object.

  • @kassios

    @kassios

    10 ай бұрын

    In real world applications where complexity only increases and new features creep in, a Finite State Machine is the only way of keeping track explicitly of the flow of the application and safely add new functionality by extending the finite states of the app.

  • @ninetysixvoid
    @ninetysixvoid10 ай бұрын

    just use bytes, it is more resource efficient: 0: Game Over 1: Playing 2: Paused

  • @lucafabbian269

    @lucafabbian269

    8 ай бұрын

    premature optimization, can't think of a scenario where it really matters. Moreover, in typescript enums are automatically transpiled into integers.

  • @scorpo999
    @scorpo99910 ай бұрын

    types as state *mind blown*

  • @bledlbledlbledl
    @bledlbledlbledl10 ай бұрын

    the diagram thing reminded me of "goto"

  • @user-on2rx4si7g
    @user-on2rx4si7g10 ай бұрын

    Any new drops ☔❤

  • @ukrainetoday960
    @ukrainetoday9608 ай бұрын

    In short video about svelte useReducer or redux patatern was better than svelte useState, by author opinion

  • @TECHN01200
    @TECHN0120011 ай бұрын

    On top of booleans being bad for the developer if you have tons of them, they are also bad for the computer. Every boolean in every major programming language takes up a whole byte for a simple true/false value. A byte should be able to hold 8 of these. On the other hand, using enums like bit flags enables you to do just that. Not only that, you can also set them up to manage mutually exclusive states by using more bits for certain enum values. A C# example might look like: public enum foo : byte { NONE_STATE = 0, BOOL_STATE_0 = 1, BOOL_STATE_1 = 2, BOOL_STATE_2 = 4, BOOL_STATE_3 = 8, EXCLUSIVE_STATE_0 = 16, EXCLUSIVE_STATE_1 = 32, EXCLUSIVE_STATE_2 = 48, ... } It is amazing how much information you can stuff into a byte if you just try.

  • @TheNewton

    @TheNewton

    10 ай бұрын

    ". Not only that, you can also set them up to manage mutually exclusive states by using more bits for certain enum values." Can you elaborate on that?

  • @TECHN01200

    @TECHN01200

    10 ай бұрын

    @@TheNewton If you have 4 states that are mutually exclusive, you can use 2 bits of your enum as 2 bits contain 4 states, 00, 01, 10 and 11. If 4 states that each take 2 bits in the same location of your byte or enum, they are then mutually exclusive as only one of those states can exist at any one time.

  • @skyemegakitty

    @skyemegakitty

    10 ай бұрын

    Premature optimization. If you're to the point where you need to fiddle with variables at the byte or bit level, especially considering modern processors have a wordsize of 64 bits and you won't see any benefit from picking one way or the other below this threshold, then your program has more fundamental problems. In many languages, the compiler is going to know better than you whats better anyways.

  • @marschma

    @marschma

    10 ай бұрын

    Agreed. If theres a bottleneck, its probably not having 12 bools. Not worth using bitmasks for the effort it takes. Rather just build the feature and then afterwards inspect what the actual bottleneck is instead of guessing prematurely

  • @DF-wl8nj

    @DF-wl8nj

    10 ай бұрын

    One thing no one has pointed out, as someone who does a lot of work with non-developers it is WAY easier to explain a state machine when state transitions can be easily and clearly modeled as switching between enumerations of a few strings (or ints mapped to strings) rather then this obscure series of changing Boolean values.

  • @SEOTADEO
    @SEOTADEO10 ай бұрын

    As a Rust dev I can stick with enums :)

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    You use Rust by the way?

  • @ratonespotnes
    @ratonespotnes11 ай бұрын

    There's an even worse way to manage states, using bit masks and bit flags. For example, the number 2 in binary is 10 and so you can use (value & 0x02)

  • @GuilhermeNeubaner

    @GuilhermeNeubaner

    10 ай бұрын

    Not sure how this `if (flags & PLAYING) {}` is not readable. Other operations are also readable: `flags |= PLAYING | INVINCIBLE`: Set the PLAYING and INVINCIBLE flag. `flags = GAMEOVER`: "Clear" alls other flags and set the GAMEOVER flag. `flags &= PAUSED`: Keep the PAUSED flag as is but clear all other flags. Using bit flags for PLAYING, PAUSED and GAMEOVER doesn't make sense since they are exclusive states. But for other use cases bit flags are extremely powerful.

  • @bledlbledlbledl

    @bledlbledlbledl

    10 ай бұрын

    That sounds like the "status word" (bitfield) in many types of industrial equipment

  • @vanjazed7021

    @vanjazed7021

    10 ай бұрын

    You could just properly name your bit masks and use them like everyone did without issues for decades

  • @barongello

    @barongello

    6 ай бұрын

    Your expression extracts a "boolean" only because any non-zero value is usually handled as true. And, for that, you don't even need to shift left, just bitwise and the value and the mask Why are you multiplying 0 or 2 by 4? Do you really want to end up with 0 or 8?

  • @jamescobban857
    @jamescobban85710 ай бұрын

    The cheapest aspect of modern computers is memory. Using enumerated States is MUCH faster to execute even if it requires duplicated code. Moreover most compilers (although not Javascript) permit you to write the code once as a function, and then the compiler will replace all calls to that function with the code itself when you tell the compiler to optimize for time at the cost of increased storage. This also makes the code easier to design, debug and maintain.

  • @MahdiyDev
    @MahdiyDev10 ай бұрын

    Remember strings are expensive

  • @nomoredarts8918
    @nomoredarts891810 ай бұрын

    Solution how this should be implemented from the start is in here - 2:48

  • @trejohnson7677
    @trejohnson767710 ай бұрын

    Ah yes edit events is always the final frontier.

  • @Burnrate
    @Burnrate10 ай бұрын

    I feel like this video implies that games are made in rust lol

  • @Pecgbr
    @Pecgbr10 ай бұрын

    Mas que feira

  • @hiraginoyuki
    @hiraginoyuki10 ай бұрын

    aren't there 8 states (2³)?

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    Yes, I'm bad at math.

  • @Hemigoblin
    @Hemigoblin10 ай бұрын

    State machines are great. “let” is a footgun.

  • @lucafabbian269
    @lucafabbian2698 ай бұрын

    A tutorial about how to turn a simple and readable code in a hell to refactor, and something that is against the Svelte philosophy.

  • @JoyofCodeDev

    @JoyofCodeDev

    8 ай бұрын

    I didn't know you wrote the Svelte philosophy.

  • @jenil430
    @jenil43010 ай бұрын

    forget states and shi* man, svelte is sexy.

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    True.

  • @SXsoft99
    @SXsoft999 ай бұрын

    the truth of the matter is "it depends on the project"

  • @twitchizle
    @twitchizle11 ай бұрын

    you tracking my activities? huh?

  • @barongello
    @barongello6 ай бұрын

    Clicked out of curiosity because I NEVER saw someone using booleans to control state machines (of course, with more than 2 states) But ended up not watching the entire video due to a silly mistake at the start that made me lose the interest: 3 boolean variables don't give you 6 possibilities, but 8 Not complaining, just pointing out that things like that make people drop out

  • @JoyofCodeDev

    @JoyofCodeDev

    6 ай бұрын

    It's okay.

  • @imxd9698
    @imxd969810 ай бұрын

    xstate gets hairy VERY quickly when you need to do more complex things.

  • @kassios

    @kassios

    10 ай бұрын

    I find quite the opposite. xState is the only thing that scales with complexity. Refactoring flow with xState is a lot easier too, since the React representation is clearly separated from the logic.

  • @yaroslavpanych2067
    @yaroslavpanych206710 ай бұрын

    If you didn't know anything in this video , you should go back to school immediately, and I better not find your code outthere in production! Really guys, this is not just basics, it is basics of basics. Anything more complex than hello world is one way or another uses state machine.. and if you have 2 bools, 95% chance you will be better replacing them with enum, for 3 or more bools- 100% replace them!

  • @AexisRai
    @AexisRai10 ай бұрын

    no 👍

  • @8koi245
    @8koi24510 ай бұрын

    why am I getting svelte content? smh loo

  • @KangJangkrik
    @KangJangkrik10 ай бұрын

    Blindly replacing boolean with string enum is a bad advice. Do whatever looks good for your code because whatever optimization you do, javascript still a high-level language. You want more optimization? Do that in Rust, or even better with non-plusplus C, or perhaps assembly if u dare enough.

  • @k98killer
    @k98killer10 ай бұрын

    Ngl, the functional paradigm feels like a bastardization of JavaScript -- JS was not designed to be a functional language -- it was barely designed at all, but the design work that did go into it made it object-oriented. The big thing back in the day was to use the prototype system to build systems of inheritance using the "function" keyword as a stand-in for "class" because whether a function call was a function call or an object instantiation was determined by the respective lack or presence of the "new" keyword. This modern JS code looks like a different language entirely at times, with very unclear relationships between things sometimes -- you just need a mental map to follow invisible lines that are often visible in other languages/paradigms -- it's very difficult to reason about a modern piece of JS code without finding some relevant documentation somewhere.

  • @Danielo515
    @Danielo5154 ай бұрын

    Your game machine has a lot of unhandled cases

  • @JorgetePanete
    @JorgetePanete10 ай бұрын

    you could have used a good language

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    Svelte is the best language.

  • @Envengerx
    @Envengerx10 ай бұрын

    Xstate code is plain ugly.

  • @JoyofCodeDev

    @JoyofCodeDev

    10 ай бұрын

    You should see the code I write.

  • @Darkspawn6666
    @Darkspawn666610 ай бұрын

    Insert 'Jump on Rake Meme' template, stop it, get some help.

  • @gishee18
    @gishee1811 ай бұрын

    json programming. Tom is a GENIUS