HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Is calling a function only twice a good use of recursion?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
twicerecursionfunctiongoodcallingonlyuse

Problem

Is this, technically, a recursive function? It only gets called once by itself, but it cleaned up my code quite a bit, I think. Or, does it needlessly complicate the code?

sub check_backlog {
    my $topic        = shift;
    my $prev_backlog = shift;
    my $backlog      = undef;
    my @status = `$CMD -topicstat $topic`;
    foreach (@status) {
        if (/Message count: (\d+)/) {
            $backlog = $LAST_PAREN_MATCH;
            if ( !$prev_backlog && $backlog > 1 ) {
                sleep $topic_wait_time;
                check_backlog( $topic, $backlog );
            }
            elsif ( $backlog > $prev_backlog ) {
                check_over_thresholds($backlog);
            }
        }
    }
    return $backlog;
}

Solution

Yes, every function which calls itself is considered a recursive function.

Recursion is really useful when traversing trees and such.

As I don't fully understand Perl, I can't really tell whether this case is proper use of recursion, perhaps also provide the intent of your code.

UPDATE

If you simply want to see whether data is passing (or not passing) through a queue, I wouldn't find recursion to be a suitable implemention.

I would expect a function which returns either true or false after a given amount of time, or immediately when data is passing through.

Consider the following pseudo code:

function isDataPassing( queue, time )
{
   headOfQueue = queue.peek();
   dataPassing = false;
   while ( timePassed < time )
   {
       if ( headOfQueue != queue.peek() )
       {
           dataPassing = true;
           break;
       }
   }

   return dataPassing;
}


I can't help you with how you would go about implementing this in Perl. StackOverflow is a better location to ask such a question.

Code Snippets

function isDataPassing( queue, time )
{
   headOfQueue = queue.peek();
   dataPassing = false;
   while ( timePassed < time )
   {
       if ( headOfQueue != queue.peek() )
       {
           dataPassing = true;
           break;
       }
   }

   return dataPassing;
}

Context

StackExchange Code Review Q#1095, answer score: 3

Revisions (0)

No revisions yet.