Avoid multiple HTTP requests by handling exceptions

public function move($from, $to)
{
    if(!$this->exists($from)){
        return false;
    }

    if($this->exists($to)){
        return false;
    }

    $result = $this->adapter->getClient()->move($from, $to);

    return $result ? true : false;
}

Every call to the exists method will fire an API request to see if the file exists before trying to move it to the new destination.
Alternative solution.

public function move($from, $to)
{
    try{
        $result = $this->adapter->getClient()->move($from, $to);
        
        return $result ? true : false;
    }catch (Exception_BadResponseCode $e){
        /* exception message can be:
            - destination file already exists.
            - $from file not found, etc.
        */

        return false;
    }
}

The second method is only firing one request to handle the operation.
whats the best approach and why?

Thanks

Surely it won’t be firing HTTP requests to check for the existence and non-existence respectively of the from and to files, because the PHP code runs on the server which is presumably where the files are located in any case.

I suspect the second solution will be slightly faster, albeit possibly not to an extent that you can detect it. If we assume that the move() function will also check that the source exists and the destination does not, all you’re achieving in the first code is to duplicate those checks. This might allow you to handle the errors more elegantly, depending on what information comes back from move() when it fails.

The move and exists methods are checking file on your Dropbox account, so its an HTTP request every time. Also, the move method will check after going to the Dropbox server. I think its double work to check using exists method. Thanks

Seems like you answered your own question.

The second approach is best because you’re “only firing one request to handle the operation.”

And also because between the time you check if the files exist and then move them, one of the files may be have been moved/deleted/etc, in which case the call to move() will fail anyway.

1 Like

Ah, I hadn’t realised you were dealing with files elsewhere.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.