Это видео недоступно.
Сожалеем об этом.

Switch Statement Alternative

Поделиться
HTML-код
  • Опубликовано: 1 окт 2023
  • To simplify switch statements using an object literal technique, you can create an object where the keys represent the cases you want to handle, and the values are functions that should be executed for each case.
    Here's a step-by-step guide on how to replace switch statements using an object literal technique:
    Define an object where the keys correspond to the cases you want to handle.
    For each key (case), assign a function or value that should be executed or returned when that case is encountered.
    Instead of using a switch statement, you can use the object to look up and execute the appropriate function based on the case.
    Here's an example:
    // Traditional switch statement
    function processFruit(fruit) {
    switch (fruit) {
    case "apple":
    return "A fruit that is red or green.";
    case "banana":
    return "A fruit that is yellow.";
    case "orange":
    return "A fruit that is orange.";
    default:
    return "Unknown fruit.";
    }
    }
    // Object literal
    const fruitInfo = {
    apple: "A fruit that is red or green.",
    banana: "A fruit that is yellow.",
    orange: "A fruit that is orange.",
    default: "Unknown fruit.",
    };
    function processFruit(fruit) {
    // Use the object literal to look up the information
    return fruitInfo[fruit] || fruitInfo.default;
    }
    console.log(processFruit("apple")); // Output: "A fruit that is red or green."
    console.log(processFruit("grape")); // Output: "Unknown fruit."
    #FlutterMapp
    #Flutter
    #coding

Комментарии • 709

  • @FlutterMapp
    @FlutterMapp  9 месяцев назад +131

    Wow, the comments are so harsh. Programmers can be quite unpredictable, but I love it!
    Use code 'CommentsAreSavage' to get 75% OFF. At the end of the course, you will be able to build your own mobile apps with Flutter: courses.fluttermapp.com/p/flutter-for-beginners?coupon_code=COMMENTSARESAVAGE

    • @scalex1882
      @scalex1882 8 месяцев назад +45

      I rarely comment but wanted to let you know the comments under this short are absolutely correct. Please make content about things you have experience with, this video is completely useless.

    • @papa15891
      @papa15891 7 месяцев назад

      + this is dumb

    • @MrRizzyWizzy
      @MrRizzyWizzy 7 месяцев назад +7

      That's because you are telling people to do something instead of how something works.

    • @gobi-wan-chess
      @gobi-wan-chess 7 месяцев назад +2

      La légende dit qu'on pouvait entendre son accent jusque dans la baie d'Hudson

    • @zero11010
      @zero11010 6 месяцев назад

      The comments were extremely harsh. I’ve worked in tech for about 20 years. The amount of “nerd sniping” in here is hilarious. It makes me want to run from user to user, beat them up, and collect their lunch money (just jokes).
      You showed another way to do something. It wasn’t optimal, but in some situations it’s reasonable to do a less than optimal solution . Depends on how much things are being called. It isn’t a good path for a scaling solution, but that’s ok.
      Even bubble sort exists for a reason and has a place.
      I think in this case defining the map outside of the function, so the map isn’t being created from scratch each time this is being called would help. I’d prefer a more descriptive name, too.
      This solution path is very easy to read, and it’s very easy to update as figures change. Updating switches and if/if else chains can be cumbersome and prone to human error.
      Abstracting out “magic numbers” like caffeine mgs into a single source so all instances globally are changed at once would make me feel more confident.
      But, for a small app, looking at an alternate way to do something … dude, this is fine. It gets a newer engineer to think about other ways to accomplish something. 👍
      If the community is this negative and toxic, I think you may want to take a little more time with future content just to head off some of the criticism in advance. BUT, there is still a place for novice level code. It’s important to learn alternate ways to accomplish a thing and to consider different approaches.
      A stepping stone like this could be a great way to introduce newer engineers to dynamic programming concepts like the cache used in memoization or tabulation.

  • @sb_dunk
    @sb_dunk 9 месяцев назад +1319

    The real takeaways from this video are:
    1. There are often multiple ways to do things.
    2. Don't always believe people when they tell you that something is the "right" way. Try to understand _why_ something is better or worse.

    • @li_tsz_fung
      @li_tsz_fung 9 месяцев назад +68

      Video intro: I'll show you why this is wrong.
      Reasoning: This is wrong. Don't do it.

    • @sergeikulikov4412
      @sergeikulikov4412 9 месяцев назад +12

      @@li_tsz_fung i think there was some reasoning like «this code looks cleaner» :)

    • @nrico6666
      @nrico6666 9 месяцев назад +17

      Using switch isnt wrong, it's just inefficient due to the multiple cases and ugly longer codes.
      Using map is more tidy and has better performance than multiple switch cases

    • @sb_dunk
      @sb_dunk 9 месяцев назад +50

      @@nrico6666 Switch is not less efficient than map. Ugly is subjective.

    • @nrico6666
      @nrico6666 9 месяцев назад +19

      @@sb_dunk Switch is less efficient than map. Map operations time complexity is O(log n), using multiple switch statements like that is O(n) on worst case, with map when you access a key, the key will be hashed into a memory location so it's very fast for big tables.
      for switch it will check for every single condition before breaking which is very slow.
      And 4 lines of code is objectively more tidy than 16

  • @roelyoon3466
    @roelyoon3466 9 месяцев назад +390

    I'm not an expert in javascript, but generally associative maps like that are implemented internally using hashmaps or balanced binary search trees (as the C++ libraries do). In either case, creating these data structures will take extra time and memory, and the way it's presented here, this data structure would need to be created every time the function is called. Especially when there are only 4 conditions like this case, you're much better off using the switch statement

    • @dusantodorovic5240
      @dusantodorovic5240 9 месяцев назад +34

      Yup, exactly. In C++ you can define it as static inside function so it generates only once, but even that one time takes more than calling switch 1000 times.

    • @saiphaneeshk.h.5482
      @saiphaneeshk.h.5482 9 месяцев назад +5

      I guess that is Dart and not Javascript.
      I'm a noob so can anyone clearly say which would be more performant and efficient?
      I mean the switch case will use more processing but no additional memory but the map would use more memory and very less computation when it's declared as a static?
      Any sources which I can refer to for more info on this?

    • @redrn2332
      @redrn2332 9 месяцев назад +4

      Would be better if using a custom constexpr map. On the other hand, many language implementations puts lots of effort into optimizing switch statements and similarly match expression. Switch is not as inefficient as people claim it is.

    • @WarClonk
      @WarClonk 8 месяцев назад +4

      ​@@saiphaneeshk.h.5482I would go with the switch case. Creating something in the RAM for something that could be a simple switch case just feels wrong and as others have explained it produces overhead. Will you feel the overhead? Probably not unless it is part of something that gets called 100 times or much more in a second. So both will work. Also you can reduce the amount of lines in the switch case by 6 if you just return in the case.

    • @floskater99
      @floskater99 8 месяцев назад +37

      Code Readability is a lot more important than saving NANOSECONDS of computing time …
      What you‘re doing is called "Premature optimization".
      If this function is called a million times a second, sure, valid point. But it usually is not.

  • @hansdietrich83
    @hansdietrich83 10 месяцев назад +810

    Enum + switch will compile to a super small and fast jump table

    • @pixelsam123
      @pixelsam123 9 месяцев назад +33

      I'm not sure this is valid for all languages
      Maybe some yes.

    • @saarza9991
      @saarza9991 9 месяцев назад

      ​@@pixelsam123most

    • @voltflake
      @voltflake 9 месяцев назад

      @@pixelsam123valid for all languages that compile to binary executables

    • @oussamasethoum1665
      @oussamasethoum1665 9 месяцев назад +1

      true, it will be faster.

    • @fabienso5889
      @fabienso5889 9 месяцев назад

      ​@@pixelsam123i can guarantee you switch +enum will always be as fast or faster
      Unless your language is really fucked up
      But in this case you are itterating over an array of string and comparing it
      The switch + enum time is one instruction cycle plus a jump
      I thing a single string compare takes more time than that by itself
      Here is the assembly code curtesy of gpt3
      section .data
      switch_table:
      dd case1
      dd case2
      dd case3
      section .text
      global _start
      _start:
      mov eax, 2
      mov ebx, eax
      shl ebx, 2
      add ebx, switch_table
      jmp [ebx]
      case1:
      ; Code for case 1
      jmp exit
      case2:
      ; Code for case 2
      jmp exit
      case3:
      ; Code for case 3
      jmp exit
      Gpt is dumb and used one cicle too many
      Here is the code for a string compare
      section .data
      str1 db "Hello",0
      str2 db "World",0
      section .text
      global _start
      _start:
      mov esi, str1 ; Load address of the first string into ESI
      mov edi, str2 ; Load address of the second string into EDI
      compare_loop:
      lodsb ; Load the byte at [ESI] into AL and increment ESI
      lodsb ; Load the byte at [EDI] into DL and increment EDI
      cmp al, dl ; Compare the characters
      jne not_equal ; Jump if characters are not equal
      cmp al, 0 ; Check for the end of the strings
      je equal ; Jump if both strings are equal
      jmp compare_loop ; Continue comparing
      not_equal:
      ; Strings are not equal
      ; Your code here
      jmp exit
      equal:
      ; Strings are equal
      ; Your code here
      jmp exit
      exit:
      ; Your exit code
      See that for loop i hope your strings aren't too long

  • @dienvidbriedis1184
    @dienvidbriedis1184 9 месяцев назад +121

    thank God, at least there are people in comment section with common sense.

  • @NullPointer
    @NullPointer 8 месяцев назад +453

    For everyone wondering why webs and apps work worse and worse everyday

    • @666neoselen
      @666neoselen 7 месяцев назад +18

      yep. best idea is:
      array with key equal to mgs
      and each key equal to a value that is coffee & stuff.
      then use it like that:
      $map[$milligrams] then you get the "coffee" as a result. and add the string " mg" at the end.
      it's plain stupid to use an object oriented method for that. and inefficient memory-wise.
      and I wondered why even simple apps are like, 1Gb of data, and 100Mb of RAM.
      this guy won't work at netflix's but at costco's.

    • @omaribbrahim
      @omaribbrahim 7 месяцев назад +34

      @@666neoselen Your simple app is using 100mb of RAM either because of garbage collection or heavy GUI resources. Your hashset is not impacting your memory use nearly as much as you think it is.

    • @omaribbrahim
      @omaribbrahim 7 месяцев назад

      @@666neoselen Snipper from Netflix's own Eureka:
      Set toShutdown = new HashSet(peerEurekaNodeUrls);
      toShutdown.removeAll(newPeerUrls);
      Set toAdd = new HashSet(newPeerUrls);
      toAdd.removeAll(peerEurekaNodeUrls);

    • @FurryDanOriginal
      @FurryDanOriginal 7 месяцев назад +7

      ​@@666neoselen The milligrams are not guaranteed to be unique, so if you have 2 drinks with the same amount of coffeine your solution wouldn't work. You should use the drink (preferably an enum) as the key, and the value as the mg number representation.

    • @ethannnnnnn
      @ethannnnnnn 7 месяцев назад +13

      @@666neoselenFound the guy who doesn’t program at all.

  • @Claxiux
    @Claxiux 9 месяцев назад +168

    after watching the video, I came to the comments to see him getting roasted. I wasn’t disappointed

  • @Eric-xh9ee
    @Eric-xh9ee 9 месяцев назад +66

    Why would you put a map inside a function? then it needs to rehash every time the function is called. Put it outside the function

    • @lukasbalaz9988
      @lukasbalaz9988 7 месяцев назад +4

      but it's const - evaluated at compile time in Dart

    • @folf
      @folf 7 месяцев назад +13

      @@lukasbalaz9988 it's constant, but only when the function is called. So it's initializing the variables multiple times.

    • @BryceDixonDev
      @BryceDixonDev 7 месяцев назад +1

      This is why C++ has `constexpr static` variables

  • @shalidor1619
    @shalidor1619 9 месяцев назад +20

    And tomorrow project manager will tell you to add notification after coffee receiving

    • @ThomasVWorm
      @ThomasVWorm 8 дней назад

      You would not add this to a function, which should just return the amount of caffeine.

  • @frackitos
    @frackitos 9 месяцев назад +104

    Great job not explaining why the switch statement is wrong

    • @jsonkody
      @jsonkody 9 месяцев назад +12

      It's not .. he should say with object its more readable

    • @alxjones
      @alxjones 9 месяцев назад +4

      It's more just reinventing the wheel. The switch statement does exactly what the map does, but map already exists. I'd get honestly get rid of the wrapping function entirely, and just do
      caffeine = map[type] ?? 'Not found'
      directly in the code.

    • @berndeveloper
      @berndeveloper 9 месяцев назад

      @@jsonkody space and time complexity of 0(1) is the best approach, so no, you're not correct.

    • @Twenty20242
      @Twenty20242 8 месяцев назад +20

      @@berndeveloperno, you’re not correct. Big O notation is a theoretical measurement of algorithm performance at scale. It measures how algorithms perform as their inputs scale infinitely. Now, let’s move into the real world. For starters, the better big O does not necessarily mean the better algorithm in practice. Take two algorithms, one of O(n^2/1000) and the other O(n). The O(n^2/1000) algorithm is actually better up until n=1000. Equally, all O(1) algorithms are not the same. All O(1) means is that the time/space complexity does not increase as input sizes increases. Yet, an algorithm that allocates for example 10000 objects on the heap each function call (constantly allocated 10000 no matter the input) is better than one that allocates no objects on each function call, even though they are both O(1). This specific example given in the problem is kinda irrelevant, it’s not like you’re gonna get drastic performance drop off allocating a object with 5 values. But, that still doesn’t change the fact that in the improved example, we allocate an object on the heap, while in the first example the compiler is just going to assemble the code into jump statements (which are highly efficient). So, despite it being O(1), it worse than the switch statement from purely a resource usage point of view.

    • @ThomasVWorm
      @ThomasVWorm 8 дней назад

      Switch is not wrong. It does, what it can do best: it sucks.
      I never understood, why it is designed in a way, that you need to add break for each case.
      I understand, that the fall through behaviour is of interest too. But this should be a another language construct.

  • @lukas.pierce
    @lukas.pierce 8 месяцев назад +25

    Enum + Switch is better because when you add new value in enum it automatically shows all places where you need add new value. It better for refactoring and it better for performance.

  • @rnseby
    @rnseby 8 месяцев назад +23

    The reason I like this over the switch statement is it's very easy to add or subtract items from the map object. Not to say I don't use a switch statement, but I've used the object lookup more times.
    Imagine if we wanted to add more items to the list of values. The map object could be loaded dynamically from a CSV file that could be edited by somebody else and presto we can add values without ever touching the code.
    I've done this method in code for my work with a pricing sheet. Sales people can provide the CSV and presto updated values.
    As far as speed, if you can actually notice the difference between the switch statement and the object, you've got other issues. Keep in mind that the object lookup is completely inside the language while the switch statement is something you need to write. Letting the language handle it means it can attempt to optimize what's happening.

  • @dwiputrasam9637
    @dwiputrasam9637 9 месяцев назад +51

    these kind of videos are one of the reasons why some beginners quit before reaching their goals

    • @DaMoodz
      @DaMoodz 9 месяцев назад

      😂

    • @orr4337
      @orr4337 7 месяцев назад +1

      What do you mean by that?

    • @enzy6434
      @enzy6434 7 месяцев назад +9

      ​@@orr4337 because these videos are pointless and just make coding seem needlessly complicated and bloated/overwhelming to people trying to learn. And just demoralize them into thinking they're wrong when they're not wrong to use a switch statement.

    • @AkioJunichiro
      @AkioJunichiro 6 месяцев назад +2

      @@enzy6434 Yes, but map or object in js are basics too. If you're lost when it comes to map and key, you won't get far. And mapping gives you the opportunity to iterate. If I say "give me the list of drinks" or "give me the total caffeine for all the drinks" he can do it easily because he's chosen the right approach.
      But I get your point, when you tell a beginner "use this approach instead" he think that's apply on all case. That's why you have to explain why this is a good approach in that particular case.

  • @SuperKidontheblock
    @SuperKidontheblock 9 месяцев назад +2

    If you listen to all of these RUclips channels you begin to develop analysis paralysis. Tools exist to test performance and over time you’ll understand what’s performant over non performant.

  • @teckyify
    @teckyify 7 месяцев назад +2

    Finally someone using their brain. Using thos technique since 20 years. Always think in data structures, not instructions.

    • @FurryDanOriginal
      @FurryDanOriginal 7 месяцев назад

      Agreed! Abstraction is key :)

    • @peezieforestem5078
      @peezieforestem5078 6 месяцев назад

      But the problem is map is not passed from the outside, so it will be reinstantiated every time the function is called. That is terrible.
      There's nothing wrong with switch, in fact, just adding enums to a switch makes it faster and more versatile.
      Why should we favor this approach? At best, it is a trade-off.

    • @FurryDanOriginal
      @FurryDanOriginal 6 месяцев назад

      @@peezieforestem5078 You're making a good point but I'm assuming it's shown like that in the video for simplicity's sake. After all, you could simply pass it as a parameter or define it as a const outside the function scope. And the main value that is gained is that a dictionary can be dynamically instantiated rather than at compile time as with switch statements.

    • @teckyify
      @teckyify 6 месяцев назад

      @@peezieforestem5078 that is typically optimized away by the compiler, it will create a separate function and give it a random-like name and call it. Except you have some context that can't be passed around. This is a classic optimization which should not be your first concern, but the conclusion from profiling your program, after you have written it

    • @teckyify
      @teckyify 6 месяцев назад

      @@FurryDanOriginal it's not so much about abstraction but the fact that the data structures determines necessarily which operations can be executed efficiently. The data structure determines the limits of your operations and the running time, space efficiency etc.

  • @Rose-ec6he
    @Rose-ec6he 9 месяцев назад +29

    Could you please explain what you find cleaner and easier about this approach?

    • @sunbear9374
      @sunbear9374 9 месяцев назад +2

      I don’t program/am looking to start sometime hence the interest or why I’m here, but I think it overall just looks cleaner might even run a bit smoother or if not just make it overall easier to take in

    • @csanadtemesvari9251
      @csanadtemesvari9251 9 месяцев назад +9

      If you want to add a new beverage, you only need to update the map, not the whole case statement.

    • @citizen320
      @citizen320 8 месяцев назад +2

      It's obviously WAY easier to read. But as others have said, it's less efficient. So this would be a bad habit

    • @sunkintree
      @sunkintree 8 месяцев назад +8

      @@citizen320 Sure but it's not the 1990s anymore. We don't need to worry about small inefficiencies in most code.
      In most applications, it's better to be readable.

    • @floskater99
      @floskater99 8 месяцев назад +2

      1. Less duplicate code.
      2. All keys and values in one spot.

  • @Chris-dx6dw
    @Chris-dx6dw 9 месяцев назад +9

    It’s not wrong at all, you are just presenting an alternative. I also use the map approach at times but please don’t misrepresent things.

  • @zlackbiro
    @zlackbiro 8 месяцев назад +43

    Nothing is faster than a switch. By using objects, you invoke heap memory which is bad!

    • @MisterAssasine
      @MisterAssasine 8 месяцев назад +3

      yeah so what the solution is easier to read and undetstand which saves you way more than the nanoseconds of runtime you save with the switch

    • @miles2309
      @miles2309 8 месяцев назад +9

      @@MisterAssasineyou can create the map outside of the function so it’s used as a reference and isn’t recreated on the heap every call

    • @floskater99
      @floskater99 8 месяцев назад

      Speed doesn‘t really matter if it won‘t be called a million times a second.

    • @uwirl4338
      @uwirl4338 8 месяцев назад +8

      As it turns out, many things are faster than a switch written in a scripting language

    • @uwirl4338
      @uwirl4338 8 месяцев назад +6

      Also don't talk about the heap memory as if you knew anything about it. If your knowledge only extends so far as to call it "bad", just don't say anything about it. Leave the performance talk to engineers and focus on centering divs or whatever you web developers do

  • @frcl
    @frcl 9 месяцев назад +1

    the fact that this is cleaner, the simpler the better , if you dont mind execution speed, thanks

  • @sivuyilemagutywa5286
    @sivuyilemagutywa5286 8 месяцев назад +5

    you could also return map[type] ?? 'Not Found'
    no need for caffeine variable

  • @wazbat1
    @wazbat1 9 месяцев назад +180

    Please dont state things as facts when you genuinely don't know what you're talking about

    • @FlutterMapp
      @FlutterMapp  9 месяцев назад +16

      I liked your comment. Facts.

    • @petrlaskevic1948
      @petrlaskevic1948 9 месяцев назад

      You need to learn how switch operates under the hood, LowLevelLearning has a nice video on how It is done in C.
      I know this is Flutter, but they do it the same way, switch is a map under the hood..

    • @kevinclark1783
      @kevinclark1783 9 месяцев назад

      Please don’t be an asshole when you genuinely don’t know what you’re talking about

    • @voltflake
      @voltflake 9 месяцев назад +6

      ⁠💀💀

    • @dawid_dahl
      @dawid_dahl 9 месяцев назад

      Amen.

  • @seventeeen29
    @seventeeen29 6 месяцев назад

    I was expecting high quality content until i saw the channel was named after flutter

  • @asagiai4965
    @asagiai4965 9 месяцев назад +11

    technically people should stop saying something is wrong when it isn't.
    If you want to introduce a technique or trick just say it.
    Like say There is a better technique than using a switch statement

  • @FurryDanOriginal
    @FurryDanOriginal 7 месяцев назад +2

    For a bit of variety in the comment section; This is one thing I've found myself often doing, so I'm happy seeing someone finally mention this. It provides the advantage that you can make your cases run-time dependent. I think it's a great solution. And for those that care about the performance downside of this, you can compensate for most of it by making the value a function. You will still have a bit of overhead for creating the hashmap and functions, but that's as good as this solution gets.

  • @hydroxa4330
    @hydroxa4330 8 месяцев назад +1

    This change is good if youre doing data driven work, since you can dynamically change the values to fit new values, but otherwise using a switch is always superior. Often, compilers have some pretty magical algorithms inside that can optimise switch blocks into very efficient jump tables. Even if you're using an interpreted language, there's almost always a reason that language offers you switch blocks, and its almost always a performance reason

  • @shayokhshorfuddin2576
    @shayokhshorfuddin2576 26 дней назад

    Man I love your videos. I am a senior engineering and have worked with Dart quite a while ago. Really enjoy the techniques. Keep going and ignore the hate. ❤

  • @sriharsha7314
    @sriharsha7314 9 месяцев назад

    glad im doing it for ages!

  • @Audienc4u
    @Audienc4u 2 месяца назад +1

    I think this may depend when the map is created, the number of keys it holds and the requirement to have one single value to each key. In some situations a single option may require several lines of code leading to more and more branches off each root map.. while that isn't bad per se.. it may start to become less navigable when changes are needed.

  • @erickpurbaya
    @erickpurbaya 5 месяцев назад

    Insightful, thanks a bunch.

  • @floppa9415
    @floppa9415 7 месяцев назад

    now do that a few million times in a loop. The garbage collector will love it!

  • @whitefercho
    @whitefercho 9 месяцев назад

    I like this approach when I instate the object out of the iterators body and just calling it.

  • @BioHazarddasdadfasfsad
    @BioHazarddasdadfasfsad 7 месяцев назад

    Plot twist: the guy secretly gets rid of potential concurrent

  • @ver1f1ed
    @ver1f1ed 7 месяцев назад

    I think the implementation is a little off what I’d recommend but the comments are going crazy. A lookup table is generally a much more readable method than a never ending switch statement. In typescript, I’d prefer this as a type for the drink and a Record for the caffeine. That way you get a compiler error if you add a new drink but forget to add it to the lookup table. You don’t get the same functionality on a switch with a default statement. It’s especially helpful when you have large amounts of people using a code base, when you can’t possibly know the impact of every minute code change. People going off on “it’s less efficient” have never worked on a code base with more than 5 people

  • @kippesolo8941
    @kippesolo8941 7 месяцев назад +1

    It depends on what else this programm has to do.
    If you want to add another drink or delete one, gotta rewrite the switch.
    So you would want a map.
    If the function is called many times and fast, you dont want to create a map everytime.
    pros and cons.
    premature optimization is a thing i guess

  • @OctagonalSquare
    @OctagonalSquare 9 месяцев назад +50

    The only real reason to do this would be if you need the be able to add or remove possible items from the list. It’s definitely not faster or clearer

    • @csanadtemesvari9251
      @csanadtemesvari9251 9 месяцев назад +12

      It's definitely cleaner. What?

    • @thenoobyblock1208
      @thenoobyblock1208 9 месяцев назад

      A map is definitely clearer and more maintainable in a lot of cases.
      Funnily enough I had a similar issue when coding in Android Studio, where I wanted to create a button handler for all buttons in a single method assigned to the button 'onClick' attribute. I assigned the appropriate class to each button ID and then I just had a single line of code at the bottom which started the class (activity) assigned to the button pressed.
      Both have their uses, it's a little ignorant to entirely dismiss the use of maps. For a function like that shown in the video, I'd probably just use a switch statement myself.

    • @floskater99
      @floskater99 8 месяцев назад +3

      It‘s cleaner for sure. Way less duplicate code. How is that even debatable?

    • @blank-404
      @blank-404 6 месяцев назад +2

      It is clearer, it is shorter, it is extendible, it is DRY. In a word, it is SUPERIOR.
      I will never understand the internet's obsession with switches. Those really aren't either clearer or standard (code blocks with breaks and without brackets? Thanks but I'll pass). Yes, it may save a couple of CPU cycles, but at what cost?

  • @racoonracer7878
    @racoonracer7878 5 месяцев назад +1

    Too complicated. Didn't learn this in class. Going with switch case. Tried and true

  • @hosseinslamizadeh549
    @hosseinslamizadeh549 6 месяцев назад

    Nice one, thanks. you deserve subscribing. keep it up.

  • @mauri802
    @mauri802 9 месяцев назад +4

    I guess this is Dart but I'm not sure. I think you should specify which language it is.

  • @Erdnussflipshow
    @Erdnussflipshow 9 месяцев назад +1

    Kinda depends on the Programming language, if that switch statement works with string-comprison, it will take longer than hashing, but ideally `type` is an enum which would allow a constant time lookup faster than hashing `type` and jumping to the corresponding case.

    • @cantorgauss
      @cantorgauss 9 месяцев назад +1

      It’s about the DART programming language in case you didn’t even bother to notice

  • @TiennxBusiness
    @TiennxBusiness 7 месяцев назад

    wow. it's fast. thank u very much

  • @Android480
    @Android480 6 месяцев назад

    This is wild! Like almost comical

  • @YuckFou0x0FFFF
    @YuckFou0x0FFFF 9 месяцев назад +1

    Can you do a CLI test to prove it's actually faster? That would be great content

  • @hayatmirah
    @hayatmirah 9 месяцев назад +26

    if i have to do it with strings i will simply do:
    getCoffeine(String type){
    return switch(type){
    'Coffee' => '95 mg' ,
    'Redbull' => '147 mg' ,
    'Tea' => '11 mg',
    'Soda' => '21 mg',
    _ => 'Not found',
    };
    }

    • @FlutterMapp
      @FlutterMapp  9 месяцев назад +2

      Thanks a really good point tho! Thanks for sharing ✌ It's pretty much the same at this point.

    • @engine_man
      @engine_man 9 месяцев назад +3

      @@FlutterMappexcept this looks more readable than a hash map.

    • @ChillAutos
      @ChillAutos 9 месяцев назад +1

      This doesn’t allow you to use the map in other places though and it’s less extensible.

    • @sfk1991
      @sfk1991 9 месяцев назад

      This , but those types should be string resources and not string literals. Has better compile time and faster runtime.

    • @berndeveloper
      @berndeveloper 9 месяцев назад +1

      This is less efficient, because it checks each case in order until it finds a match. The hash map approeach is superior.

  • @JonathanHobbe
    @JonathanHobbe 9 месяцев назад

    I would say its generally better to keep it as a switch since you dont have to initialize a new map and since the switch expression make use of jump-tables

  • @zeez7777
    @zeez7777 8 месяцев назад

    Super readable and ALOT slower at the same time, dont assume creating an object is a cheap operation

  • @GoogleAccount-wy2hc
    @GoogleAccount-wy2hc 9 месяцев назад +1

    that's what I usually do, code looks tidy. Aaand if your code has different behaviors not just values you can create a hashmap of classes each of which would do what you want. Strategy pattern!

  • @reynoldskynaston9529
    @reynoldskynaston9529 6 месяцев назад

    It’s good to have the tools and to know when to use them. There is no need for a map in this case unless you can justify it.

  • @KilgoreTroutAsf
    @KilgoreTroutAsf 8 месяцев назад

    You can even do minimal perfect hashing for optimum size or, better still, let the compiler substitute the const strings with enums., which is their true function.

  • @OzanErenBilgen
    @OzanErenBilgen 2 месяца назад

    Amazed that so many coders including the OP don’t know map gives O(1) complexity and any other method is O(N)

  • @YmanYoutube
    @YmanYoutube 7 месяцев назад +1

    and people wonder why websites are so slow nowadays

    • @reroman
      @reroman 6 месяцев назад +1

      Exactly!! It's not the browser itself but all the apps created with this mindset. "Only because it's more readable": Did they skip the control flow instructions of the language in their bootcamps? "Just a few nanoseconds more": Do they even know how a map data structure is implemented? It's not just worse performance but more memory used.

  • @user-qj4rr1rm8i
    @user-qj4rr1rm8i 4 месяца назад

    Object literal tech.... I should remember this well.

  • @jjbasic3041
    @jjbasic3041 3 месяца назад

    I always see this guy’s shorts and just think about how he is wasting so much memory just for readability

  • @joshuaunderwood1873
    @joshuaunderwood1873 5 месяцев назад

    This is a very simple way to write slower code!

  • @codingman313
    @codingman313 9 месяцев назад +25

    This is a good example of of clean code is preferred over performent code

    • @primary157
      @primary157 9 месяцев назад +1

      Out of curiosity, in your opinion...
      Which one is the clean code?
      Which one is the performant one?

    • @ashutoshgupta9056
      @ashutoshgupta9056 9 месяцев назад +5

      ​@@primary157 Map is clean
      Switch is performant

    • @aaaabbbbbcccccc
      @aaaabbbbbcccccc 9 месяцев назад +3

      @@ashutoshgupta9056 Why? What is 'cleaner' about the map approach? How do you define 'clean'?

    • @mysorrowangel
      @mysorrowangel 9 месяцев назад +1

      It's clean only for this small example. For big switch constructs it's harder to understand the code - scroll up to see the init value and then scroll down to code use. Plus switch is usually more complex than if_then pattern.

    • @codingman313
      @codingman313 9 месяцев назад

      @@mysorrowangel what I meant by by first comment is that for those who think making a website or server or few microservices or using a few libraries to make an app or web-app is a big thing, clean code matters, for others who make those libraries, who write drivers, who write databases, whi write os, who write high performance apps like photoshop, game-engines, pyhsics engines, embeded system codes etc. its just pure bullshit.

  • @chrissullivan331
    @chrissullivan331 8 месяцев назад

    I always do this, I hate switch statements but they still have their place.

  • @codewithvicky
    @codewithvicky 7 месяцев назад

    Guys I prefer readable than performance here. For simple few switch cases, we are talking about performance. 😮
    Still instead of using map, we can use enum. It is more readable for me.

  • @gmjammin4367
    @gmjammin4367 6 месяцев назад

    I think this type of flow is preferable once your list of cases gets long enough. No solution is perfect.

  • @ousseynoudiagne7712
    @ousseynoudiagne7712 9 месяцев назад +1

    Just use enum and return the value directly without assigning any variable.

  • @kiss-liava
    @kiss-liava 7 месяцев назад

    It's called just "using a map". At least in this case nowadays front-enders would've googled "what's a map in programming"... And also you can use an enum + some array with the values to avoid hashing those strings every time

  • @SarkanyGergogaming
    @SarkanyGergogaming 6 месяцев назад

    Yes, because constructing a map in memory, filling it up and then acessing it, copying it to a variable and then finally returning it is, indeed, much faster then a few if-else branches or a native switch statement that quite literally is instantaneous and uses basically no memory.

    • @blank-404
      @blank-404 6 месяцев назад

      Of course, because inlining hardcoded data in the middle of your function and repeating your condition and variable assignment 10 times and remembering to break out of weird code blocks is so much better. Who needs DRY code? When a new drink is invented, just repeat a few lines of code to support it... That's how modern programming works, right?

  • @yeetskeet691
    @yeetskeet691 2 месяца назад

    You technically can still use a switch statement, but remove the variable assignments and return straight out in the case

  • @LaughingMan44
    @LaughingMan44 7 месяцев назад

    You have two redundant lines, don't need to declare a string local variable and can just return the string from the map directly

  • @KDrizzz
    @KDrizzz 3 месяца назад

    Nice. I bet I could do the same in typescript.

  • @ninguern7693
    @ninguern7693 8 месяцев назад

    This is what I think about this approach: If you are doing this in the front-end and this will only be called a reasonable amount of times, I prefer it. 1ms will not make any difference on the client, but a more readble code saves a ton of money in a project. Unless the real-world-performance is affected I always prefer a more readble code then a faster one.

  • @GuyananV
    @GuyananV 8 месяцев назад

    Ben oui continue comme soh mon Kevin

  • @Diamonddrake
    @Diamonddrake 6 месяцев назад

    While this does work and in the grand scheme of things doesn’t really matter the idea of replacing optimized language fundamentals with a memory allocation and map lookup because it looks better is some modern dev patterns that should be taken with a grain of salt.

  • @AbdelrahmanbahaaBonna
    @AbdelrahmanbahaaBonna 9 месяцев назад

    this depends on whether you enhance memory usage or execution time but both ways are correct.

  • @longnguyenkhanh7251
    @longnguyenkhanh7251 6 месяцев назад

    Well, at C, C++ and some of language I know will create hashmap in assembly code anyway, for match case in Rust I 'm not check yet as they allow to do the comparsion. But using map object you can bring out so when there is new option you can just add to object easily. On other hand, it will need more memory for computer

  • @lemonandgaming6013
    @lemonandgaming6013 6 месяцев назад

    Branchless programming is important in certain cases like gpu programming. That being said you usually want to find the simplest and most obvious way to implement stuff like this. This is because if you are doing something simple there is a high chance the compiler / interpreter creator will have predicted and specifically optimized for it. But if you overcomplicate the compiler will probably not pick up on your intent and generate utter unoptimized garbage. Not that it even matters in most cases, just turn on a profiler and see where the problem actually lies.

  • @dawid_dahl
    @dawid_dahl 9 месяцев назад +1

    You forgot to mention why one is better than the other. I wonder why.

  • @avananana
    @avananana 9 месяцев назад

    I can see why the channel is named after Flutter now.

  • @nordern1
    @nordern1 6 месяцев назад

    People are acting like they understand performance optimizations. The reason why this has different performance characteristics in the first place is because the semantics changed. Try giving it "hasOwnProperty" as an argument.

  • @pawieplays
    @pawieplays 9 месяцев назад

    Yeah don’t listen to people when their first argument is you are wrong lol

  • @fmachine86
    @fmachine86 5 месяцев назад

    If you send me over a PR with this in it, I’m gonna PIP you so fast you’ll think I’m Amazon.

  • @fgpreviews
    @fgpreviews 9 месяцев назад +1

    Should use Liskov substitution principle.

  • @HiHelloHi
    @HiHelloHi 3 месяца назад

    They both do the same thing but the map let's you add new "cases" at runtime which you couldn't with the switch.

  • @rummusLoL
    @rummusLoL 7 месяцев назад

    Use a string enum - that way you get a compile time check that you are providing a valid caffeinetype

  • @Dittoh123
    @Dittoh123 8 месяцев назад

    Oftentimes you’ll need to do more than just simply assign a value. For those instances I just use enum with a switch

  • @vnm_8945
    @vnm_8945 9 месяцев назад +1

    I like the part where he says why is it wrong.

  • @kyle19421
    @kyle19421 7 месяцев назад

    Another thing I like about this, if you make the values of the object functions that return a string, you can add other behavior in there and do a mapping[index].?() ?? 'Not found' if you want to add more behavior within each case

  • @mr.clumsy7225
    @mr.clumsy7225 10 месяцев назад +1

    This is ok to use and cleaner, unless you're not running the code iteratively, where switch case will be more efficient.

    • @FlutterMapp
      @FlutterMapp  10 месяцев назад

      Good point! Thanks 🙏

    • @max-ii9kd
      @max-ii9kd 10 месяцев назад

      can you give an example?

  • @lestradicpaul6044
    @lestradicpaul6044 7 месяцев назад

    Using return switch from Dart 3 you can bring this function to a much clearer 6 lines code and also being faster and whithout using any variable to store data.

    • @Zipperheaddttl
      @Zipperheaddttl 7 месяцев назад

      Yeah you can just write case tea : return 11 mg ;
      It's even less code if you write it that way.

  • @sshreddderr9409
    @sshreddderr9409 7 месяцев назад +2

    its much more readable and compact, but also slower. Contrary to what many people say here, the improved readability alone could be worth it if this Code is not executed extremely often. I personally would choose readability over speed by default, and only make the conscious choice to make it very efficient when its Code that gets executed very often. Many switch statements do not have to be executed often in a running program, but they typically are very exhausting to read

  • @weroro
    @weroro 7 месяцев назад

    In this demo, Flutter looks like Typescript to me. If it's really that similar, I guess I could take a look at Flutter and start doing something in it.

  • @GEN47-27
    @GEN47-27 7 месяцев назад +2

    Remember, negative engagement with a short is still engagement. And by arguing here OP gets to farm you X times

    • @benbrook469
      @benbrook469 7 месяцев назад

      this comment has +EV engagement btw

    • @FlutterMapp
      @FlutterMapp  7 месяцев назад

      100% true lol

  • @cipherxen2
    @cipherxen2 9 месяцев назад +7

    Almost nobody will use switch for a simple mapping between strings.

  • @coreybayless6168
    @coreybayless6168 8 месяцев назад

    Here is the same but in Python
    def get_caffeine(type):
    caffeine = ""
    map = {
    "Coffee": "95 mg",
    "Redbull": "147 mg",
    "Tea": "11 mg",
    "Soda": "21 mg"
    }
    caffeine = map[type]
    return caffeine
    print(get_caffeine('Redbull'))

  • @AllanSavolainen
    @AllanSavolainen 2 месяца назад +1

    That is fine until you need to execute some code for cases.

  • @zsigmondforianszabo4698
    @zsigmondforianszabo4698 9 месяцев назад +5

    I heard switch statements are actually really good bc they do hashtable lookup

    • @zlackbiro
      @zlackbiro 8 месяцев назад

      Switch is the fastest js statement.

    • @floskater99
      @floskater99 8 месяцев назад

      according to that logic if/else would be the best to use here..

  • @chervilious
    @chervilious 5 месяцев назад

    To be honest I'll do object literal technique first. If i really really need those performance sure I'll change it to switch/if based solution

  • @369lalala
    @369lalala 9 месяцев назад

    They both work, so both are right.

    • @jsonkody
      @jsonkody 9 месяцев назад

      Exactly

  • @nonchip
    @nonchip 7 месяцев назад

    and that's what we call "almost understood what a `class drink` is".

  • @irozockt
    @irozockt 9 месяцев назад +1

    Yeah nice now i don't have a default return value if some faulty "type" gets in as a parameter. It will just throw an exception which i should catch. Also i can't execute anything depending on the type and only return a value based on the type.
    And it is slower as already mentioned by multiple comments.

    • @floskater99
      @floskater99 8 месяцев назад

      He literally added a default return value?

  • @nganyong9904
    @nganyong9904 9 месяцев назад

    Should use is probably improper remark. Could use would be better. Btw, it becomes harder to read rather than simple switch break statement

  • @zebraforceone
    @zebraforceone 9 месяцев назад

    Having an object literal isn't necessarily bad, but it will consume more memory than a switch.
    If you are going to use an object literal then you should definitely at least make your map static or put it in a higher scope than your function, otherwise you're allocating and then garbage collecting that map on every call to your function.

  • @TheAmzngAids
    @TheAmzngAids 8 месяцев назад

    And were going to allocate that additional memory on the heap because.....slightly more readable i guess?

  • @nomiscph
    @nomiscph 9 месяцев назад

    Switch statements are actually faster until about 10 items then a object lookup is faster in js that is

  • @Warpgatez
    @Warpgatez 9 месяцев назад +1

    That is a way of doing it yea. Not a fast way though. Learning developers, don’t just take things at face value. Run tests yourself and learn how things work.

  • @doxed64
    @doxed64 8 месяцев назад

    case "Coffee": return "95 mg"
    You don't need an assignment or break.
    But yeah, at that point just use a dictonary

  • @ClickbaiterZ
    @ClickbaiterZ 9 месяцев назад +1

    Ok, maps and switch case are different thing. None of them are incorrect, it depends on what you need.