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...?
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.
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