Do This Instead Of Representing State With Booleans

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 ธ.ค. 2024

ความคิดเห็น • 162

  • @JoyofCodeDev
    @JoyofCodeDev  ปีที่แล้ว +1

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

  • @lm5050
    @lm5050 ปีที่แล้ว +24

    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 ปีที่แล้ว +28

    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 ปีที่แล้ว

      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 ปีที่แล้ว +196

    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 ปีที่แล้ว +7

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

    • @lukekurlandski7653
      @lukekurlandski7653 ปีที่แล้ว +11

      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 ปีที่แล้ว +12

      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 ปีที่แล้ว +2

      @@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 ปีที่แล้ว +8

      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
    @alexismandelias ปีที่แล้ว +6

    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  ปีที่แล้ว +1

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

  • @AK-vx4dy
    @AK-vx4dy ปีที่แล้ว +6

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

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว +3

      I'm bad at math.

    • @AK-vx4dy
      @AK-vx4dy ปีที่แล้ว +2

      @@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 !!!

  • @AetherMomon
    @AetherMomon ปีที่แล้ว +44

    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 ปีที่แล้ว +5

      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 ปีที่แล้ว +2

      ​@@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 ปีที่แล้ว +4

    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  ปีที่แล้ว +1

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

  • @zachmanifold
    @zachmanifold ปีที่แล้ว +22

    (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 ปีที่แล้ว +3

      This helps saving memory too. Very good for embedded systems

    • @ImperiumLibertas
      @ImperiumLibertas ปีที่แล้ว

      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 ปีที่แล้ว

      @@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 ปีที่แล้ว

      @@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

  • @ibrahimkoz1983
    @ibrahimkoz1983 ปีที่แล้ว +14

    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 ปีที่แล้ว

      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 ปีที่แล้ว

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

    • @askeladden450
      @askeladden450 ปีที่แล้ว

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

    • @ToJak91
      @ToJak91 9 หลายเดือนก่อน

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

  • @DefinitelyNotAMachineCultist
    @DefinitelyNotAMachineCultist ปีที่แล้ว

    🎯 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

  • @br3nto
    @br3nto ปีที่แล้ว +3

    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 ปีที่แล้ว +1

      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 ปีที่แล้ว +24

    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  ปีที่แล้ว +9

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

    • @redumptious2544
      @redumptious2544 ปีที่แล้ว +1

      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 ปีที่แล้ว

      @@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.

  • @asatorftw
    @asatorftw ปีที่แล้ว

    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

  • @francopascual6958
    @francopascual6958 ปีที่แล้ว +3

    Clean video, liking this format!

  • @jsvrs
    @jsvrs ปีที่แล้ว +3

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

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว +4

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

  • @amaraw9893
    @amaraw9893 ปีที่แล้ว +6

    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 ปีที่แล้ว

      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 ปีที่แล้ว +1

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

    • @amaraw9893
      @amaraw9893 ปีที่แล้ว

      @@SEOTADEO 😅 i use em interchangeably

    • @amaraw9893
      @amaraw9893 ปีที่แล้ว

      @@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 ปีที่แล้ว

    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.

  • @alfredlotsu950
    @alfredlotsu950 ปีที่แล้ว +1

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

  • @kmemz
    @kmemz ปีที่แล้ว

    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.

  • @AlainPilon
    @AlainPilon ปีที่แล้ว +4

    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 ปีที่แล้ว +4

      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.

  • @ahasdasetodu6304
    @ahasdasetodu6304 ปีที่แล้ว

    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.

  • @softgripper
    @softgripper ปีที่แล้ว +2

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

  • @kirillvoloshin2065
    @kirillvoloshin2065 ปีที่แล้ว +3

    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

  • @fredbcruz
    @fredbcruz ปีที่แล้ว

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

  • @erickmoya1401
    @erickmoya1401 ปีที่แล้ว

    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

  • @elatedbento
    @elatedbento ปีที่แล้ว

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

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว

      I use Animotion: th-cam.com/video/dBfZjv-lt2k/w-d-xo.html.

  • @ninetysixvoid
    @ninetysixvoid ปีที่แล้ว +2

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

    • @lucafabbian269
      @lucafabbian269 ปีที่แล้ว +1

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

  • @doxologist
    @doxologist ปีที่แล้ว +2

    Awesome video!
    What theme do u use?

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว +3

      joyofcode.xyz/uses

    • @doxologist
      @doxologist ปีที่แล้ว

      @@JoyofCodeDev damn you're so organised. Thanks

  • @detaaditya6237
    @detaaditya6237 ปีที่แล้ว +6

    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

  • @bjul
    @bjul ปีที่แล้ว +1

    You're da bomb! Thanks.

  • @Der_Yoloist
    @Der_Yoloist ปีที่แล้ว

    this got from simple math to rocket science pretty quick

  • @razt3757
    @razt3757 ปีที่แล้ว +21

    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 ปีที่แล้ว +2

      Thanks, it's good to have different opinions.

    • @Mark-wz9uh
      @Mark-wz9uh ปีที่แล้ว +1

      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.

  • @Metruzanca
    @Metruzanca ปีที่แล้ว

    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

  • @yash1152
    @yash1152 ปีที่แล้ว

    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  ปีที่แล้ว +1

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

    • @yash1152
      @yash1152 ปีที่แล้ว

      @@JoyofCodeDev awesome +1

  • @k98killer
    @k98killer ปีที่แล้ว

    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?

  • @markcahalan5698
    @markcahalan5698 ปีที่แล้ว

    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

  • @TECHN01200
    @TECHN01200 ปีที่แล้ว +6

    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 ปีที่แล้ว

      ". 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 ปีที่แล้ว

      @@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 ปีที่แล้ว +7

      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 ปีที่แล้ว +1

      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 ปีที่แล้ว +3

      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.

  • @jsonkody
    @jsonkody ปีที่แล้ว

    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 ... 🤣🤣🤣

  • @allendover7480
    @allendover7480 ปีที่แล้ว

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

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว +1

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

    • @allendover7480
      @allendover7480 ปีที่แล้ว

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

  • @covle9180
    @covle9180 ปีที่แล้ว

    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  ปีที่แล้ว

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

  • @rogue.ganker
    @rogue.ganker ปีที่แล้ว

    Very well done!

  • @MahdiyDev
    @MahdiyDev ปีที่แล้ว +2

    Remember strings are expensive

  • @gabrieljose7041
    @gabrieljose7041 ปีที่แล้ว

    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

    • @davidkpiano
      @davidkpiano ปีที่แล้ว +2

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

    • @gabrieljose7041
      @gabrieljose7041 ปีที่แล้ว

      ​@@davidkpiano 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 ปีที่แล้ว +1

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

    • @gabrieljose7041
      @gabrieljose7041 ปีที่แล้ว

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

  • @mz00956
    @mz00956 ปีที่แล้ว

    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?

  • @DanielCarvalho2
    @DanielCarvalho2 ปีที่แล้ว

    i love your videos, thank you! :)

  • @acharafranklyn5167
    @acharafranklyn5167 ปีที่แล้ว

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

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว

      I included some resources in the description.

  • @dane4ka474
    @dane4ka474 ปีที่แล้ว

    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)

  • @ste-fa-no
    @ste-fa-no ปีที่แล้ว

    Great content! 👏

  • @nomoredarts8918
    @nomoredarts8918 ปีที่แล้ว

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

  • @k98killer
    @k98killer ปีที่แล้ว

    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.)

  • @talkysassis
    @talkysassis ปีที่แล้ว

    Is it faster to execute?

  • @BenRangel
    @BenRangel ปีที่แล้ว

    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  ปีที่แล้ว

      You can have intermediary states.

    • @BenRangel
      @BenRangel ปีที่แล้ว

      @@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

  • @Burnrate
    @Burnrate ปีที่แล้ว +2

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

  • @jamescobban857
    @jamescobban857 ปีที่แล้ว +4

    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.

  • @TheFoxstory
    @TheFoxstory ปีที่แล้ว

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

  • @ratonespotnes
    @ratonespotnes ปีที่แล้ว +5

    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 ปีที่แล้ว +11

      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 ปีที่แล้ว

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

    • @vanjazed7021
      @vanjazed7021 ปีที่แล้ว +2

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

    • @barongello
      @barongello ปีที่แล้ว

      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?

  • @lucafabbian269
    @lucafabbian269 ปีที่แล้ว +1

    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  ปีที่แล้ว

      I didn't know you wrote the Svelte philosophy.

  • @zhanezar
    @zhanezar ปีที่แล้ว

    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  ปีที่แล้ว

      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 ปีที่แล้ว

      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 ปีที่แล้ว

      @@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.

  • @bledlbledlbledl
    @bledlbledlbledl ปีที่แล้ว +1

    the diagram thing reminded me of "goto"

  • @ukrainetoday960
    @ukrainetoday960 ปีที่แล้ว

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

  • @good-dev-student
    @good-dev-student ปีที่แล้ว

    Any new drops ☔❤

  • @good-dev-student
    @good-dev-student ปีที่แล้ว

    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
    @eastcoastpizza784 ปีที่แล้ว

    Wow ! 👍👍

  • @MikeNugget
    @MikeNugget ปีที่แล้ว

    Nice.

  • @SEOTADEO
    @SEOTADEO ปีที่แล้ว

    As a Rust dev I can stick with enums :)

  • @scorpo999
    @scorpo999 ปีที่แล้ว

    types as state *mind blown*

  • @hiraginoyuki
    @hiraginoyuki ปีที่แล้ว +1

    aren't there 8 states (2³)?

  • @Hemigoblin
    @Hemigoblin ปีที่แล้ว

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

  • @SXsoft99
    @SXsoft99 ปีที่แล้ว

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

  • @trejohnson7677
    @trejohnson7677 ปีที่แล้ว

    Ah yes edit events is always the final frontier.

  • @barongello
    @barongello ปีที่แล้ว

    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

  • @twitchizle
    @twitchizle ปีที่แล้ว +1

    you tracking my activities? huh?

  • @yaroslavpanych2067
    @yaroslavpanych2067 ปีที่แล้ว

    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!

  • @jenil430
    @jenil430 ปีที่แล้ว +1

    forget states and shi* man, svelte is sexy.

  • @imxd9698
    @imxd9698 ปีที่แล้ว

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

    • @kassios
      @kassios ปีที่แล้ว

      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.

  • @k98killer
    @k98killer ปีที่แล้ว

    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.

  • @KangJangkrik
    @KangJangkrik ปีที่แล้ว +1

    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.

  • @AexisRai
    @AexisRai ปีที่แล้ว

    no 👍

  • @Danielo515
    @Danielo515 10 หลายเดือนก่อน

    Your game machine has a lot of unhandled cases

  • @Pecgbr
    @Pecgbr ปีที่แล้ว

    Mas que feira

  • @8koi245
    @8koi245 ปีที่แล้ว

    why am I getting svelte content? smh loo

  • @JorgetePanete
    @JorgetePanete ปีที่แล้ว

    you could have used a good language

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว

      Svelte is the best language.

  • @Envengerx
    @Envengerx ปีที่แล้ว

    Xstate code is plain ugly.

    • @JoyofCodeDev
      @JoyofCodeDev  ปีที่แล้ว

      You should see the code I write.

  • @gishee18
    @gishee18 ปีที่แล้ว +1

    json programming. Tom is a GENIUS

  • @Darkspawn6666
    @Darkspawn6666 ปีที่แล้ว

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