FizzBuzz - switch and all its glories


#1

The thing to remember about a switch is that the expressions are interchangeable. Both,

switch (expression)

case expression:

can be written to satisfy each other in either direction. It's a tricky concept to grasp at first. Production coders don't play on tricks and best practice dictates will vary from team to team. On our own turf we can and should explore.


[Challenge] The Classic FizzBuzz Challenge
#2

Yeah your right it is a tricky concept to grasp, I can use a switch but I don't think I completely understand and grasp it at this point. Will study more.

Thanks for the advice.


#3

In every scenario the comparative expressions will be restrained to a particular environment. A value or expression will open the switch, and a corresponding satisfactory value or expression will close it.


#4

I like that explanation, definitely helping me to get my head around it. Can you give me an real life example/ scenario where a switch would be the most efficient approach?


#5

Off the top of my head, no. As much as I may think I think about efficiency, I think intuition is the best course for me, and for the learner. Set efficiency on the back burner and get immersed in the concepts without that constraint.

We saw in the example where the opening expression was zero, itself, and the case expressions were modulo operations. One satisfies the other. That's how this works.

Aside

Expressions are not statements, but representations. They present themselves by whatever construct is deployed and always result in a value.

a = b

is a statement. It is immediately declarative.

6 * 7

is an expression which in this form is meaningless, but if we assign it to a variable will be cached for later use. (We know all this ...)

Expressions are the backbone of dynamic logic since they make up the bulk of the input stream of our programs. Remember, there is an interpreter back there that sees them all, in their many forms.

If the expression passes syntax and exception muster, it will pass in a switch. That's why it is necessary to explore. Remember also, a function is an expression. If that doesn't brighten the picture, I don't know what else would.


#6

Wow you really have a way of putting code into words and sentences. You clearly have a great understanding of the language and this has most absolutely brightened the picture.