DEV Community

Cover image for Juniors Literally Can't Write Switch Statements: What Senior PHP Developers Need to Focus On

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

Rob Waller on September 27, 2017

Collapse
 
jbristow profile image
Jon Bristow • Edited

DIGRESSION/SLIGHTLY OT, FEEL FREE TO DISREGARD

As a Senior Developer, I hate switch functions. (Especially if they don't auto-break.)

They were a mistake to add to C, especially with the fall through. It's a bad construct that unnecessarily simplifies an if/elseif/else construct while enabling mistakes and unclear flow.

They are doubly a mistake in "OO" languages. They encourage thinking that breaks the "Tell, don't ask" model.

Yes, they're old and they served their purpose when optimizing compilers weren't as good and disk space for storing source code was expensive. I say that we should avoid 'em and teach others to do the same.

(I do not argue that switch is sometimes easier to read than a forest of if/elif/else. I just think the dangers introduced by fall-through switches is too high to ignore.)

Collapse
 
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 kotlinlang.org/docs/reference/cont...)

Collapse
 
jbristow profile image
Jon Bristow • Edited

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);

Over

switch (operatorInput) {
  "+": add(a, b);
       break;
  "-": minus(a, b);
       break;
  default:
    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

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
        OperatorType.plus -> a + b
    }

or:

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

I think the first one is way more clear.

Collapse
 
robdwaller profile image
Rob Waller

I'll be honest with you, I've never really used them. I agree they don't seem to suit OOP and I'm not sure they can comply with the single responsibility principle.

Collapse
 
nefariolabs profile image
Dr Nefario

I felt compelled to sign in and comment even though I ought to be off home by now. As someone just at the beginning of the journey learning to code, I've definitely fallen into the trap of just copying from Stack Overflow. But I've walked away from this seeing that actually I learnt and achieved nothing that way. Ultimately I became frustrated when blocks of copied and pasted code didn't do what I wanted because I didn't have a solid foundation. As you say: "wax on, wax off"! A great post. Thank you for sharing

Collapse
 
robdwaller profile image
Rob Waller

Genuinely pleased that it is helpful.

I'd advise any dev starting to just stick at it. I've got a degree in history and had to completely retrain.

Took me about 9 years to get decent at it. Now after 12 I've still got a great deal to learn.

Keep going and keep pushing.

Collapse
 
ben profile image
Ben Halpern

As senior developers we need to put things in perspective, particularly in the PHP community right now. Beyond actually coding stuff, the day job, the primary focus of senior developers should be to educate and guide junior developers. This means two things, teach the basics, the real basics, and encourage juniors to learn, to self teach.

I definitely agree with this and I'm not always great at making it the focus myself.

Collapse
 
robdwaller profile image
Rob Waller

It's hard, a lot of leads and seniors really don't have the time. I spend most of my days in meetings discussing everything but dev.

But to be fair you've built a platform that helps developers every day. You're defo doing your bit and more.

Collapse
 
essiccf37 profile image
essic

You should be taking side if you want to teach / mentor / support junior in the trade.
So they might understand your focus and get their own ...
I'm referring to the beginning of your article on the Twitter thing...
To me that illustrate far more your point that juniors making a mistake, for which your approach is 100% positive for all, as your blog post and the solution you talk about.

Collapse
 
robdwaller profile image
Rob Waller

I'd say I have a 'side' I'm just not ideologically bound to it.

Collapse
 
essiccf37 profile image
essic

I do not think that I said or implied that you have to be "fanatical" about the side you chose or rather the position you hold on a subject / idea.
I simply wanted to say that while I agree with your conclusion, I find weird that you take side on the switch statement of a rookie but not on the twitter exchange you posted, especially since you seemed to write about the PHP community.

Thread Thread
 
robdwaller profile image
Rob Waller

Sorry, I see what you're saying now. To clarify my position I see control structures like switch statements as a 'basic'. An objective topic you have to get right.

Whereas dependency injection is a higher level topic that is more subjective.

Thread Thread
 
essiccf37 profile image
essic

No worries 👍🏿
I see what you mean but then it seems to me that the worst in our industry is not ignorance or lack of knowledge but the almost supernatural way that most of us refuse to be challenged like you have shown us in this Twitter repost...
But then maybe, it does start because we lacks the basics !

Thanks for the post

Collapse
 
jeroendedauw profile image
Jeroen De Dauw

I strongly disagree with one of the basics you mentioned: "Use a simple text editor for a few years, not a super powerful IDE". In my opinion, you should do the exact opposite. Why?

  • Feedback loops help you to learn. IDEs provide lots of instant feedback via static analysis. They will highlight all kinds of classes of mistakes and tech you to not make them.

  • Lack of these powerful tools teaches you to work as if they do not exist, which results in a lot of bad habits that are hard to unlearn. Things such as putting too much code into a single file because navigation is hard, or not renaming a variable because search and replace that does not understand scope is too dangerous.

My points here are about writing and modifying code. I do concur it is not a good idea to hide things such as SQL behind GUIs, especially if you do not understand what is going on.

Collapse
 
robdwaller profile image
Rob Waller

I think this is a more nuanced point. I started coding in notepad and I wouldn't advise anyone do that.

I think a clean install of Atom or Sublime is a better place to start than say PhpStorm.

I think there is a lot to be gained by debugging the old hard way rather than using tools to help you. To begin with at least.

Collapse
 
jeroendedauw profile image
Jeroen De Dauw

Perhaps we are not in disagreement after all, at least not very much.

In my opinion using debuggers teaches you bad habits. You should not need a debugger. It is one of many things inside of PHPStorm that IMO you should not use. I've been using PHPStorm for years and not used the debugger for at least 4 now.

That said, I think junior devs, and all devs, should still use IDEs such as PHPStorm, to make sure they have access to:

  • Static analysis showing immediate feedback on bugs and code smells
  • Navigation capabilities such as "go to definition", "show all implementations", "find all usages", etc.
  • Strong auto-completion
  • Safe refactorings at least for basic things such as renaming stuff and inlining variables
Collapse
 
arandilopez profile image
Arandi López

Code is like philosophy, you should read as much of it as possible, from as many sources as possible, regardless of whether you agree with it or not. Me personally, I prefer capitalism over communism, would I ever say read Hayek but not Marx, no! That would be idiotic, read both, they were both intelligent people, they both have interesting ideas and you can make your own mind up on who you prefer.

I have no words, thank you so much for this article 👏🏻 👏🏻 👏🏻 👏🏻 👏🏻

Collapse
 
robdwaller profile image
Rob Waller

I'm pleased you like it.

Collapse
 
kayis profile image
K • Edited

Is this the new "Junior devs can't make striped rows in a table"?

Somehow I have the feeling in the PHP world the wish to sepeeate oneself from these pesky juniors from university is rather big.

I left PHP for JS 6 years ago and I have the feeling it was the right decision :/

Also, the ecosystem feels to become more and more like Java, which I wouldn't consider a good thing either. I still have hopes that JS won't end up like that, but it seems the ecosystem goes more in the FP direction, so I'm probably save, hehe.

Collapse
 
robdwaller profile image
Rob Waller

"pesky juniors from university" you're going to have to explain that concept to me because I'm not sure what you're getting at.

Collapse
 
kayis profile image
K

I had the feeling most PHP devs I met were kinda self taught and most told me the story about how junior devs right from university can't really code, often followed by some anecdotes about striped tables or something.

Collapse
 
vasilvestre profile image
Valentin Silvestre

I'm sad because it's true.
I'm a Junior and I don't even know what a Dependence Injection really is.
I've learn PHP with Symfony ; I can make clean and pro code in Symfony.

But I don't know a lot of things about vanilla PHP..
In one hand, company ask us to code with FW and in other hand we want to learn basic code..

Collapse
 
vasilvestre profile image
Valentin Silvestre

But in fact, I'm trying to don't use switch function.. In most of case, if/else are cleaner.

Instead of this :

<?php

switch (true) {
    case $this->object instanceof SomeClass:
        //Do Something
    break;
    //etc, etc...

I prefer ternary operator or simple if :

<?php

if ($this->object instanceOf SomeClass) {
   // Do something
}

return $this->object instanceOf SomeClass ? 'foo' : 'bar';

And I'm triggered that there's no default in your switch !

Collapse
 
robdwaller profile image
Rob Waller

Think of a small app you could build and then don't use any frameworks, write your own code for everything. That's a good way to learn. Forces you to think threw some of the issues that framework builders also think through.