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

I just read the 100 best signs of a spaghetti code , and I came across number 4, which simply reads:

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

I saw this multiple if-else pattern in other discussions of spaghetti . I am a little confused why this is so, and even if it applies to this example.

Is the above example bad because

  • the first variable is actitivity , which indicates that the encoder needs some sleep, so this is a joke or

  • view should not be displayed during logic or

  • something about too big if / else


EDIT ignoring this second part, this is bad due to nested conditional expressions and multiple returns

In other discussions of spaghetti , this is bad because

- the logic has a return in it, which breaks the stream, or

- there are too many if/else piled on top of each other ...?

+4
source share
1 answer
Operator

If/else often violates the Open-closed principle . (Java example, but valid also in PHP)

Solution => favorable polymorphism.

In addition, assigning temporary variables more than once is indeed error-prone and reduces readability. Especially in PHP, as it is not a static language. Indeed, what if someone first assigns $actitivity = "Writing spaghetti code"; and then $actitivity = 1; ? ... mixing apples with oranges inside the same container. Take a look at this: http://sourcemaking.com/refactoring/split-temporary-variable

In addition, the logic allows a side effect ( print ) only if one of the conditions is checked => The method is not cohesive and, therefore, is violated by SRP.

+3
source

Source: https://habr.com/ru/post/1499760/


All Articles