부스트코스 웹개발 프로젝트를 진행하고 있습니다. 자바 코드 스타일도 평가 기준에 포함되어있어 한 번 공부 해보려고 합니다. 시간 나는대로 틈틈이 번역해보겠습니다.
Terminology Note: block-like construct refers to the body of a class, method or constructor. Note that, by Section 4.8.3.1 on array initializers, any array initializer may optionally be treated as if it were a block-like construct.
용어 참고 : 블록 유사 구조는 클래스, 메서드 또는 생성자의 본문을 나타냅니다. 배열 이니셜 라이저에 대한 섹션 4.8.3.1에 따라 모든 배열 이니셜 라이저는 선택적으로 블록과 유사한 구조 인 것처럼 처리 될 수 있습니다.
Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement.
if, else, for, do, while 문에는 본문이 비어 있거나 단일 문장만 쓰는 경우에도 중괄호를 함께 사용합니다.
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs:
비어 있지 않은 블록 및 블록 유사 구조의 경우 Kernighan and Ritchie 스타일을 따릅니다.
No line break before the opening brace.
Line break after the opening brace.
Line break before the closing brace.
Line break after the closing brace, only if that brace terminates a statement or terminates the body of a method, constructor, or named class. For example, there is no line break after the brace if it is followed by else or a comma.
Examples:
return () -> {
while (condition()) {
method();
}
};
return new MyClass() {
@Override public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
} else if (otherCondition()) {
somethingElse();
} else {
lastThing();
}
}
};
A few exceptions for enum classes are given in Section 4.8.1, Enum classes.
열거 형 클래스에 대한 몇 가지 예외는 섹션 4.8.1, 열거 형 클래스에 있습니다.
An empty block or block-like construct may be in K & R style (as described in Section 4.1.2). Alternatively, it may be closed immediately after it is opened, with no characters or line break in between ({}), unless it is part of a multi-block statement (one that directly contains multiple blocks: if/else or try/catch/finally).
빈 블록이나 유사 블록 구조는 K&R 스타일로 해도되지만 블록을 여는 즉시 닫아도 된다(if/else나 try/catch/finally와 같은 다중 블록 명령문은 허용하지 않음).
Examples:
// 허용
void doNothing() {}
// 허용
void doNothingElse() {
}
// 불허(multi-block statement)
try {
doSomething();
} catch (Exception e) {}
Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. (See the example in Section 4.1.2, Nonempty blocks: K & R Style.)
새 블록 또는 블록과 유사한 구조가 열릴 때마다 들여 쓰기가 두 칸씩 증가합니다. 블록이 끝나면 들여 쓰기는 이전 들여 쓰기 수준으로 돌아갑니다. 들여 쓰기 수준은 블록 전체의 코드와 주석 모두에 적용됩니다. (섹션 4.1.2, 비어 있지 않은 블록 : K & R 스타일의 예를 참조하십시오.)
Each statement is followed by a line break.
각 문장 뒤에서는 줄 바꿈할 것.
Java code has a column limit of 100 characters. A "character" means any Unicode code point. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.5, Line-wrapping.
Java 코드의 열 제한은 100 자입니다. "문자"는 모든 유니 코드 코드 포인트를 의미합니다. 아래 명시된 경우를 제외하고이 제한을 초과하는 모든 줄은 섹션 4.5, 줄 바꿈에 설명 된대로 줄 바꿈되어야합니다.
Each Unicode code point counts as one character, even if its display width is greater or less. For example, if using fullwidth characters, you may choose to wrap the line earlier than where this rule strictly requires.
각 유니 코드 코드 포인트는 표시 너비가 더 크거나 작더라도 하나의 문자로 계산됩니다. 예를 들어 전각 문자를 사용하는 경우 100자를 채우기 전에 줄을 줄 바꿔도 된다?(좀 더 번역이 필요..)
Exceptions:
Terminology Note: When code (that might otherwise legally occupy a single line) is divided into multiple lines, this activity is called line-wrapping.
용어 참고 : 규칙을 어기지 않고도 코드를 한 줄로 쓸 수 있음에도 줄을 나누는 것을 줄 바꿈이라고 한다.
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.
모든 상황에서 줄 바꿈하는 방법을 정확히 보여주는 포괄적이고 결정적인 공식은 없다. 같은 코드를 줄 바꿈하는 여러 가지 유효한 방법이 많이 있다.
Note: While the typical reason for line-wrapping is to avoid overflowing the column limit, even code that would in fact fit within the column limit may be line-wrapped at the author's discretion.
참고 : 줄 바꿈의 일반적인 이유는 열 제한(100자)을 초과하지 않도록하는 것이지만, 열 제한에 맞는 코드도 작성자가 재량껏 줄 바꿈 할 수 있다.
Tip: Extracting a method or local variable may solve the problem without the need to line-wrap.
팁 : 메서드 또는 지역 변수를 추출하면 줄 바꿈없이 문제를 해결할 수 있습니다.(글로는 이해부족)
The prime directive of line-wrapping is: prefer to break at a higher syntactic level. Also:
줄 바꿈의 주요 지침: 더 높은 수준의 구문에서 중단.
.: :의 두 콜론& Bar>)| BarException e)):에도 적용된다.A method or constructor name stays attached to the open parenthesis (() that follows it.
메서드 또는 생성자 이름은 뒤에 오는 여는 소괄호("(")에 붙어있어야 한다.
A comma (,) stays attached to the token that precedes it.
쉼표(,)는 쉼표 바로 앞에 오는 토큰에 붙인다(쉼표 줄바꿈x).
A line is never broken adjacent to the arrow in a lambda, except that a break may come immediately after the arrow if the body of the lambda consists of a single unbraced expression. Examples:
람다식은 화살표 바로 옆에서는 줄 바꿈 할 수 없다(본문이 중괄호 없이 한 문장밖에 없어서 화살표 다음에 바로 줄 바꿈이 가능한 경우 제외).
MyLambda<String, Long, Object> lambda =
(String label, Long value, Object obj) -> { //화살표 바로 옆에서 줄 바꿈 불허
...
};
//예외
Predicate<String> predicate = str ->
longExpressionInvolving(str);
Note: The primary goal for line wrapping is to have clear code, not necessarily code that fits in the smallest number of lines.
참고 : 줄 바꿈의 기본 목표는 코드 라인 수를 최소한으로 줄이는 게 아니라 명확한 코드를 만드는 것입니다.
When line-wrapping, each line after the first (each continuation line) is indented at least +4 from the original line.
When there are multiple continuation lines, indentation may be varied beyond +4 as desired. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements.
Section 4.6.3 on Horizontal alignment addresses the discouraged practice of using a variable number of spaces to align certain tokens with previous lines.
A single blank line always appears:
한 줄 띄우는 케이스:
Between consecutive members or initializers of a class: fields, constructors, methods, nested classes, static initializers, and instance initializers.
Exception: A blank line between two consecutive fields (having no other code between them) is optional. Such blank lines are used as needed to create logical groupings of fields.
Exception: Blank lines between enum constants are covered in Section 4.8.1.
연속 멤버 또는 클래스의 이니셜 라이저 간 : 필드(멤버 변수), 생성자, 메서드, 중첩 클래스, 정적 이니셜 라이저 및 인스턴스 이니셜 라이저
예외 : 두 개의 연속 된 필드 사이에 다른 코드가없는 빈 줄은 선택 사항입니다. 이러한 빈 줄은 필드의 논리적 그룹을 만드는 데 필요에 따라 사용됩니다.
예외 : enum 상수 사이의 빈 줄은 섹션 4.8.1에서 다룹니다.
As required by other sections of this document (such as Section 3, Source file structure, and Section 3.3, Import statements).
이 문서의 다른 섹션에서 요구하는대로 (예 : 섹션 3, 소스 파일 구조 및 섹션 3.3, Import 문).
A single blank line may also appear anywhere it improves readability, for example between statements to organize the code into logical subsections. A blank line before the first member or initializer, or after the last member or initializer of the class, is neither encouraged nor discouraged.
가독성을 향상시키는 모든 곳에 빈 줄 하나가 나타날 수 있습니다. 예를 들어 코드를 논리적 하위 섹션으로 구성하는 명령문 사이와 같이.
첫 번째 멤버나 이니셜라이저 앞이나 클래스의 마지막 멤버나 이니셜라이저 뒤의 빈 줄은 내키는 대로..
(이니셜라이저가 생성자랑 좀 다른 거 같은데 대체 뭐지??)
Multiple consecutive blank lines are permitted, but never required (or encouraged).
여러 개의 연속 된 빈 줄이 허용되지만 필수 (또는 권장)는 아닙니다.
Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.
Separating any reserved word, such as if, for or catch, from an open parenthesis (() that follows it on that line
Separating any reserved word, such as else or catch, from a closing curly brace (}) that precedes it on that line
Before any open curly brace ({), with two exceptions:
@SomeAnnotation({a, b}) (no space is used)
String[][] x = {{"foo"}}; (no space is required between {{, by item 8 below)
On both sides of any binary or ternary operator. This also applies to the following "operator-like" symbols:
the ampersand in a conjunctive type bound: <T extends Foo & Bar>
the pipe for a catch block that handles multiple exceptions: catch (FooException | BarException e)
the colon (:) in an enhanced for ("foreach") statement
the arrow in a lambda expression: (String str) -> str.length()
but not
the two colons (::) of a method reference, which is written like Object::toString
the dot separator (.), which is written like object.toString()
After ,:; or the closing parenthesis ()) of a cast
On both sides of the double slash (//) that begins an end-of-line comment. Here, multiple spaces are allowed, but not required.
Between the type and variable of a declaration: List list
Optional just inside both braces of an array initializer
new int[] {5, 6} and new int[] { 5, 6 } are both valid
Between a type annotation and [] or ....
This rule is never interpreted as requiring or forbidding additional space at the start or end of a line; it addresses only interior space.
Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.
Here is an example without alignment, then using alignment:
private int x; // this is fine
private Color color; // this too
private int x; // permitted, but future edits
private Color color; // may leave it unaligned
Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a "blast radius." This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
Optional grouping parentheses are omitted only when author and reviewer agree that there is no reasonable chance the code will be misinterpreted without them, nor would they have made the code easier to read. It is not reasonable to assume that every reader has the entire Java operator precedence table memorized.
After each comma that follows an enum constant, a line break is optional. Additional blank lines (usually just one) are also allowed. This is one possibility:
private enum Answer {
YES {
@Override public String toString() {
return "yes";
}
},
NO,
MAYBE
}
An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer (see Section 4.8.3.1 on array initializers).
private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
Since enum classes are classes, all other rules for formatting classes apply.
Every variable declaration (field or local) declares only one variable: declarations such as int a, b; are not used.
Exception: Multiple variable declarations are acceptable in the header of a for loop.
Local variables are not habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
Any array initializer may optionally be formatted as if it were a "block-like construct." For example, the following are all valid (not an exhaustive list):
new int[] { new int[] {
0, 1, 2, 3 0,
} 1,
2,
new int[] { 3,
0, 1, }
2, 3
} new int[]
{0, 1, 2, 3}
The square brackets form a part of the type, not the variable: String[] args, not String args[].
Terminology Note: Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels (either case FOO: or default:), followed by one or more statements (or, for the last statement group, zero or more statements).
As with any other block, the contents of a switch block are indented +2.
After a switch label, there is a line break, and the indentation level is increased +2, exactly as if a block were being opened. The following switch label returns to the previous indentation level, as if a block had been closed.
Within a switch block, each statement group either terminates abruptly (with a break, continue, return or thrown exception), or is marked with a comment to indicate that execution will or might continue into the next statement group. Any comment that communicates the idea of fall-through is sufficient (typically // fall through). This special comment is not required in the last statement group of the switch block. Example:
switch (input) {
case 1:
case 2:
prepareOneOrTwo();
// fall through
case 3:
handleOneTwoOrThree();
break;
default:
handleLargeNumber(input);
}
Notice that no comment is needed after case 1:, only at the end of the statement group.
Each switch statement includes a default statement group, even if it contains no code.
Exception: A switch statement for an enum type may omit the default statement group, if it includes explicit cases covering all possible values of that type. This enables IDEs or other static analysis tools to issue a warning if any cases were missed.
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping (Section 4.5, Line-wrapping), so the indentation level is not increased. Example:
@Override
@Nullable
public String getNameIfPresent() { ... }
Exception: A single parameterless annotation may instead appear together with the first line of the signature, for example:
@Override public int hashCode() { ... }
Annotations applying to a field also appear immediately after the documentation block, but in this case, multiple annotations (possibly parameterized) may be listed on the same line; for example:
@Partial @Mock DataLoader loader;
There are no specific rules for formatting annotations on parameters, local variables, or types.
This section addresses implementation comments. Javadoc is addressed separately in Section 7, Javadoc.
Any line break may be preceded by arbitrary whitespace followed by an implementation comment. Such a comment renders the line non-blank.
Block comments are indented at the same level as the surrounding code. They may be in / ... / style or // ... style. For multi-line / ... / comments, subsequent lines must start with aligned with the on the previous line.
/*
Tip: When writing multi-line comments, use the / ... / style if you want automatic code formatters to re-wrap the lines when necessary (paragraph-style). Most formatters don't re-wrap lines in // ... style comment blocks.
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
public protected private abstract default static final transient volatile synchronized native strictfp
long-valued integer literals use an uppercase L suffix, never lowercase (to avoid confusion with the digit 1). For example, 3000000000L rather than 3000000000l.