Avoid switch with very few branches

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Metadata

ID: java-best-practices/switch-few-branches

Language: Java

Severity: Warning

Category: Best Practices

Description

switch statements are used to trigger different block of code based on different values. Developers should avoid switch statements with less than 3 branches. If a switch statement has less than 3 branches, we should rather use a if statement.

Non-Compliant Code Examples

class Main {
    public static void main(String[] args) {
        switch (condition) {
            case value1:
                break;
            default:
                break;
        }

        switch (condition) {
            case value1:
                break;
            case value2:
                break;
            default:
                break;
        }
    }
}

Compliant Code Examples

class Main {
    public static void main(String[] args) {
        switch (condition) {
            case value1:
                break;
            case value2:
                break;
            default:
                break;
        }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis