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

What do you think of my Recursive FizzBuzz?

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

Problem

I wanted to see if I fully understood recursion so I attempted the FizzBuzz challenge and applied recursion to it.

Did I do it correctly? Is this good code? Is there a more efficient way of doing it? How can I improve?

//---------------------------------------------------------------------------------------
//[RecurFizzBuzz]
//  FizzBuzz using recursion
//---------------------------------------------------------------------------------------
// Author : Jimmy
//---------------------------------------------------------------------------------------

public class RecurFizzBuzz {

 // Specify a range to recurse, starts at int a, ends at int b
 public static void recurse(int a, int b){

  if(a <= b){
   if(a % 3 == 0 && a % 5 == 0){
    System.out.println("FizzBuzz");
   } else if(a % 3 == 0){
    System.out.println("Fizz");
   } else if(a % 5 == 0){
    System.out.println("Buzz"); 
   } else {
    System.out.println(a);
   }
   recurse(++a, b);
  } else {   
   System.exit(0);
  }
 }

 public static void main(String[]args) {
  recurse(1, 100);
 }
}

Solution

-
It's worth to mention a disadvantage of recursion: the possibility of stack overflow. Calling recurse(1, 6500) throws a StackOverflowError on my machine.

-
a % 3 == 0 && a % 5 == 0 could be a % 15 == 0. (Deleted, based on @QPaysTaxes's comment.)

-
recurse isn't a descriptive method name. printFizzBuzz would be better.

-
Use longer variable names for the parameters which explain the purpose, for example: lowerBound and upperBound.
They're easier to read and maintain.


Without proper names, we are constantly decoding and reconstructing the
information that should be apparent from reading the code alone.

(From codesparkle's former answer.)

-
System.exit isn't the nicest way to stop the recursion. You could use a simple return or omit the whole else block since the method returns anyway.

Context

StackExchange Code Review Q#18820, answer score: 10

Revisions (0)

No revisions yet.