The use of if / else / if not depends on the context of the application. If there is a difference of operations, but a single part of the completion of the code, then you need to use the first option.
If, if some condition is not fulfilled, the continuation of the program (method) does not make sense anymore , then it is logical to use the second option.
The advantages of the second method in this context are obvious. When analyzing a code, it is simply easier for you to see and keep in your head the conditions under which code execution will end, therefore you use it. After all, in fact, this is a boundary condition that interrupts the main code.
Suppose there is a task:
Write a controller method in which to issue an error if there is no record, and if successful, change the name field to 1, save to the database and display all information on the user. If the user’s name is Ivan, then just reset the password, but do not change the name.
$user = Users::find($id); if (!$user) { throw new BadRequestException("User not found"); } if ($user->getName()=="Ivan") { $user->setPassword(null); } else { $user->setName(1); } $user->save(); var_dump($user->toArray());
There is a question of logic, because it is so convenient to read this code and it is immediately clear that if this user does not exist, the execution of the program will be interrupted and there is no sense to read further. Imagine that we use if else, then we get additional nesting if, which complicates the reading of the program and its visibility:
$user = Users::find($id); if ($user) { if ($user->getName()=="Ivan") { $user->setPassword(null); } else { $user->setName(1); } $user->save(); var_dump($user->toArray()); } else { throw new BadRequestException("User not found"); }
We, as a matter of fact, here have carried out the basic code of the program in a condition that is not quite right. After all, the entire controller method may depend on this $user , and you will have to render all the code in an if.
It seems to me that you need to avoid unnecessary nesting , if there is a reasonable solution method.
unless(unless)! Well, you can stillif-not(Clojure) . - D-side