[JAVA] Easy to maintain FizzBuzz

Introduction

When I registered on a skill evaluation site for a change of pace, the first problem was FizzBuzz.

It's not fun to just solve FizzBuzz, so I'll write that FizzBuzz, which is easy to maintain in my own way, looks like this.

The code that was finally adopted

Actually, it is a little different from the submitted answer, but as a result of refactoring after submitting the answer, it became as follows.

public final class FizzBuzz {
    /**
     *Output numerical values from 1 to 100 to standard output as shown below.
     * <p>
     * <ul>
     * <li>For multiples of 3 and 5: "FizzBuzz"And output</li>
     * <li>If it is a multiple of 3 and not a multiple of 5: "Fizz"And output</li>
     * <li>For multiples of 5 instead of multiples of 3: "Buzz"And output</li>
     * <li>If neither:Output numerical value as it is</li>
     * </ul>
     *
     * @param args unused
     */
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            boolean fizz = (i % 3 == 0);
            boolean buzz = (i % 5 == 0);

            if (fizz && buzz) {
                System.out.println("FizzBuzz");
            } else if (fizz) {
                System.out.println("Fizz");
            } else if (buzz) {
                System.out.println("Buzz");
            } else {
                System.out.println(i);
            }
        }
    }
}

Write Javadoc exactly

The specification of the main () method is described in Javadoc. It is usually not possible to leave unused arguments, but this time it is a main () method, so the unused arguments are described as "unused".

Introduced explanatory variables

It's okay to write ʻif (i% 3 == 0)`, but it's a bit unpleasant to see the same expression twice, so I've included an explanatory variable.

It may be better for the variable name to represent "multiple of 3" or "multiple of 5", but I couldn't think of a good name, and this time, "if it's a multiple of 3 & a multiple of 5," fizz "&" buzz " And output ”, so I chose the variable names fizz and buzz.

Put parentheses so you don't get lost in operator precedence

boolean fizz = (i % 3 == 0);

This is the same even if you write the following as a result.

boolean fizz = i % 3 == 0;

But without the parentheses, it can be a confusing moment for the reader of the code. It's a good idea to put parentheses so as not to confuse the reader.

Do not omit the curly braces

You can write it as follows, but if you omit the curly braces, you are more likely to make a mistake when additional processing is added later, so I have not omitted it.

Well, it may be an old habit because you will notice it if it is properly indented.

public final class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            boolean fizz = (i % 3 == 0);
            boolean buzz = (i % 5 == 0);

            if (fizz && buzz) System.out.println("FizzBuzz");
            else if (fizz) System.out.println("Fizz");
            else if (buzz) System.out.println("Buzz");
            else System.out.println(i);
        }
    }
}

Do not write ʻi% 15 == 0`

I often see code that says ʻif (i% 15 == 0) `in the condition judgment.

This is not a mistake, but the FizzBuzz spec never mentions the number "15".

Obviously it's 3x5, of course, but I've tried not to give the number 15 to avoid any confusion.

Add final to class

There is no inheritance or crap in a class that has only static methods, In the past, I just didn't add final, so I was inherited and cried. Except for some Exceptions, I basically add final.

Do not use Range

In Java, the method of indicating the range is not supported by the language, so I did not adopt the following writing method and used a simple for statement that anyone can understand. Which one you actually use depends on the situation.

import java.util.stream.IntStream;

public static void main(String[] args) {
    IntStream.rangeClosed(1, 100).mapToObj((i) -> {
        if (i % 3 == 0 && i % 5 == 0) {
            return "FizzBuzz";
        } else if (i % 3 == 0) {
            return "Fizz";
        } else if (i % 5 == 0) {
            return "Buzz";
        } else {
            return String.valueOf(i);
        }
    }).forEach(System.out::println);
}

Of course, if Ruby is supported by the language, write as follows.

(1..100).each do |i|
   ...
end

Do not make unnecessary abstractions

For example, thinking "I may output other than standard output later, so I want to be able to return it as List ", I can write it as follows (aside from the method name run).

However, it is rarely needed in practice, and there are many cases where we cried because of unnecessary abstraction. It's enough to refactor when needed.

import java.util.ArrayList;
import java.util.List;

public final class FizzBuzz {
    public static void main(String[] args) {
        List<String> results = FizzBuzz.run();

        for (String result : results) {
            System.out.println(result);
        }
    }

    private static List<String> run() {
        List<String> results = new ArrayList<>();

        for (int i = 1; i <= 100; i++) {
            boolean fizz = (i % 3 == 0);
            boolean buzz = (i % 5 == 0);

            if (fizz && buzz) {
                results.add("FizzBuzz");
            } else if (fizz) {
                results.add("Fizz");
            } else if (buzz) {
                results.add("Buzz");
            } else {
                results.add(String.valueOf(i));
            }
        }

        return results;
    }
}

in conclusion

It's like, "What should I do if I'm serious about FizzBuzz?", But it was quite interesting to write down what I was thinking about when coding.

Recommended Posts

Easy to maintain FizzBuzz
Write code that is easy to maintain (Part 1)
Write code that is easy to maintain (Part 4)
Write code that is easy to maintain (Part 3)
Easy to create Processing library
Function is very easy to use
SpringBoot + Redis Easy to make demo
[Rails] Easy way to check columns
Easy to use Cloud Firestore (Android)
to_ ○
Let's write a code that is easy to maintain (Part 2) Name
Easy to make Slack Bot in Java
Easy way to set iOS app icon
How to blur an image (super easy)
[Swift] Easy to implement modal with PanModal
Easy way to create JSP custom tags
[Easy] How to upgrade Ruby and bundler
Easy to trip with Java regular expressions