Purists are theorists, not do-orists. I'm a do-orist. Let's say I have a N-tree of objects and some function that walks the tree and executes itself on each child of a given node. Now, I want to stop walking the tree if any child returns 0 instead of 1.
# Impure
sub walk_and_do
{
my $self = shift;
foreach my $child (@{$self->children})
{
return 0 unless $child->walk_and_do;
}
return 0 unless $self->do_my_stuff;
return 1;
}
#####
# Pure
sub walk_and_do
{
my $self = shift;
my $rc = 1;
foreach my $child (@{$self->children})
{
$rc = $child->walk_and_do;
last unless $rc;
}
unless ($rc)
{
$rc = $self->do_my_stuff;
}
return $rc;
}
I think that the first is clearer and cleaner. There are less levels of indentation. Torvalds says in his style guide that there should never be more than 3 levels of indentation. If you're constantly checking codes and values, that simply won't work. I often find it harder to read code with 1 entry and 1 exit vs. 1 entry and N intelligently-designed exits.
Exit when appropriate, not when some schmuck with a bunch of letters after their name tells you. I work for a living.
------ We are the carpenters and bricklayers of the Information Age. Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement. |