Personally, i see multiple "Tasks" in that code
- Start the application
- Count from 1 to 100
- Decide what to print for the current number
- Print it
The "Start" is for me an extra Task, because if i want that my application behaves differently on different environments (count to 100 on my local machine, but count to 1 Million on my super computer), than this would be a place to get the desired information and then forward it to the "functionality".
Yes this is over engineered for this small code example, but we lean with small code examples and then apply it to big applications. Therefor i like to take the big gun for small examples, as long as the goal is training. :-)
In my eyes, the following code is much longer, but its easier to understand, because each methodname gives a "context" what will happen in it. That makes it easier to follow and understand the underlying code.
Also, when the "tasks" are logically separated, then its much easier to apply changes to it. Changing the "rules" would only mean to change the convertNumber
function. Changing the way it should print the result would be only to change the output
method.
Also it would be quite easy to extract those functionalities in extra classes, and inject them. Then it would be a breeze to decide on the outside (environment) that the output should be done via System.out.println
or via a graphical interface.
But as always, many ways bring us to our goal(s). And as always if you choose one way, then you get good things, but you have to pay for them. My approach gives flexibility, but it its much more writing. The minimal slower performance would be only an argument in a high performance environment, i think, where we have to count each cycle.
public class FizzBuzzApp {
public static void main(String[] args) {
FizzBuzz game = new FizzBuzz();
game.playGame();
}
}
public class FizzBuzz {
public void playGame(){
for (int numbers = 1; numbers <= 100; numbers++) {
String result = convertNumber(number);
output(result);
}
}
private String convertNumber(int number) {
if (numbers % 3 == 0 && numbers % 5 == 0) {
return "Fizz Buzz";
} else if (numbers % 3 == 0) {
return "Fizz";
} else if (numbers % 5 == 0) {
return "Buzz";
} else {
return String.valueOf(number);
}
}
private void output(String value) {
System.out.println(value);
}
}
Happy to hear about your opinion about my approach