Re: GOTO operator

From: Date: Fri, 30 Jul 2004 20:27:25 +0000
Subject: Re: GOTO operator
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-11727@lists.php.net to get a copy of this message
On Jul 30, 2004, at 10:35 AM, Shaun Thomas wrote:
Paul G wrote:
function pseudocode() {
    $a=allocate_resource_z();
    $b=allocate_resource_y();
    $res=do_stuff();
    if(!$res)
        goto err_out;
    $c=allocate_resource_x();
    $res=do_more_stuff();
    if(!$res)
        goto err_out;
    $d=allocate_resource_foo();
    $res=do_even_more_stuff();
    if(!$res)
        goto err_out;
    return true;
err_out:
    free_resouce($a);
    free_resouce($b);
    if(isset($c)) free_resouce($c);
    if(isset($d)) free_resouce($c);
    return false;
}
While this is valid, it's not really a good example of pseudocode that requires a goto to be efficient. You could do the same thing with try/catch/throw: function pseudocode() { $a=allocate_resource_z(); $b=allocate_resource_y(); try {
    $res=do_stuff();
    if(!$res)
      throw SOME_ERROR;
    $c=allocate_resource_x();
    $res=do_more_stuff();
    if(!$res)
      throw SOME_ERROR;
    $d=allocate_resource_foo();
    $res=do_even_more_stuff();
    if(!$res)
      throw SOME_ERROR;
    return true;
} catch SOME_ERROR {
    free_resouce($a);
    free_resouce($b);
    if(isset($c)) free_resouce($c);
    if(isset($d)) free_resouce($c);
    return false;
} }
I would prefer to write the original code as follows: function pseudocode() {
    try {
        $a = allocate_resource_z();
        $b = allocate_resource_y();
        $res = do_stuff();
        $c = allocate_resource_x();
        $res = do_more_stuff();
        $d = allocate_resource_foo();
        $res = do_even_more_stuff();
    } catch ( Exception $e ) {
        free_resouce($a);
        free_resouce($b);
        if(isset($c)) free_resouce($c);
        if(isset($d)) free_resouce($c);
        throw ($e);
    }
} Where did the if statements go? do_stuff(), do_more_stuff(), and do_even_more_stuff() should throw exceptions rather than return boolean error indicators. (Following the principle of raising the error as soon as it can be detected.) This implementation of pseudocode() also re-throws the exception, rather than use a boolean error return value. One major benefit of exceptions is to eliminate conditional statements as error codes "bubble up." goto does not help with this.

« previous php.internals (#11727) next »