Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to avoid "spaghetti code", why is multiple if-else bad?

I was just reading the top 100 signs of spaghetti code and I came across number 4, which simply states:

if ($status == "awake"){ 
    $actitivity = "Writing spaghetti code"; 
} else if ($healthstatus == "OK"){ 
    $activity = "Sleep"; 
} else { 
    print "CALL 911 IMMEDIATELY!"; 
}

I've seen this multiple if-else pattern in other spaghetti discussions. I'm a little confused why this is, and even if it's applicable to this example.

Is the above example bad because

  • the first variable is actitivity which indicates the coder needs some sleep, so it's a joke, or

  • view shouldn't be being output during logic, or

  • something about too many if/else


EDIT never mind this second part, it's bad because of nested conditionals and multiple returns

In the other spaghetti discussions link, is it bad because

- the logic has return in it, which breaks the flow, or

- there's too many if/else piled on top of eachother...?

like image 383
Ben Avatar asked Oct 03 '22 02:10

Ben


1 Answers

If/else statement often breaks Open-closed principle. (Java example but valid in PHP too)

Solution => favor polymorphism.

Besides, assigning a temporary variables more than once is really error prone and reduces readability. Especially in PHP since it isn't a static-typed language. Indeed, what if someone first assign $actitivity = "Writing spaghetti code"; and then $actitivity = 1; ?? ...blending apples with oranges inside the same container.. Look at this: http://sourcemaking.com/refactoring/split-temporary-variable

Also, the logic allows for side-effect (print) only if one of the condition is verified => Method isn't cohesive and thus SRP violated.

like image 53
Mik378 Avatar answered Oct 12 '22 10:10

Mik378