Do This Instead Of Representing State With Booleans

  Переглядів 113,400

Joy of Code

Joy of Code

День тому

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
▶️ UKposts 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
@JoyofCodeDev 10 місяців тому
🔴 Patreon: www.patreon.com/joyofcode 💬 Discord: joyofcode.xyz/invite
@lm5050
@lm5050 9 місяців тому
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
@cyrusol 9 місяців тому
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 9 місяців тому
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.
@IvanKleshnin
@IvanKleshnin 9 місяців тому
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 9 місяців тому
I totally agree with you, but I feel like a lot of react/other js web framework like using JSON-like code
@lukekurlandski7653
@lukekurlandski7653 9 місяців тому
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 9 місяців тому
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 9 місяців тому
@@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 9 місяців тому
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.
@AetherMomon
@AetherMomon 9 місяців тому
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 9 місяців тому
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 8 місяців тому
​@@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 ;-;.
@smithrockford-dv1nb
@smithrockford-dv1nb 9 місяців тому
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 9 місяців тому
I also didn't understand it when I used it to be honest. 😂
@ibrahimkoz1983
@ibrahimkoz1983 9 місяців тому
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 9 місяців тому
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 9 місяців тому
​@@pedrokalil4410I've never seen a university teach state machine
@askeladden450
@askeladden450 9 місяців тому
​@@andreilucasgoncalves1416its part of an automata course in most universities
@ToJak91
@ToJak91 2 місяці тому
We were taught state famines.. But that was in a version of Java, which couldn't handle switch on strings..
@francopascual6958
@francopascual6958 10 місяців тому
Clean video, liking this format!
@kirillvoloshin2065
@kirillvoloshin2065 9 місяців тому
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
@asatorftw 8 місяців тому
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
@alexismandelias
@alexismandelias 9 місяців тому
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 9 місяців тому
I only show the reducer example because people conflate them when they're not the same and I never use it.
@fredbcruz
@fredbcruz 9 місяців тому
Thank you! just stumbled in exact this problem coding a simple snake game on svelte
@JoseWaldier
@JoseWaldier 9 місяців тому
Underrated Channel. Keep it up bro. You'll grow fast Q: how do you edit your videos with those effect?
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
It's made with Svelte and I plan to release it when it's ready. 🙂
@alfredlotsu950
@alfredlotsu950 9 місяців тому
At 1:01 I would have personally set playing = !gameOver, to prevent that impossible state, but great tutorial overall! Subbed!
@amaraw9893
@amaraw9893 9 місяців тому
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 9 місяців тому
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 9 місяців тому
Hahahaha this is the first time I have heard someone refering to children as kids (in programming). But good point.
@amaraw9893
@amaraw9893 9 місяців тому
@@SEOTADEO 😅 i use em interchangeably
@amaraw9893
@amaraw9893 9 місяців тому
@@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).
@KorhalKk
@KorhalKk 8 місяців тому
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.
@Der_Yoloist
@Der_Yoloist 8 місяців тому
this got from simple math to rocket science pretty quick
@zachmanifold
@zachmanifold 9 місяців тому
(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 9 місяців тому
This helps saving memory too. Very good for embedded systems
@ImperiumLibertas
@ImperiumLibertas 9 місяців тому
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 9 місяців тому
@@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 9 місяців тому
@@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
@bjul
@bjul 10 місяців тому
You're da bomb! Thanks.
@ahasdasetodu6304
@ahasdasetodu6304 9 місяців тому
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.
@AK-vx4dy
@AK-vx4dy 9 місяців тому
@0:57 there are 8(eight) possible states on 3 booleans 2^3 2**3
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
I'm bad at math.
@AK-vx4dy
@AK-vx4dy 9 місяців тому
@@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 !!!
@br3nto
@br3nto 9 місяців тому
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 9 місяців тому
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.
@idktbh4004
@idktbh4004 10 місяців тому
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 10 місяців тому
Local constants were added a while ago: svelte.dev/docs/special-tags#const.
@redumptious2544
@redumptious2544 9 місяців тому
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 9 місяців тому
@@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.
@rogue.ganker
@rogue.ganker 9 місяців тому
Very well done!
@ste-fa-no
@ste-fa-no 10 місяців тому
Great content! 👏
@NedCollyer
@NedCollyer 10 місяців тому
I miss my "Hey friends" :) Thanks for the vids.
@elatedbento
@elatedbento 9 місяців тому
The video quality is absolutely awesome. Is there a tool that you use? Fantastic content.
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
I use Animotion: ukposts.info/have/v-deo/nHKXjqCtZKKlk58.html.
@markcahalan5698
@markcahalan5698 8 місяців тому
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
@detaaditya6237
@detaaditya6237 9 місяців тому
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
@yash1152
@yash1152 8 місяців тому
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 7 місяців тому
I use Animotion which is a presentational framework I made for creating educational content at animotion.pages.dev/.
@yash1152
@yash1152 7 місяців тому
@@JoyofCodeDev awesome +1
@talkysassis
@talkysassis 9 місяців тому
Is it faster to execute?
@zhanezar
@zhanezar 10 місяців тому
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 10 місяців тому
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 10 місяців тому
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 9 місяців тому
@@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.
@k98killer
@k98killer 9 місяців тому
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.)
@igeoerre
@igeoerre 8 місяців тому
I was following until I got to the state machine part things got too abstract, but the explanation is very good, thanks.
@kmemz
@kmemz 7 місяців тому
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.
@doxologist
@doxologist 10 місяців тому
Awesome video! What theme do u use?
@JoyofCodeDev
@JoyofCodeDev 10 місяців тому
joyofcode.xyz/uses
@doxologist
@doxologist 10 місяців тому
@@JoyofCodeDev damn you're so organised. Thanks
@dane4ka474
@dane4ka474 9 місяців тому
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)
@acharafranklyn5167
@acharafranklyn5167 7 місяців тому
please is there a blog or an article i can go read about this more
@JoyofCodeDev
@JoyofCodeDev 7 місяців тому
I included some resources in the description.
@razt3757
@razt3757 10 місяців тому
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 10 місяців тому
Thanks, it's good to have different opinions.
@Mark-wz9uh
@Mark-wz9uh 9 місяців тому
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.
@allendover7480
@allendover7480 7 місяців тому
How do you get === and => to look like they do? That's a nice touch.
@JoyofCodeDev
@JoyofCodeDev 7 місяців тому
Make sure your font supports font ligatures and enable them in your editor.
@allendover7480
@allendover7480 7 місяців тому
​@@JoyofCodeDev That looks so elegant. Thanks for the answer!
@erickmoya1401
@erickmoya1401 7 місяців тому
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 7 місяців тому
It's me! 😄
@TheFoxstory
@TheFoxstory 9 місяців тому
love your videos man! are you going to do a pocketbase auth crud app tutorial anytime?
@jsonkody
@jsonkody 8 місяців тому
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 ... 🤣🤣🤣
@k98killer
@k98killer 9 місяців тому
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?
@DanielCarvalho2
@DanielCarvalho2 8 місяців тому
i love your videos, thank you! :)
@JoyofCodeDev
@JoyofCodeDev 8 місяців тому
My pleasure! 😄
@BenRangel
@BenRangel 9 місяців тому
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 9 місяців тому
You can have intermediary states.
@BenRangel
@BenRangel 9 місяців тому
@@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
@mz00956
@mz00956 9 місяців тому
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 9 місяців тому
It's just an example.
@gabrieljose7041
@gabrieljose7041 9 місяців тому
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 9 місяців тому
What don't you like about it? (Creator here, would love suggestions to improve it)
@gabrieljose7041
@gabrieljose7041 9 місяців тому
​@@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 9 місяців тому
@@gabrieljose7041You don’t like that it’s declarative? You want it to be imperative instead?
@gabrieljose7041
@gabrieljose7041 9 місяців тому
@@ethernet764 no, it's just not the tool me for
@user-on2rx4si7g
@user-on2rx4si7g 9 місяців тому
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! 🙌😊 ❤❤
@MikeNugget
@MikeNugget 9 місяців тому
Nice.
@ukrainetoday960
@ukrainetoday960 7 місяців тому
In short video about svelte useReducer or redux patatern was better than svelte useState, by author opinion
@nomoredarts8918
@nomoredarts8918 9 місяців тому
Solution how this should be implemented from the start is in here - 2:48
@Metruzanca
@Metruzanca 9 місяців тому
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
@DefinitelyNotAMachineCultist
@DefinitelyNotAMachineCultist 6 місяців тому
🎯 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
@eastcoastpizza784
@eastcoastpizza784 9 місяців тому
Wow ! 👍👍
@AlainPilon
@AlainPilon 9 місяців тому
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 9 місяців тому
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.
@09lilkiller
@09lilkiller 9 місяців тому
I usually never comment or like videos. But this was very well done.
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
Thank you! 😄
@covle9180
@covle9180 9 місяців тому
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 9 місяців тому
I only included a reducer example because there's always someone who equates it to a state machine when it's not the same.
@bledlbledlbledl
@bledlbledlbledl 9 місяців тому
the diagram thing reminded me of "goto"
@ninetysixvoid
@ninetysixvoid 9 місяців тому
just use bytes, it is more resource efficient: 0: Game Over 1: Playing 2: Paused
@lucafabbian269
@lucafabbian269 7 місяців тому
premature optimization, can't think of a scenario where it really matters. Moreover, in typescript enums are automatically transpiled into integers.
@user-on2rx4si7g
@user-on2rx4si7g 9 місяців тому
Any new drops ☔❤
@jamescobban857
@jamescobban857 9 місяців тому
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
@MahdiyDev 9 місяців тому
Remember strings are expensive
@lucafabbian269
@lucafabbian269 7 місяців тому
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 7 місяців тому
I didn't know you wrote the Svelte philosophy.
@scorpo999
@scorpo999 9 місяців тому
types as state *mind blown*
@TECHN01200
@TECHN01200 9 місяців тому
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 9 місяців тому
". 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 9 місяців тому
@@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 9 місяців тому
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 9 місяців тому
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 9 місяців тому
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.
@hiraginoyuki
@hiraginoyuki 9 місяців тому
aren't there 8 states (2³)?
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
Yes, I'm bad at math.
@ratonespotnes
@ratonespotnes 9 місяців тому
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 9 місяців тому
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 9 місяців тому
That sounds like the "status word" (bitfield) in many types of industrial equipment
@vanjazed7021
@vanjazed7021 9 місяців тому
You could just properly name your bit masks and use them like everyone did without issues for decades
@barongello
@barongello 5 місяців тому
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?
@Burnrate
@Burnrate 9 місяців тому
I feel like this video implies that games are made in rust lol
@SXsoft99
@SXsoft99 8 місяців тому
the truth of the matter is "it depends on the project"
@SEOTADEO
@SEOTADEO 9 місяців тому
As a Rust dev I can stick with enums :)
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
You use Rust by the way?
@Hemigoblin
@Hemigoblin 9 місяців тому
State machines are great. “let” is a footgun.
@trejohnson7677
@trejohnson7677 9 місяців тому
Ah yes edit events is always the final frontier.
@Pecgbr
@Pecgbr 9 місяців тому
Mas que feira
@k98killer
@k98killer 9 місяців тому
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.
@yaroslavpanych2067
@yaroslavpanych2067 9 місяців тому
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!
@barongello
@barongello 5 місяців тому
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 5 місяців тому
It's okay.
@jenil430
@jenil430 9 місяців тому
forget states and shi* man, svelte is sexy.
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
True.
@twitchizle
@twitchizle 9 місяців тому
you tracking my activities? huh?
@AexisRai
@AexisRai 9 місяців тому
no 👍
@imxd9698
@imxd9698 9 місяців тому
xstate gets hairy VERY quickly when you need to do more complex things.
@kassios
@kassios 9 місяців тому
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.
@KangJangkrik
@KangJangkrik 9 місяців тому
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.
@Danielo515
@Danielo515 3 місяці тому
Your game machine has a lot of unhandled cases
@8koi245
@8koi245 9 місяців тому
why am I getting svelte content? smh loo
@JorgetePanete
@JorgetePanete 9 місяців тому
you could have used a good language
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
Svelte is the best language.
@Envengerx
@Envengerx 9 місяців тому
Xstate code is plain ugly.
@JoyofCodeDev
@JoyofCodeDev 9 місяців тому
You should see the code I write.
@Darkspawn6666
@Darkspawn6666 9 місяців тому
Insert 'Jump on Rake Meme' template, stop it, get some help.
@gishee18
@gishee18 9 місяців тому
json programming. Tom is a GENIUS
Introducing Animotion: Visualize Ideas With Code
5:31
Joy of Code
Переглядів 47 тис.
Why You Shouldn't Nest Your Code
8:30
CodeAesthetic
Переглядів 2,5 млн
Анна Трінчер - Бар за баром (Official Music Video)
02:38
Анна Трінчер
Переглядів 1,9 млн
КАК ГЛОТАЮТ ШПАГУ?😳
00:33
Masomka
Переглядів 2,1 млн
You might not need useEffect() ...
21:45
Academind
Переглядів 121 тис.
How Senior Programmers ACTUALLY Write Code
13:37
Healthy Software Developer
Переглядів 1,2 млн
Naming Things in Code
7:25
CodeAesthetic
Переглядів 1,9 млн
How To Not Suck At Design For Developers
14:23
Joy of Code
Переглядів 74 тис.
So You Think You Know Git - FOSDEM 2024
47:00
GitButler
Переглядів 884 тис.
Never install locally
5:45
Coderized
Переглядів 1,5 млн
Computers Without Memory - Computerphile
8:52
Computerphile
Переглядів 333 тис.