readability-cli 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
guides/javaguide.md ADDED
@@ -0,0 +1,1189 @@
1
+ Google Java Style Guide
2
+
3
+
4
+
5
+ # Google Java Style Guide
6
+
7
+ ## 1 Introduction
8
+
9
+ This document serves as the **complete** definition of Google's coding standards for
10
+ source code in the Java™ Programming Language. A Java source file is described as being *in
11
+ Google Style* if and only if it adheres to the rules herein.
12
+
13
+ Like other programming style guides, the issues covered span not only aesthetic issues of
14
+ formatting, but other types of conventions or coding standards as well. However, this document
15
+ focuses primarily on the **hard-and-fast rules** that we follow universally, and
16
+ avoids giving *advice* that isn't clearly enforceable (whether by human or tool).
17
+
18
+ ### 1.1 Terminology notes
19
+
20
+ In this document, unless otherwise clarified:
21
+
22
+ 1. The term *class* is used inclusively to mean a normal class, record class, enum
23
+ class, interface or annotation type (`@interface`).
24
+ 2. The term *member* (of a class) is used inclusively to mean a nested class, field,
25
+ method, *or constructor*; that is, all top-level contents of a class except initializers.
26
+ 3. The term *comment* always refers to *implementation* comments. We do not
27
+ use the phrase "documentation comments", and instead use the common term "Javadoc."
28
+
29
+ Other "terminology notes" will appear occasionally throughout the document.
30
+
31
+ ### 1.2 Guide notes
32
+
33
+ Example code in this document is **non-normative**. That is, while the examples
34
+ are in Google Style, they may not illustrate the *only* stylish way to represent the
35
+ code. Optional formatting choices made in examples should not be enforced as rules.
36
+
37
+ ## 2 Source file basics
38
+
39
+ ### 2.1 File name
40
+
41
+ For a source file containing classes, the file name consists of the case-sensitive name of the
42
+ top-level class (of which there is [exactly one](#s3.4.1-one-top-level-class)), plus the
43
+ `.java` extension.
44
+
45
+ ### 2.2 File encoding: UTF-8
46
+
47
+ Source files are encoded in **UTF-8**.
48
+
49
+ ### 2.3 Special characters
50
+
51
+ #### 2.3.1 Whitespace characters
52
+
53
+ Aside from the line terminator sequence, the **ASCII horizontal space
54
+ character** (**0x20**) is the only whitespace character that appears
55
+ anywhere in a source file. This implies that:
56
+
57
+ 1. All other whitespace characters are escaped in `char` and string literals and in
58
+ text blocks.
59
+ 2. Tab characters are **not** used for indentation.
60
+
61
+ #### 2.3.2 Special escape sequences
62
+
63
+ For any character that has a
64
+ [special escape sequence](http://docs.oracle.com/javase/tutorial/java/data/characters.html)
65
+ (`\b`,
66
+ `\t`,
67
+ `\n`,
68
+ `\f`,
69
+ `\r`,
70
+ `\s`,
71
+ `\"`,
72
+ `\'` and
73
+ `\\`), that sequence
74
+ is used rather than the corresponding octal
75
+ (e.g. `\012`) or Unicode
76
+ (e.g. `\u000a`) escape.
77
+
78
+ #### 2.3.3 Non-ASCII characters
79
+
80
+ For the remaining non-ASCII characters, either the actual Unicode character
81
+ (e.g. `∞`) or the equivalent Unicode escape
82
+ (e.g. `\u221e`) is used. The choice depends only on
83
+ which makes the code **easier to read and understand**, although Unicode escapes
84
+ outside string literals and comments are strongly discouraged.
85
+
86
+ **Tip:** In the Unicode escape case, and occasionally even when actual
87
+ Unicode characters are used, an explanatory comment can be very helpful.
88
+
89
+ Examples:
90
+
91
+ | Example | Discussion |
92
+ | --- | --- |
93
+ | `String unitAbbrev = "μs";` | Best: perfectly clear even without a comment. |
94
+ | `String unitAbbrev = "\u03bcs"; // "μs"` | Allowed, but there's no reason to do this. |
95
+ | `String unitAbbrev = "\u03bcs"; // Greek letter mu, "s"` | Allowed, but awkward and prone to mistakes. |
96
+ | `String unitAbbrev = "\u03bcs";` | Poor: the reader has no idea what this is. |
97
+ | `return '\ufeff' + content; // byte order mark` | Good: use escapes for non-printable characters, and comment if necessary. |
98
+
99
+ **Tip:** Never make your code less readable simply out of fear that
100
+ some programs might not handle non-ASCII characters properly. If that should happen, those
101
+ programs are **broken** and they must be **fixed**.
102
+
103
+ ## 3 Source file structure
104
+
105
+ An ordinary source file consists of these sections, **in order**:
106
+
107
+ 1. License or copyright information, if present
108
+ 2. Package declaration
109
+ 3. Imports
110
+ 4. Exactly one top-level class declaration
111
+
112
+ **Exactly one blank line** separates each section that is present.
113
+
114
+ A `package-info.java` file is the same, but without the class declaration.
115
+
116
+ A `module-info.java` file does not contain a package declaration and replaces the
117
+ class declaration with a module declaration, but otherwise follows the same structure.
118
+
119
+ ### 3.1 License or copyright information, if present
120
+
121
+ If license or copyright information belongs in a file, it belongs here.
122
+
123
+ ### 3.2 Package declaration
124
+
125
+ Every source file must have a package declaration. [Compact source files](https://openjdk.org/jeps/512) are not used. (This rule obviously does not apply to
126
+ `module-info.java` files, which have a different syntax that does not include a
127
+ package declaration.)
128
+
129
+ The package declaration is **not line-wrapped**. The column limit (Section 4.4,
130
+ [Column limit: 100](#s4.4-column-limit)) does not apply to package declarations.
131
+
132
+ ### 3.3 Imports
133
+
134
+ #### 3.3.1 No wildcard imports
135
+
136
+ **Wildcard ("on-demand") imports**, static or otherwise, **are not
137
+ used**.
138
+
139
+ #### 3.3.1.1 No module imports
140
+
141
+ [Module imports](https://docs.oracle.com/en/java/javase/25/language/module-import-declarations.html) **are not used**.
142
+
143
+ Example:
144
+
145
+ ```
146
+ import module java.base;
147
+ ```
148
+
149
+ #### 3.3.2 No line-wrapping
150
+
151
+ Imports are **not line-wrapped**. The column limit (Section 4.4,
152
+ [Column limit: 100](#s4.4-column-limit)) does not apply to imports.
153
+
154
+ #### 3.3.3 Ordering and spacing
155
+
156
+ Imports are ordered as follows:
157
+
158
+ 1. All static imports in a single group.
159
+ 2. All non-static imports in a single group.
160
+
161
+ If there are both static and non-static imports, a single blank line separates the two
162
+ groups. There are no other blank lines between imports.
163
+
164
+ Within each group the imported names appear in ASCII sort order. (**Note:**
165
+ this is not the same as the import *lines* being in ASCII sort order, since '.'
166
+ sorts before ';'.)
167
+
168
+ #### 3.3.4 No static import for classes
169
+
170
+ Static import is not used for static nested classes. They are imported with
171
+ normal imports.
172
+
173
+ ### 3.4 Class declaration
174
+
175
+ #### 3.4.1 Exactly one top-level class declaration
176
+
177
+ Each top-level class resides in a source file of its own.
178
+
179
+ #### 3.4.2 Ordering of class contents
180
+
181
+ The order you choose for the members and initializers of your class can have a great effect on
182
+ learnability. However, there's no single correct recipe for how to do it; different classes may
183
+ order their contents in different ways.
184
+
185
+ What is important is that each class uses ***some* logical order**, which its
186
+ maintainer could explain if asked. For example, new methods are not just habitually added to the end
187
+ of the class, as that would yield "chronological by date added" ordering, which is not a logical
188
+ ordering.
189
+
190
+ ##### 3.4.2.1 Overloads: never split
191
+
192
+ Methods of a class that share the same name appear in a single contiguous group with no other
193
+ members in between. The same applies to multiple constructors. This rule applies even when
194
+ modifiers such as `static` or
195
+ `private` differ between the methods or constructors.
196
+
197
+ ### 3.5 Module declaration
198
+
199
+ #### 3.5.1 Ordering and spacing of module directives
200
+
201
+ Module directives are ordered as follows:
202
+
203
+ 1. All `requires` directives in a single block.
204
+ 2. All `exports` directives in a single block.
205
+ 3. All `opens` directives in a single block.
206
+ 4. All `uses` directives in a single block.
207
+ 5. All `provides` directives in a single block.
208
+
209
+ A single blank line separates each block that is present.
210
+
211
+ ## 4 Formatting
212
+
213
+ **Terminology Note:** *block-like construct* refers to
214
+ the body of a class, method, constructor, or switch. Note that, by Section 4.8.3.1 on
215
+ [array initializers](#s4.8.3.1-array-initializers), any array initializer
216
+ *may* optionally be treated as if it were a block-like construct.
217
+
218
+ ### 4.1 Braces
219
+
220
+ #### 4.1.1 Use of optional braces
221
+
222
+ Braces are used with
223
+ `if`,
224
+ `else`,
225
+ `for`,
226
+ `do` and
227
+ `while` statements, even when the
228
+ body is empty or contains only a single statement.
229
+
230
+ Other optional braces, such as those in a lambda expression, remain optional.
231
+
232
+ #### 4.1.2 Nonempty blocks: K & R style
233
+
234
+ Braces follow the Kernighan and Ritchie style for *nonempty* blocks and block-like
235
+ constructs:
236
+
237
+ * No line break before the opening brace, except as detailed below.
238
+ * Line break after the opening brace.
239
+ * Line break before the closing brace.
240
+ * Line break after the closing brace, *only if* that brace terminates a statement or
241
+ terminates the body of a method, constructor, or *named* class.
242
+ For example, there is *no* line break after the brace if it is followed by
243
+ `else` or a comma.
244
+
245
+ Exception: In places where these rules allow a single statement ending with a semicolon
246
+ (`;`), a block of statements can appear, and the opening
247
+ brace of this block is preceded by a line break. Blocks like these are typically introduced to
248
+ limit the scope of local variables.
249
+
250
+ Examples:
251
+
252
+ ```
253
+ return () -> {
254
+ while (condition()) {
255
+ method();
256
+ }
257
+ };
258
+
259
+ return new MyClass() {
260
+ @Override public void method() {
261
+ if (condition()) {
262
+ try {
263
+ something();
264
+ } catch (ProblemException e) {
265
+ recover();
266
+ }
267
+ } else if (otherCondition()) {
268
+ somethingElse();
269
+ } else {
270
+ lastThing();
271
+ }
272
+ {
273
+ int x = foo();
274
+ frob(x);
275
+ }
276
+ }
277
+ };
278
+ ```
279
+
280
+ A few exceptions for enum classes are given in Section 4.8.1,
281
+ [Enum classes](#s4.8.1-enum-classes).
282
+
283
+ #### 4.1.3 Empty blocks: may be concise
284
+
285
+ An empty block or block-like construct may be in K & R style (as described in
286
+ [Section 4.1.2](#s4.1.2-blocks-k-r-style)). Alternatively, it may be closed immediately
287
+ after it is opened, with no characters or line break in between
288
+ (`{}`), **unless** it is part of a
289
+ *multi-block statement* (one that directly contains multiple blocks:
290
+ `if/else` or
291
+ `try/catch/finally`).
292
+
293
+ Examples:
294
+
295
+ ```
296
+ // This is acceptable
297
+ void doNothing() {}
298
+
299
+ // This is equally acceptable
300
+ void doNothingElse() {
301
+ }
302
+ ```
303
+
304
+ ```
305
+ // This is not acceptable: No concise empty blocks in a multi-block statement
306
+ try {
307
+ doSomething();
308
+ } catch (Exception e) {}
309
+ ```
310
+
311
+ ### 4.2 Block indentation: +2 spaces
312
+
313
+ Each time a new block or block-like construct is opened, the indent increases by two
314
+ spaces. When the block ends, the indent returns to the previous indent level. The indent level
315
+ applies to both code and comments throughout the block. (See the example in Section 4.1.2,
316
+ [Nonempty blocks: K & R Style](#s4.1.2-blocks-k-r-style).)
317
+
318
+ ### 4.3 One statement per line
319
+
320
+ Each statement is followed by a line break.
321
+
322
+ ### 4.4 Column limit: 100
323
+
324
+ Java code has a column limit of 100 characters. A "character" means any Unicode code point.
325
+ Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in
326
+ Section 4.5, [Line-wrapping](#s4.5-line-wrapping).
327
+
328
+ Each Unicode code point counts as one character, even if its display width is
329
+ greater or less. For example, if using
330
+ [fullwidth characters](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms),
331
+ you may choose to wrap the line earlier than where this rule strictly requires.
332
+
333
+ **Exceptions:**
334
+
335
+ 1. Lines where obeying the column limit is not possible (for example, a long URL in Javadoc,
336
+ or a long JSNI method reference).
337
+ 2. `package` declarations and
338
+ imports (see Sections 3.2 [Package declarations](#s3.2-package-statement) and
339
+ 3.3 [Imports](#s3.3-import-statements)).
340
+ 3. Contents of [text blocks](#s4.8.9-text-blocks).
341
+ 4. Command lines in a comment that may be copied-and-pasted into a shell.
342
+ 5. Very long identifiers, on the rare occasions they are called for, are allowed to exceed the
343
+ column limit. In that case, the valid wrapping for the surrounding code is as produced by
344
+ [google-java-format](https://github.com/google/google-java-format).
345
+
346
+ ### 4.5 Line-wrapping
347
+
348
+ **Terminology Note:** When code that might otherwise
349
+ occupy a single line is divided into multiple lines, this activity is called
350
+ *line-wrapping*.
351
+
352
+ There is no comprehensive, deterministic formula showing *exactly* how to line-wrap in
353
+ every situation. Very often there are several valid ways to line-wrap the same piece of code.
354
+
355
+ **Note:** While the typical reason for line-wrapping is to avoid
356
+ overflowing the column limit, even code that would in fact fit within the column limit *may*
357
+ be line-wrapped at the author's discretion.
358
+
359
+ **Tip:** Extracting a method or local variable may solve the problem
360
+ without the need to line-wrap.
361
+
362
+ #### 4.5.1 Where to break
363
+
364
+ The prime directive of line-wrapping is: prefer to break at a
365
+ **higher syntactic level**. Also:
366
+
367
+ 1. When a line is broken at a *non-assignment* operator the break comes *before*
368
+ the symbol. (Note that this is not the same practice used in Google style for other languages,
369
+ such as C++ and JavaScript.)
370
+ * This also applies to the following "operator-like" symbols:
371
+ + the dot separator (`.`)
372
+ + the two colons of a method reference
373
+ (`::`)
374
+ + an ampersand in a type bound
375
+ (`<T extends Foo & Bar>`)
376
+ + a pipe in a catch block
377
+ (`catch (FooException | BarException e)`).
378
+ 2. When a line is broken at an *assignment* operator the break typically comes
379
+ *after* the symbol, but either way is acceptable.
380
+ * This also applies to the colon in an enhanced
381
+ `for` ("foreach") statement.
382
+ 3. A method, constructor, or record-class name stays attached to the open parenthesis
383
+ (`(`) that follows it.
384
+ 4. A comma (`,`) stays attached to the token that
385
+ precedes it.
386
+ 5. A line is never broken adjacent to the arrow in a lambda or a switch rule, except that a
387
+ break may come immediately after the arrow if the text following it consists of a single unbraced
388
+ expression. Examples:
389
+
390
+ ```
391
+ MyLambda<String, Long, Object> lambda =
392
+ (String label, Long value, Object obj) -> {
393
+ ...
394
+ };
395
+
396
+ Predicate<String> predicate = str ->
397
+ longExpressionInvolving(str);
398
+
399
+ switch (x) {
400
+ case ColorPoint(Color color, Point(int x, int y)) ->
401
+ handleColorPoint(color, x, y);
402
+ ...
403
+ }
404
+ ```
405
+
406
+ **Note:** The primary goal for line wrapping is to have clear
407
+ code, *not necessarily* code that fits in the smallest number of lines.
408
+
409
+ #### 4.5.2 Indent continuation lines at least +4 spaces
410
+
411
+ When line-wrapping, each line after the first (each *continuation line*) is indented
412
+ at least +4 from the original line.
413
+
414
+ When there are multiple continuation lines, indentation may be varied beyond +4 as
415
+ desired. In general, two continuation lines use the same indentation level if and only if they
416
+ begin with syntactically parallel elements.
417
+
418
+ Section 4.6.3 on [Horizontal alignment](#s4.6.3-horizontal-alignment) addresses
419
+ the discouraged practice of using a variable number of spaces to align certain tokens with
420
+ previous lines.
421
+
422
+ ### 4.6 Whitespace
423
+
424
+ #### 4.6.1 Vertical whitespace (blank lines)
425
+
426
+ A single blank line always appears:
427
+
428
+ 1. *Between* consecutive members or initializers of a class: fields, constructors,
429
+ methods, nested classes, static initializers, and instance initializers.
430
+ * **Exception:** A blank line between two consecutive
431
+ fields (having no other code between them) is optional. Such blank lines are used as needed to
432
+ create *logical groupings* of fields.
433
+ * **Exception:** Blank lines between enum constants are
434
+ covered in [Section 4.8.1](#s4.8.1-enum-classes).
435
+ 2. As required by other sections of this document (such as Section 3,
436
+ [Source file structure](#s3-source-file-structure), and Section 3.3,
437
+ [Imports](#s3.3-import-statements)).
438
+
439
+ A single blank line may also appear anywhere it improves readability, for example between
440
+ statements to organize the code into logical subsections. A blank line before the first member or
441
+ initializer, or after the last member or initializer of the class, is neither encouraged nor
442
+ discouraged.
443
+
444
+ *Multiple* consecutive blank lines are permitted, but never required (or encouraged).
445
+
446
+ #### 4.6.2 Horizontal whitespace
447
+
448
+ Beyond where required by the language or other style rules, and apart from within literals,
449
+ comments and Javadoc, a single ASCII space also appears in the following places
450
+ **only**.
451
+
452
+ 1. Separating any keyword, such as
453
+ `if`,
454
+ `for` or
455
+ `catch`, from an open parenthesis
456
+ (`(`)
457
+ that follows it on that line
458
+ 2. Separating any keyword, such as
459
+ `else` or
460
+ `catch`, from a closing curly brace
461
+ (`}`) that precedes it on that line
462
+ 3. Before any open curly brace
463
+ (`{`), with two exceptions:
464
+ * `@SomeAnnotation({a, b})` (no space is used)
465
+ * `String[][] x = {{"foo"}};` (no space is required
466
+ between `{{`, by item 10 below)
467
+ 4. On both sides of any binary or ternary operator. This also applies to the following
468
+ "operator-like" symbols:
469
+ * the ampersand that separates multiple type bounds:
470
+ `<T extends Foo & Bar>`
471
+ * the pipe for a catch block that handles multiple exceptions:
472
+ `catch (FooException | BarException e)`
473
+ * the colon (`:`) in an enhanced
474
+ `for` ("foreach") statement
475
+ * the arrow in a lambda expression:
476
+ `(String str) -> str.length()`
477
+ or switch rule:
478
+ `case "FOO" -> bar();`but not
479
+ * the two colons (`::`) of a method reference, which
480
+ is written like `Object::toString`
481
+ * the dot separator (`.`), which is written like
482
+ `object.toString()`
483
+ 5. After `,:;` or the closing parenthesis
484
+ (`)`) of a cast
485
+ 6. Between any content and a double slash (`//`) which
486
+ begins a comment. Multiple spaces are allowed.
487
+ 7. Between a double slash (`//`) which begins a comment
488
+ and the comment's text. Multiple spaces are allowed.
489
+ 8. Between the type and identifier of a declaration:
490
+ `List<String> list`
491
+ 9. *Optional* just inside both braces of an array initializer
492
+ * `new int[] {5, 6}` and
493
+ `new int[] { 5, 6 }` are both valid
494
+ 10. Between a type annotation and `[]` or
495
+ `...`.
496
+
497
+ This rule is never interpreted as requiring or forbidding additional space at the start or
498
+ end of a line; it addresses only *interior* space.
499
+
500
+ #### 4.6.3 Horizontal alignment: never required
501
+
502
+ **Terminology Note:** *Horizontal alignment* is the
503
+ practice of adding a variable number of additional spaces in your code with the goal of making
504
+ certain tokens appear directly below certain other tokens on previous lines.
505
+
506
+ This practice is permitted, but is **never required** by Google Style. It is not
507
+ even required to *maintain* horizontal alignment in places where it was already used.
508
+
509
+ Here is an example without alignment, then using alignment:
510
+
511
+ ```
512
+ private int x; // this is fine
513
+ private Color color; // this too
514
+
515
+ private int x; // permitted, but future edits
516
+ private Color color; // may leave it unaligned
517
+ ```
518
+
519
+ **Tip:** Alignment can aid readability, but attempting to preserve
520
+ alignment for its own sake creates future problems. For example, consider a change that touches only
521
+ one line. If that change disrupts the previous alignment, it's important \*\*not\*\* to introduce
522
+ additional changes on nearby lines simply to realign them. Introducing formatting changes on
523
+ otherwise unaffected lines corrupts version history, slows down reviewers, and exacerbates merge
524
+ conflicts. These practical concerns take priority over alignment.
525
+
526
+ ### 4.7 Grouping parentheses: recommended
527
+
528
+ Optional grouping parentheses are omitted only when author and reviewer agree that there is no
529
+ reasonable chance the code will be misinterpreted without them, nor would they have made the code
530
+ easier to read. It is *not* reasonable to assume that every reader has the entire Java
531
+ operator precedence table memorized.
532
+
533
+ ### 4.8 Specific constructs
534
+
535
+ #### 4.8.1 Enum classes
536
+
537
+ After the comma that follows an enum constant, a line break is optional. Additional blank
538
+ lines (usually just one) are also allowed. This is one possibility:
539
+
540
+ ```
541
+ private enum Answer {
542
+ YES {
543
+ @Override public String toString() {
544
+ return "yes";
545
+ }
546
+ },
547
+
548
+ NO,
549
+ MAYBE
550
+ }
551
+ ```
552
+
553
+ An enum class with no methods and no documentation on its constants may optionally be formatted
554
+ as if it were an array initializer (see Section 4.8.3.1 on
555
+ [array initializers](#s4.8.3.1-array-initializers)).
556
+
557
+ ```
558
+ private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
559
+ ```
560
+
561
+ Since enum classes *are classes*, all other rules for formatting classes apply.
562
+
563
+ #### 4.8.2 Variable declarations
564
+
565
+ ##### 4.8.2.1 One variable per declaration
566
+
567
+ Every variable declaration (field or local) declares only one variable: declarations such as
568
+ `int a, b;` are not used.
569
+
570
+ **Exception:** Multiple variable declarations are acceptable in the header of a
571
+ `for` loop.
572
+
573
+ ##### 4.8.2.2 Declared when needed
574
+
575
+ Local variables are **not** habitually declared at the start of their containing
576
+ block or block-like construct. Instead, local variables are declared close to the point they are
577
+ first used (within reason), to minimize their scope. Local variable declarations typically have
578
+ initializers, or are initialized immediately after declaration.
579
+
580
+ #### 4.8.3 Arrays
581
+
582
+ ##### 4.8.3.1 Array initializers: can be "block-like"
583
+
584
+ Any array initializer may *optionally* be formatted as if it were a "block-like
585
+ construct." For example, the following are all valid (**not** an exhaustive
586
+ list):
587
+
588
+ ```
589
+ new int[] { new int[] {
590
+ 0, 1, 2, 3 0,
591
+ } 1,
592
+ 2,
593
+ new int[] { 3,
594
+ 0, 1, }
595
+ 2, 3
596
+ } new int[]
597
+ {0, 1, 2, 3}
598
+ ```
599
+
600
+ ##### 4.8.3.2 No C-style array declarations
601
+
602
+ The square brackets form a part of the *type*, not the variable:
603
+ `String[] args`, not
604
+ `String args[]`.
605
+
606
+ #### 4.8.4 Switch statements and expressions
607
+
608
+ For historical reasons, the Java language has two distinct syntaxes for `switch`, which we can call *old-style* and
609
+ *new-style*. New-style switches use an arrow
610
+ (`->`) after the switch labels, while old-style switches
611
+ use a colon (`:`).
612
+
613
+ **Terminology Note:** Inside the braces of a
614
+ *switch block* are either one or more *switch rules* (new-style);
615
+ or one or more *statement groups* (old-style). A *switch
616
+ rule* consists of a *switch label* (`case ...`
617
+ or `default`) followed by `->` and an expression, block, or `throw`. A statement group consists of one or more switch labels each followed by
618
+ a colon, then one or more statements, or, for the *last* statement group, *zero* or
619
+ more statements. (These definitions match the Java Language Specification,
620
+ [§14.11](https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.11).)
621
+
622
+ ##### 4.8.4.1 Indentation
623
+
624
+ As with any other block, the contents of a switch block are indented +2. Each switch label
625
+ starts with this +2 indentation.
626
+
627
+ In a new-style switch, a switch rule can be written on a single line if it otherwise follows
628
+ Google style. (It must not exceed the column limit, and if it contains a non-empty block then
629
+ there must be a line break after `{`.) The line-wrapping
630
+ rules of [Section 4.5](#s4.5-line-wrapping) apply, including the +4 indent for
631
+ continuation lines. For a switch rule with a non-empty block after the arrow, the same rules apply
632
+ as for blocks elsewhere: lines between `{` and
633
+ `}` are indented a further +2 relative to the line with the
634
+ switch label.
635
+
636
+ ```
637
+ switch (number) {
638
+ case 0, 1 -> handleZeroOrOne();
639
+ case 2 ->
640
+ handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine();
641
+ default -> {
642
+ logger.atInfo().log("Surprising number %s", number);
643
+ handleSurprisingNumber(number);
644
+ }
645
+ }
646
+ ```
647
+
648
+ In an old-style switch, the colon of each switch label is followed by a line break. The
649
+ statements within a statement group are indented a further +2.
650
+
651
+ ##### 4.8.4.2 Fall-through: commented
652
+
653
+ Within an old-style switch block, each statement group either terminates abruptly (with a
654
+ `break`,
655
+ `continue`,
656
+ `return` or thrown exception), or is marked with a comment
657
+ to indicate that execution will or *might* continue into the next statement group. Any
658
+ comment that communicates the idea of fall-through is sufficient (typically
659
+ `// fall through`). This special comment is not required in
660
+ the last statement group of the switch block. Example:
661
+
662
+ ```
663
+ switch (input) {
664
+ case 1:
665
+ case 2:
666
+ prepareOneOrTwo();
667
+ // fall through
668
+ case 3:
669
+ handleOneTwoOrThree();
670
+ break;
671
+ default:
672
+ handleLargeNumber(input);
673
+ }
674
+ ```
675
+
676
+ Notice that no comment is needed after `case 1:`, only
677
+ at the end of the statement group.
678
+
679
+ There is no fall-through in new-style switches.
680
+
681
+ ##### 4.8.4.3 Exhaustiveness and presence of the `default` label
682
+
683
+ The Java language requires switch expressions and many kinds of switch statements to be
684
+ *exhaustive*. That effectively means that every possible value that could be switched on will
685
+ be matched by one of the switch labels. A switch is exhaustive if it has a `default` label, but also for example if the value being switched
686
+ on is an enum and every value of the enum is matched by a switch label. Google Style requires
687
+ *every* switch to be exhaustive, even those where the language itself does not require it.
688
+ This may require adding a `default` label, even if it
689
+ contains no code.
690
+
691
+ ##### 4.8.4.4 Switch expressions
692
+
693
+ Switch expressions must be new-style switches:
694
+
695
+ ```
696
+ return switch (list.size()) {
697
+ case 0 -> "";
698
+ case 1 -> list.getFirst();
699
+ default -> String.join(", ", list);
700
+ };
701
+ ```
702
+
703
+ #### 4.8.5 Annotations
704
+
705
+ ##### 4.8.5.1 Type-use annotations
706
+
707
+ Type-use annotations appear immediately before the annotated type. An annotation is a type-use
708
+ annotation if it is meta-annotated with
709
+ `@Target(ElementType.TYPE_USE)`. Example:
710
+
711
+ ```
712
+ final @Nullable String name;
713
+
714
+ public @Nullable Person getPersonByName(String name);
715
+ ```
716
+
717
+ ##### 4.8.5.2 Class, package, and module annotations
718
+
719
+ Annotations applying to a class, package, or module declaration appear immediately after the
720
+ documentation block, and each annotation is listed on a line of its own (that is, one annotation
721
+ per line). These line breaks do not constitute line-wrapping (Section
722
+ 4.5, [Line-wrapping](#s4.5-line-wrapping)), so the indentation level is not
723
+ increased. Examples:
724
+
725
+ ```
726
+ /** This is a class. */
727
+ @Deprecated
728
+ @CheckReturnValue
729
+ public final class Frozzler { ... }
730
+ ```
731
+
732
+ ```
733
+ /** This is a package. */
734
+ @Deprecated
735
+ @CheckReturnValue
736
+ package com.example.frozzler;
737
+ ```
738
+
739
+ ```
740
+ /** This is a module. */
741
+ @Deprecated
742
+ @SuppressWarnings("CheckReturnValue") // TODO: b/123 - Fix existing CRV violations.
743
+ module com.example.frozzler { ... }
744
+ ```
745
+
746
+ ##### 4.8.5.3 Method and constructor annotations
747
+
748
+ The rules for annotations on method and constructor declarations are the same as the
749
+ [previous section](#s4.8.5.2-class-annotation-style). Example:
750
+
751
+ ```
752
+ @Deprecated
753
+ @Override
754
+ public String getNameIfPresent() { ... }
755
+ ```
756
+
757
+ **Exception:** If the method or constructor only has a
758
+ *single*, *parameterless* annotation, it *may* appear together with the first
759
+ line of the signature, for example:
760
+
761
+ ```
762
+ @Override public int hashCode() { ... }
763
+ ```
764
+
765
+ ##### 4.8.5.4 Field annotations
766
+
767
+ Annotations applying to a field also appear immediately after the documentation block, but in
768
+ this case, *multiple* annotations (possibly parameterized) may be listed on the same line;
769
+ for example:
770
+
771
+ ```
772
+ @Partial @Mock DataLoader loader;
773
+ ```
774
+
775
+ ##### 4.8.5.5 Parameter and local variable annotations
776
+
777
+ There are no specific rules for formatting annotations on parameters or local variables (except,
778
+ of course, when the annotation is a type-use annotation).
779
+
780
+ #### 4.8.6 Comments
781
+
782
+ This section addresses *implementation comments*. Javadoc is addressed separately in
783
+ Section 7, [Javadoc](#s7-javadoc).
784
+
785
+ Any line break may be preceded by arbitrary whitespace followed by an implementation comment.
786
+ Such a comment renders the line non-blank.
787
+
788
+ ##### 4.8.6.1 Block comment style
789
+
790
+ Block comments are indented at the same level as the surrounding code. They may be in
791
+ `/* ... */` style or
792
+ `// ...` style. For multi-line
793
+ `/* ... */` comments, subsequent lines must start with
794
+ `*` aligned with the `*` on the previous line.
795
+
796
+ ```
797
+ /*
798
+ * This is // And so /* Or you can
799
+ * okay. // is this. * even do this. */
800
+ */
801
+ ```
802
+
803
+ Comments are not enclosed in boxes drawn with asterisks or other characters.
804
+
805
+ **Tip:** When writing multi-line comments, use the
806
+ `/* ... */` style if you want automatic code formatters to
807
+ re-wrap the lines when necessary (paragraph-style). Most formatters don't re-wrap lines in
808
+ `// ...` style comment blocks.
809
+
810
+ ##### 4.8.6.2 TODO comments
811
+
812
+ Use `TODO` comments for code that is temporary, a short-term solution, or good-enough
813
+ but not perfect.
814
+
815
+ A `TODO` comment begins with the word `TODO` in all caps, a following
816
+ colon, and a link to a resource that contains the context, ideally a bug reference. A bug
817
+ reference is preferable because bugs are tracked and have follow-up comments. Follow this piece of
818
+ context with an explanatory string introduced with a hyphen `-`.
819
+
820
+ The purpose is to have a consistent `TODO` format that can be searched to find out how
821
+ to get more details.
822
+
823
+ ```
824
+ // TODO: crbug.com/12345678 - Remove this after the 2047q4 compatibility window expires.
825
+ ```
826
+
827
+ Avoid adding TODOs that refer to an individual or team as the context:
828
+
829
+ ```
830
+ // TODO: @yourusername - File an issue and use a '*' for repetition.
831
+ ```
832
+
833
+ If your `TODO` is of the form "At a future date do something" make sure that you
834
+ either include a very specific date ("Fix by November 2005") or a very specific event ("Remove
835
+ this code when all clients can handle XML responses.").
836
+
837
+ #### 4.8.7 Modifiers
838
+
839
+ Class and member modifiers, when present, appear in the order
840
+ recommended by the Java Language Specification:
841
+
842
+ ```
843
+ public protected private abstract default static final sealed non-sealed
844
+ transient volatile synchronized native strictfp
845
+ ```
846
+
847
+ Modifiers on `requires` module directives, when present, appear in the following
848
+ order:
849
+
850
+ ```
851
+ transitive static
852
+ ```
853
+
854
+ #### 4.8.8 Numeric Literals
855
+
856
+ `long`-valued integer literals use an uppercase `L` suffix, never
857
+ lowercase (to avoid confusion with the digit `1`). For example, `3000000000L`
858
+ rather than `3000000000l`.
859
+
860
+ #### 4.8.9 Text Blocks
861
+
862
+ The opening `"""` of a text block is always on a new line. That line may
863
+ either follow the same indentation rules as other constructs, or it may have no indentation at all
864
+ (so it starts at the left margin). The closing `"""` is on a new line
865
+ with the same indentation as the opening `"""`, and may be followed on the
866
+ same line by further code. Each line of text in the text block is indented at least as much as the
867
+ opening and closing `"""`. (If a line is indented further, then the string
868
+ literal defined by the text block will have space at the start of that line.)
869
+
870
+ The contents of a text block may exceed the [column limit](#columnlimit).
871
+
872
+ ## 5 Naming
873
+
874
+ ### 5.1 Rules common to all identifiers
875
+
876
+ Identifiers use only ASCII letters and digits, and, in a small number of cases noted below,
877
+ underscores. Thus each valid identifier name is matched by the regular expression
878
+ `\w+` .
879
+
880
+ In Google Style, special prefixes or suffixes are **not** used. For example, these
881
+ names are not Google Style: `name_`, `mName`,
882
+ `s_name` and `kName`.
883
+
884
+ ### 5.2 Rules by identifier type
885
+
886
+ #### 5.2.1 Package and module names
887
+
888
+ Package and module names use only lowercase letters and digits (no underscores). Consecutive
889
+ words are simply concatenated together. For example, `com.example.deepspace`, not
890
+ `com.example.deepSpace` or
891
+ `com.example.deep_space`.
892
+
893
+ #### 5.2.2 Class names
894
+
895
+ Class names are written in [UpperCamelCase](#s5.3-camel-case).
896
+
897
+ Class names are typically nouns or noun phrases. For example,
898
+ `Character` or
899
+ `ImmutableList`. Interface names may also be nouns or
900
+ noun phrases (for example, `List`), but may sometimes be
901
+ adjectives or adjective phrases instead (for example,
902
+ `Readable`).
903
+
904
+ There are no specific rules or even well-established conventions for naming annotation types.
905
+
906
+ A *test* class has a name that ends with `Test`,
907
+ for example, `HashIntegrationTest`.
908
+ If it covers a single class, its name is the name of that class
909
+ plus `Test`, for example `HashImplTest`.
910
+
911
+ #### 5.2.3 Method names
912
+
913
+ Method names are written in [lowerCamelCase](#s5.3-camel-case).
914
+
915
+ Method names are typically verbs or verb phrases. For example,
916
+ `sendMessage` or
917
+ `stop`.
918
+
919
+ Underscores may appear in JUnit *test* method names to separate logical components of the
920
+ name, with *each* component written in [lowerCamelCase](#s5.3-camel-case), for
921
+ example `transferMoney_deductsFromSource`. There is no One
922
+ Correct Way to name test methods.
923
+
924
+ #### 5.2.4 Constant names
925
+
926
+ Constant names use `UPPER_SNAKE_CASE`: all uppercase
927
+ letters, with each word separated from the next by a single underscore. But what *is* a
928
+ constant, exactly?
929
+
930
+ Constants are static final fields whose contents are deeply immutable and whose methods have no
931
+ detectable side effects. Examples include primitives, strings, immutable value classes, and anything
932
+ set to `null`. If any of the instance's observable state can change, it is not a
933
+ constant. Merely *intending* to never mutate the object is not enough. Examples:
934
+
935
+ ```
936
+ // Constants
937
+ static final int NUMBER = 5;
938
+ static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
939
+ static final Map<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
940
+ static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
941
+ static final SomeMutableType[] EMPTY_ARRAY = {};
942
+
943
+ // Not constants
944
+ static String nonFinal = "non-final";
945
+ final String nonStatic = "non-static";
946
+ static final Set<String> mutableCollection = new HashSet<String>();
947
+ static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
948
+ static final ImmutableMap<String, SomeMutableType> mutableValues =
949
+ ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
950
+ static final Logger logger = Logger.getLogger(MyClass.getName());
951
+ static final String[] nonEmptyArray = {"these", "can", "change"};
952
+ ```
953
+
954
+ These names are typically nouns or noun phrases.
955
+
956
+ #### 5.2.5 Non-constant field names
957
+
958
+ Non-constant field names (static or otherwise) are written
959
+ in [lowerCamelCase](#s5.3-camel-case).
960
+
961
+ These names are typically nouns or noun phrases. For example,
962
+ `computedValues` or
963
+ `index`.
964
+
965
+ #### 5.2.6 Parameter names
966
+
967
+ Parameter names are written in [lowerCamelCase](#s5.3-camel-case).
968
+
969
+ One-character parameter names in public methods should be avoided.
970
+
971
+ #### 5.2.7 Local variable names
972
+
973
+ Local variable names are written in [lowerCamelCase](#s5.3-camel-case).
974
+
975
+ Even when final and immutable, local variables are not considered to be constants, and should not
976
+ be styled as constants.
977
+
978
+ #### 5.2.8 Type variable names
979
+
980
+ Each type variable is named in one of two styles:
981
+
982
+ * A single capital letter, optionally followed by a single numeral (such as
983
+ `E`, `T`,
984
+ `X`, `T2`)
985
+ * A name in the form used for classes (see Section 5.2.2,
986
+ [Class names](#s5.2.2-class-names)), followed by the capital letter
987
+ `T` (examples:
988
+ `RequestT`,
989
+ `FooBarT`).
990
+
991
+ #### 5.2.9 Unnamed variables
992
+
993
+ The `_` syntax for unnamed variables and parameters is
994
+ allowed wherever it is applicable. For example:
995
+
996
+ ```
997
+ Predicate<String> alwaysTrue = _ -> true;
998
+ ```
999
+
1000
+
1001
+
1002
+ ### 5.3 Camel case: defined
1003
+
1004
+ Sometimes there is more than one reasonable way to convert an English phrase into camel case,
1005
+ such as when acronyms or unusual constructs like "IPv6" or "iOS" are present. To improve
1006
+ predictability, Google Style specifies the following (nearly) deterministic scheme.
1007
+
1008
+ Beginning with the prose form of the name:
1009
+
1010
+ 1. Convert the phrase to plain ASCII and remove any apostrophes. For example, "Müller's
1011
+ algorithm" might become "Muellers algorithm".
1012
+ 2. Divide this result into words, splitting on spaces and any remaining punctuation (typically
1013
+ hyphens).
1014
+ * *Recommended:* if any word already has a conventional camel-case appearance in common
1015
+ usage, split this into its constituent parts (e.g., "AdWords" becomes "ad words"). Note
1016
+ that a word such as "iOS" is not really in camel case *per se*; it defies *any*
1017
+ convention, so this recommendation does not apply.
1018
+ 3. Now lowercase *everything* (including acronyms), then uppercase only the first
1019
+ character of:
1020
+ * ... each word, to yield *upper camel case*, or
1021
+ * ... each word except the first, to yield *lower camel case*
1022
+ 4. Finally, join all the words into a single identifier. Note that the casing of the original
1023
+ words is almost entirely disregarded.
1024
+
1025
+ In very rare circumstances (for example, multipart version numbers), you may need to use
1026
+ underscores to separate adjacent numbers, since numbers do not have upper and lower case variants.
1027
+
1028
+ Examples:
1029
+
1030
+ | Prose form | Correct | Incorrect |
1031
+ | --- | --- | --- |
1032
+ | "XML HTTP request" | `XmlHttpRequest` | `XMLHTTPRequest` |
1033
+ | "new customer ID" | `newCustomerId` | `newCustomerID` |
1034
+ | "inner stopwatch" | `innerStopwatch` | `innerStopWatch` |
1035
+ | "supports IPv6 on iOS?" | `supportsIpv6OnIos` | `supportsIPv6OnIOS` |
1036
+ | "YouTube importer" | `YouTubeImporter` `YoutubeImporter`\* | |
1037
+ | "Turn on 2SV" | `turnOn2sv` | `turnOn2Sv` |
1038
+ | "Guava 33.4.6" | `guava33_4_6` | `guava3346` |
1039
+
1040
+ \*Acceptable, but not recommended.
1041
+
1042
+ **Note:** Some words are ambiguously hyphenated in the English
1043
+ language: for example "nonempty" and "non-empty" are both correct, so the method names
1044
+ `checkNonempty` and
1045
+ `checkNonEmpty` are likewise both correct.
1046
+
1047
+ ## 6 Programming Practices
1048
+
1049
+ ### 6.1 `@Override`: always used
1050
+
1051
+ A method is marked with the `@Override` annotation
1052
+ whenever it is legal. This includes a class method overriding a superclass method, a class method
1053
+ implementing an interface method, an interface method respecifying a superinterface method, and an
1054
+ explicitly declared accessor method for a record component.
1055
+
1056
+ **Exception:**
1057
+ `@Override` may be omitted when the parent method is
1058
+ `@Deprecated`.
1059
+
1060
+ ### 6.2 Caught exceptions: not ignored
1061
+
1062
+ It is very rarely correct to do nothing in response to a caught
1063
+ exception. (Typical responses are to log it, or if it is considered "impossible", rethrow it as an
1064
+ `AssertionError`.)
1065
+
1066
+ When it truly is appropriate to take no action whatsoever in a catch block, the reason this is
1067
+ justified is explained in a comment.
1068
+
1069
+ ```
1070
+ try {
1071
+ int i = Integer.parseInt(response);
1072
+ return handleNumericResponse(i);
1073
+ } catch (NumberFormatException _) {
1074
+ // it's not numeric; that's fine, just continue
1075
+ }
1076
+ return handleTextResponse(response);
1077
+ ```
1078
+
1079
+ ### 6.3 Static members: qualified using class
1080
+
1081
+ When a reference to a static class member must be qualified, it is qualified with that class's
1082
+ name, not with a reference or expression of that class's type.
1083
+
1084
+ ```
1085
+ Foo aFoo = ...;
1086
+ Foo.aStaticMethod(); // good
1087
+ aFoo.aStaticMethod(); // bad
1088
+ somethingThatYieldsAFoo().aStaticMethod(); // very bad
1089
+ ```
1090
+
1091
+ ### 6.4 Finalizers: not used
1092
+
1093
+ Do not override `Object.finalize`. Finalization support
1094
+ is [*scheduled for removal*](https://openjdk.org/jeps/421).
1095
+
1096
+ ## 7 Javadoc
1097
+
1098
+ ### 7.1 Formatting
1099
+
1100
+ #### 7.1.1 General form
1101
+
1102
+ The *basic* formatting of Javadoc blocks is as seen in this example:
1103
+
1104
+ ```
1105
+ /**
1106
+ * Multiple lines of Javadoc text are written here,
1107
+ * wrapped normally...
1108
+ */
1109
+ public int method(String p1) { ... }
1110
+ ```
1111
+
1112
+ ... or in this single-line example:
1113
+
1114
+ ```
1115
+ /** An especially short bit of Javadoc. */
1116
+ ```
1117
+
1118
+ The basic form is always acceptable. The single-line form may be substituted when the entirety
1119
+ of the Javadoc block (including comment markers) can fit on a single line. Note that this only
1120
+ applies when there are no block tags such as `@param`.
1121
+
1122
+ #### 7.1.2 Paragraphs
1123
+
1124
+ One blank line—that is, a line containing only the aligned leading asterisk
1125
+ (`*`)—appears between paragraphs, and before the group of block tags if present.
1126
+ Each paragraph except the first has `<p>` immediately before the first word, with
1127
+ no space after it. HTML tags for other block-level elements, such as `<ul>` or
1128
+ `<table>`, are *not* preceded with `<p>`.
1129
+
1130
+ #### 7.1.3 Block tags
1131
+
1132
+ Any of the standard "block tags" that are used appear in the order `@param`,
1133
+ `@return`, `@throws`, `@deprecated`, and these four types never
1134
+ appear with an empty description. When a block tag doesn't fit on a single line, continuation lines
1135
+ are indented four (or more) spaces from the position of the `@`.
1136
+
1137
+ ### 7.2 The summary fragment
1138
+
1139
+ Each Javadoc block begins with a brief **summary fragment**. This
1140
+ fragment is very important: it is the only part of the text that appears in certain contexts such as
1141
+ class and method indexes.
1142
+
1143
+ This is a fragment—a noun phrase or verb phrase, not a complete sentence. It does
1144
+ **not** begin with `A {@code Foo} is a...`, or
1145
+ `This method returns...`, nor does it form a complete imperative sentence
1146
+ like `Save the record.`. However, the fragment is capitalized and
1147
+ punctuated as if it were a complete sentence.
1148
+
1149
+ **Tip:** A common mistake is to write simple Javadoc in the form
1150
+ `/** @return the customer ID */`. This is
1151
+ incorrect, and should be changed to
1152
+ `/** Returns the customer ID. */` or
1153
+ `/** {@return the customer ID} */`.
1154
+
1155
+ ### 7.3 Where Javadoc is used
1156
+
1157
+ At the *minimum*, Javadoc is present for every *visible* class, member, or record
1158
+ component, with a few exceptions noted below. A top-level class is visible if it is `public`; a member is visible if it is `public` or `protected` and its containing
1159
+ class is visible; and a record component is visible if its containing record is visible.
1160
+
1161
+ Additional Javadoc content may also be present, as explained in Section 7.3.4,
1162
+ [Non-required Javadoc](#s7.3.4-javadoc-non-required).
1163
+
1164
+ #### 7.3.1 Exception: self-explanatory members
1165
+
1166
+ Javadoc is optional for "simple, obvious" members and record components, such as a
1167
+ `getFoo()` method, *if* there *really and
1168
+ truly* is nothing else worthwhile to say but "the foo".
1169
+
1170
+ **Important:** it is not appropriate to cite this exception to justify
1171
+ omitting relevant information that a typical reader might need to know. For example, for a record
1172
+ component named `canonicalName`, don't omit its
1173
+ documentation (with the rationale that it would say only
1174
+ `@param canonicalName the canonical name`) if a typical reader may have
1175
+ no idea what the term "canonical name" means!
1176
+
1177
+ #### 7.3.2 Exception: overrides
1178
+
1179
+ Javadoc is not always present on a method that overrides a supertype method.
1180
+
1181
+ #### 7.3.4 Non-required Javadoc
1182
+
1183
+ Other classes, members, and record components have Javadoc *as needed or desired*.
1184
+
1185
+ Whenever an implementation comment would be used to define the overall purpose or behavior of a
1186
+ class or member, that comment is written as Javadoc instead (using `/**`).
1187
+
1188
+ Non-required Javadoc is not strictly required to follow the formatting rules of Sections
1189
+ 7.1.1, 7.1.2, 7.1.3, and 7.2, though it is of course recommended.