On Dec 14, 2006, at 11:20 PM, Matisse Enzer wrote:


On Dec 14, 2006, at 3:05 PM, Michael G Schwern wrote:

Matisse Enzer wrote:
   sub complexity_of_six {
       my $bar = shift;
       my $total = 0;
       my $type = ref $bar;
       if ( ! $type ) {
           $total = $bar;
       }
       elsif ( $type eq 'ARRAY' ) {
           foreach my $baz ( @{$bar} ) {
               $total += $baz;
           }
       }
       else {
           confess("Don't know how to handle refs to $type");
       }
       return $total;
   }

I'm missing something, I only count 3 paths. if, elsif and else. The confess() might count (die/throw exception) but its the only path through the else. Same with the loop, its the only path through the elsif.


I over-simplified my explanation. It's not exactly paths-through- the-code.

The complexity "points" in that example are:

   1 for the subroutine itself.
   1 for the "if"
   1 for the ! logic operator in the if condition
   1 for the elsif
   1 for the "ne" logic operator in the elsif condition
   1 for the else
  ----
   6 total

That can't be right. Negation does not contribute to complexity. Instead, I believe it is the for loop and the exit points that are increasing your count. Consider rewriting the for as ifs and gotos:

   sub complexity_of_six {
       my $bar = shift;
       my $total = 0;
       my $type = ref $bar;
       if ( ! $type ) {
           $total = $bar;
       }
       elsif ( $type eq 'ARRAY' ) {
           my $_i = 0;
         LOOP:
           goto DONE if ($_i >= @{$bar});
           my $baz = $bar->[$_i];
           $total += $baz;
           $_i++;
           goto LOOP;
         DONE:
       }
       else {
           confess("Don't know how to handle refs to $type");
       }
       return $total;
   }

Then the decision points are:
  1) if ( ! $type )
  2) if ( $type eq 'ARRAY')
  3) if ($_i >= @{$bar})
  4) else
and the end points are
  1) confess("Don't know how to handle refs to $type");
  2) return $total

So I actually count a complexity of 7 (num decision points + num endpoints + 1) if I've understood the wiki definition correctly.
  http://en.wikipedia.org/wiki/Cyclomatic_complexity

Chris

--
Chris Dolan, Software Developer, Clotho Advanced Media Inc.
608-294-7900, fax 294-7025, 1435 E Main St, Madison WI 53703
vCard: http://www.chrisdolan.net/ChrisDolan.vcf

Clotho Advanced Media, Inc. - Creators of MediaLandscape Software (http://www.media-landscape.com/) and partners in the revolutionary Croquet project (http://www.opencroquet.org/)


Reply via email to