Dry programming Sometimes i find myself repeating code , most of the time when business logic changes and we start implementing if statements.

One of the difficult things in programming is trying your code dry. It's not easy to not repeat yourself. This example is perfect working code but if the _chunk term needs change , it has to be changend in three places.

Original code



        if (is_null($companyId)) {
            if (!
auth()->check()) {
                
$path $mount '/remote/_chunks' $identifier;
            } else {
                
$path $mount '/' auth()->user->companyId '/_chunks' $identifier;
            }
        } else {
            
$path $mount '/' $companyId '/_chunks/' $identifier;
        }

        

Refactored code



        // implementend in two lines for readablity reasons
        $ifNoCompanyId = (!auth()->check() ? "remote" auth()->user->companyId);
        
$companyFolder $companyId ?? $ifNoCompanyId;

        
// or even shorter , but maybe less readable
        
$companyFolder $companyId ?? (!auth()->check() ? "remote" auth()->user->companyId);

        
$path $mount '/' $companyFolder '/_chunks/' $identifier;

        

Here is the output of the code

This is the output of original

This is the path : /mnt/path/123456789/_chunks/identifier

This is the output of refactor

This is the path : /mnt/path/123456789/_chunks/identifier

Want to learn more from LLoadout ?

LLoadout is your loadout for Laravel, helping you kickstart your development process. Besides this refactoring site we also make some cool packages and video tutorials !

Go to LLoadout on github