Content

Clean Code, Refactoring, Real world Example (programming)

A part of Articles.  submit an article

posted by owen on Thu, 28th Apr 2016 at 8:02 am .

Here is a real world example of a long function that I presently use in production. The function creates/updates the meta information about a file or directory that is passed to it. The code is roughly 40 lines long. I could have chosen a longer function but for the purpose of the internet (aka social media) this seemed to be the most suitable. I am interested to see the ways this code can be "cleaned" up, code "smell"/bugs removed and made more maintainable as mentioned in JeremyBytes - Clean Code: The Refactoring Bits (video);


//save the meta information for a file to disk

function file_dir_set_meta($path, $data, $fullpath=false ){

        global $metafile_ext, $metafile_directory, $default_dir;

        $tags=''; //temp tag string         if(isset($data['tags'])) $tags .= $data['tags'];

        if($fullpath){                 $path=substr($path, strlen($default_dir), strlen($path) ); //convert absolute to relative         }

        if(isset($data['name'])) { //create tags from the name if available                 if( trim($data['name'])!='' ) $tags.=','.$data['name'];         }

        file_delete_all_tag_refs($path); //delete old tags                  tags_save( $path, $tags ); //save/update tag info

        $path = meta_filename($default_dir . $path);         $meta_filename=$metafile_directory . $path .$metafile_ext;

        if( !is_array($data) | count($data)==0 ){                 //delete the meta file if it has no data                 file_dir_delete_meta($path);         } else {                 //save the data to the meta file                 unset($data['domove']); //remove garbage and empty keys                 unset($data['dest_fold']);                 unset($data['unlink']);                 if(array_get($data,'sort','nothing')=='') unset($data['sort']);

                if( !flock_put_contents($meta_filename, serialize($data) ) ) return false; //write file         }

        //done         return true; }

Conclusion

Sorry that there is no colouring on the code but its PHP and it should be pretty easy to read. You can post your cleaned version in the comments or where ever. There are many ways to clean code as mentioned in the Clean Code discussion but cleaning code should not be the focus of software development.


permanent link, visited 96 times, Post your comments on this article. .

comments

    Comment list is empty. You should totally be the first to Post your comments on this article.


comment