Simple Example of Making Code Easier to Read

Posted: 2015-09-17 10:37:22

Just a quick example

Before

    public function updateMarketoFolder($folder)
    {

        /**
         * If parent id found in array then use it else use root
         */
        if(isset($this->folders_and_meta_data[$folder['id']]))
        {
            $folder_meta_data = $this->folders_and_meta_data[$folder['id']];
        }
        elseif(isset($folder['parent']) && isset($folder['parent']['id']) && isset($this->folders_and_meta_data[$folder['parent']['id']]))
        {
            $folder_meta_data = $this->folders_and_meta_data[$folder['parent']['id']];
        }
        else
        {
            $folder_meta_data = $this->folders_and_meta_data['root'];
        }

        if(isset($folder['name']))
            $this->names[] = $folder['name'] . '--' . $folder_meta_data->id;


        $this->folders_and_meta_data[$folder['id']] = $folder_meta_data;

    }

Here is what we can do to make it easier to come back to six months later.

    public function updateMarketoFolder($folder)
    {

        if($this->hasOwnFolder($folder))
        {
            $folder_meta_data = $this->folders_and_meta_data[$folder['id']];
        }
        elseif($this->hasAParentAndParentHasFolder($folder))
        {
            $folder_meta_data = $this->folders_and_meta_data[$folder['parent']['id']];
        }
        else
        {
            $folder_meta_data = $this->getRootFolder();
        }

        if($this->checkItHasAName($folder))
            $this->names[] = $folder['name'] . '--' . $folder_meta_data->id;

        $this->folders_and_meta_data[$folder['id']] = $folder_meta_data;

    }

    private function hasOwnFolder($folder)
    {
        return isset($this->folders_and_meta_data[$folder['id']]);
    }

    private function hasAParentAndParentHasFolder($folder)
    {
        return isset($folder['parent']) && isset($folder['parent']['id']) && isset($this->folders_and_meta_data[$folder['parent']['id']]);
    }

    private function getRootFolder()
    {
        return $this->folders_and_meta_data['root'];
    }

    private function checkItHasAName($folder)
    {
        return isset($folder['name']);
    }

Just a lot easier to come back to an remember why and what I am doing in the if statements. Also just to read a bit more easily what the needs are here of the data.


Tags:

php clean code