Skip to main content
7 of 9
added revised code
NaN
  • 205
  • 1
  • 3

Attempt at the Most dynamic FizzBuzz possible in Java

I was trying to come up with the most dynamic fizzbuzz answer I could.. and well, this is what I came up with:

public static void main(String[] args) {

    ultraFizzBuzz((Integer arg) -> {
        String retVal = "";
        if(arg % 3 == 0) { retVal += "fizz"; }
        if(arg % 5 == 0) { retVal += "buzz"; }
        return retVal;
    });
}

public static void ultraFizzBuzz(modConditions<Integer> tester) {
    
    for(int i = 1; i < 100; i++) {
        String result = tester.test(i);
        if(result != "")
            System.out.println(tester.test(i));
        else
            System.out.println(i);
    }
}

In here the modConditions is an interface with a method (test) that returns type String.

What I was basically trying to do is create a super dynamic function that lets you add as many fizzes and buzzes and pops as you wanted.. but I think in the process accidentally made it so you end up writing 90% of the code in a lambda statement everytime you want to call it.

Am I overcomplicating things? Would this be considered bad programming practice?

EDIT:

Based on suggestions, here is revised code:

static List<Function<Integer, String>> fizzBuzzList = Arrays.asList(
    x -> x % 3 == 0 ? "fizz" : "",
    x -> x % 5 == 0 ? "buzz" : "",
    x -> x % 7 == 0 ? "pop"  : ""
);

public static void main(String[] args) {
    
    fizzBuzz(fizzBuzzList);
}

public static void fizzBuzz(List<Function<Integer, String>> tester) {
    
    for(int i = 1; i <= 100; i++) {
        boolean hasPrinted = false; // will be true if any functions in tester return non-empty string
        
        for(Function<Integer, String> f : tester) {
            String result = f.apply(i);
            
            if(!result.isEmpty()) {
                System.out.print(f.apply(i));
                hasPrinted = true;
            }
        }
        
        if(!hasPrinted) {
            System.out.print(i);
        }
        
        System.out.println();
    }
}

More logic is now based inside of the actual function

NaN
  • 205
  • 1
  • 3