I see a lot of people saying it’s wrong to do switch
in the code, because it ends up weighing and is ugly
I don’t see that. I might use good programmers as a reference :)
switch
It’s elegant and fast, so every modern language, like the old ones, has it. Knowing how to use it is very powerful and facilitates a lot, in addition to being faster than other options in most scenarios. In fact it exists by optimizing execution first, and elegance second, so I can’t imagine where these ideas come from.
Well, I even imagine in another scenario. There are some people who say that because it is less object oriented. But if you ask why it’s bad, in general they don’t know how to say it, they read it somewhere and keep repeating it. They give no context, as with those who have an incomplete understanding of things (something you are seeking to get rid of here). Of course, in some context it is not so appropriate to use it, but this applies to all resources of the programming language, without exception, applies to variables, literals, operators, all commands, up to a simple semicolon.
If the comparison is with if
I would say that it is usually more elegant in cases where it can be used (not all of it can). The case shown in the question is very basic and the most ideal for your adoption. It gets faster and more beautiful, even if beautiful is something subjective (it would be more if you were not obliged to use break
).
Of course, considering the first line, it doesn’t even make sense because it’s guaranteed that only the first will be executed.
There’s a question that talks more about how it works: How the switch works behind the scenes? (despite being another language, it works the same)
It may also be useful to read:
I didn’t even mention your use as Pattern matching which is much more powerful and interesting, and is available in C#, although many do not know it. And in version 8 it can be used as expression.
Depending on the situation, the swtich case can be very good in certain cases, as the documentation itself already explains "The switch instruction is usually used as an alternative to an if-Else construct if a single expression is tested with three or more conditions. For example, the following switch statement determines whether a Color type variable has one of the three values:" documentation
– Jonathan Igor Bockorny Pereira