DEV Community

Discussion on: Juniors Literally Can't Write Switch Statements: What Senior PHP Developers Need to Focus On

legosteen11 profile image
Wouter Doeland

They can be quite useful traversing through possible enum values. It kinda depends how the language implements switch functions. I program a lot in Kotlin and I like how they have implemented it (no need to break and you can use mutliple possible values which means no falling through

jbristow profile image
Jon Bristow • Edited on

Right, but only for simple things.

To me, especially with an OO design, I'd rather encourage:

// assume a calculator that only handles binary operators

Operator operator = Operator.parse("+"); //throws OperatorParsingException
operator.resolve(a, b);


switch (operatorInput) {
  "+": add(a, b);
  "-": minus(a, b);
    throw OperatorParsingException(operatorInput);

Now, when we get back into functional, I'm not as confident in my design, but I think I would do it like this. (But the switch statement badness is not precisely involved anyway, I'm just thinking out loud here.)

(defmulti operator (fn [op a b] op))
(defmethod operator :plus [_ a b] (+ a b))
(defmethod operator :minus [_ a b] (- a b))

(operator :plus 5 6) ; =11
Thread Thread
legosteen11 profile image
Wouter Doeland • Edited on

Sure, but in the Operator#resolve function you will still need either an if or a switch statement. How I would do this in Kotlin:

fun resolve(a: Int, b: Int) = when(type) { // type is the operator type
        OperatorType.minus -> a - b -> a + b


fun resolve(a: Int, b: Int) =
    if(type == OperatorType.minus)
        a - b
    else if(type ==
        a + b
        throw Exception("!?")

I think the first one is way more clear.