I do not want to use Switch in my code, so I'm looking for some alternative
Example with Switch:
function write(what) { switch(what) { case 'Blue': alert ('Blue'); break; ... case 'Red': alert ('Red'); break; } }
Example without Switch:
colors = []; colors['Blue'] = function() { alert('Blue'); }; colors['Red'] = function() { alert('Red'); }; function write(what) { colors[what](); }
My questions are:
Object oriented programming (OOP), that is virtual functions, are a substitute for switch .
What is the replacement of Switch Case in Python? Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.
char, byte, short can be used in switches too.
In this case, you could also use std::array<int, 5> , which, unlike std::vector<int> , can be constexpr .
I have only a note about your second approach, you shouldn't use an Array to store non-numeric indexes (that you would call in other languages an associative array).
You should use a simple Object.
Also, you might want to check if the what
argument passed to your write
function exists as a property of your colors
object and see if it's a function, so you can invoke it without having run-time errors:
var colors = {}; colors['Blue'] = function() { alert('Blue'); }; colors['Red'] = function() { alert('Red'); }; function write(what) { if (typeof colors[what] == 'function') { colors[what](); return; } // not a function, default case // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With