이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

Metadata

ID: java-code-style/control-statement-braces

Language: Java

Severity: Notice

Category: Code Style

Description

Omitting braces {} is valid in multiple statements, such as, for loops, if statements, and while loops. However, enforcing the use of control braces throughout your codebase will make the code more consistent and can make it easier to add statements in the future.

Non-Compliant Code Examples

public class Foo {
    int x = 0;

    public void bar() {
        String message;
        if (randomNumber < something)
            message = "foo";
        else
            message = "bar";

        if (randomNumber < something) {
            message = "foo";
        }
        else
            message = "bar";

        if (randomNumber < something)
            message = "foo";
        else {
            message = "bar";
        }
    }
}
public class Foo {
    int x = 0;

    public void bar() {
        // while loop - no braces
        while (true)
            x++;

        // for loop - no braces
        for (int i = 0; i < 42; i++)
            x++;

        // if only - no braces
        if (true)
            x++;
        
        // if/else - no braces
        if (true)
            x++;
         else 
            x--;
        
        // do/while - no braces
        do
            i++;
        while (true);
        
        // case - no braces - allowed by default
        switch(i) {
            case (i < 42):
                return "foo";
            default: 
                return "bar";
        }
    }
}

Compliant Code Examples

public class Foo {
    List list = new ArrayList();

    public void bar() {
        String message;
        if(list.size() == 0) {
            message = "empty";
        } else if (list.size() == 1) {
            message = "solo";
        } else {
            message = "multiple";
        }
    }
}
public class Foo {
    int x = 0;

    public void bar() {
        // while loop - with braces
        while (true) {
            x++;
        }

        // for loop - with braces
        for (int i = 0; i < 42; i++) {
            x++;
        }

        // if only - with braces
        if (true) {
            x++;
        }
            
        // if/else - with braces
        if (true) {
            x++;
        } else {
            x--;
        }
    
        // do/while - with braces
        do {
            i++;
        }
        while (true);
        
        // case - with braces
        switch(i) {
            case (i < 42) {
                return "foo";
            }
            default {
                return "bar"
            }
        }
    }
}
PREVIEWING: dgreen15/github-error-fix