Search code examples
phplaravelphpmd

else is never necessary and you can simplify the code to work without else


I got a message of PHPMD telling me:

else is never necessary and you can simplify the code to work without else on this portion of code:

if ($settings == null) {
        $settings = new self($arrSettings);
} else {
        $settings->fill($arrSettings);
}
$settings->save();

return $settings;

My question is : How should I avoid else(). The only way I see is duplicating $setting->save() and return.

Any idea?


Solution

  • Probably because it can be re-written as

    if ($settings === null) {
        $settings = new self; // or new self([]);
    }
    $settings->fill($arrSettings);
    $settings->save();
    
    return $settings;
    

    But, TBH, the entire thing looks like one big violation of SRP, because class instances should not be able to crate new instances of themselves. That just don't make any sense .. but then again, I am not an "artisan".