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. --
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php




Reply via email to