[nycphp-talk] structured programming in practice
Jayesh Sheth
jay_nyphp at fastmail.fm
Tue Jun 14 20:35:03 EDT 2005
Hello NYPHP members,
I thought I would ask your opinions on using structured programming (
see http://en.wikipedia.org/wiki/Structured_programming and
http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=31001
) principles. More specifically, what are your opinions on single points
of entry and exit for functions?
For example, consider the following three code snippets:
What if you are stuck using PHP 4, and you have to use any of the
following error handling methods instead of exceptions, which one would
you choose? If so, why? Thanks in advance for reading through these
snippets!
----
Snippet 1
function make_beverage($bev_type, &$bev)
{
if($bev_type == 'coffee')
{
$aw = add_cwater($bev);
if ( ! $aw)
{
return false;
}
$bc = brew_coffee($bev);
if (!$bc)
{
return false;
}
return true;
}
else if ($bev_type == 'tea')
{
$aw = add_twater($bev)
{
if (! $aw)
{
return false;
}
}
$atb = add_tea_bag($bev);
if ( ! $atb )
{
return false;
}
return true;
}
}
-----
Snippet
function make_beverage($bev_type, &$bev)
{
if($bev_type == 'coffee' || $bev_type == 'tea')
{
if($bev_type == 'coffee')
{
$aw = add_cwater($bev);
if ($aw)
{
$bc = brew_coffee($bev);
if ($bc)
{
$return = true;
}
else
{
$return = false;
}
}
else
{
$return = false;
}
}
else
{
$aw = add_twater($bev)
if ($aw)
{
$atb = add_tea_bag($bev);
if ( $atb )
{
$return = true;
}
else
{
$return = false;
}
}
else
{
$return = false;
}
}
return $return;
}
}
----
Both Snippet 1 and Snippet 2 introduce an interesting problem. $bev is
passed in by reference, and so the functions that make_beverage() call
also act on $bev, which is defined outside of make_beverage(), before
make_beverage() is called.
So, if you want to know what exactly failed, what would you do?
Would you use return codes? For example:
----
Snippet 3
function make_beverage($bev_type, &$bev)
{
if($bev_type == 'coffee')
{
$aw = add_cwater($bev);
if ( ! $aw)
{
return -1;
}
$bc = brew_coffee($bev);
if (!$bc)
{
return -2;
}
return 1;
}
else if ($bev_type == 'tea')
{
$aw = add_twater($bev)
{
if (! $aw)
{
return -3;
}
}
$atb = add_tea_bag($bev);
if ( ! $atb )
{
return -4;
}
return 1;
}
}
----
Or would you do something like:
----
Snippet 4
function make_beverage($bev_type, &$bev, &$errs)
{
if($bev_type == 'coffee' || $bev_type == 'tea')
{
if($bev_type == 'coffee')
{
$aw = add_cwater($bev);
if ($aw)
{
$bc = brew_coffee($bev);
if ($bc)
{
$return = true;
}
else
{
$errs[] = 'bc';
$return = false;
}
}
else
{
$errs[] = 'aw';
$return = false;
}
}
else
{
$aw = add_twater($bev)
if ($aw)
{
$atb = add_tea_bag($bev);
if ( $atb )
{
$return = true;
}
else
{
$errs[] = 'atb';
$return = false;
}
}
else
{
$errs[] = 'aw';
$return = false;
}
}
return $return;
}
}
----
Best regards,
- Jay
More information about the talk
mailing list