A hint: This file contains one or more very long lines, so maybe it is better readable using the pure text view mode that shows the contents as wrapped lines within the browser window.
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!-- 3 Licensed to the Apache Software Foundation (ASF) under one or more 4 contributor license agreements. See the NOTICE file distributed with 5 this work for additional information regarding copyright ownership. 6 The ASF licenses this file to You under the Apache License, Version 2.0 7 (the "License"); you may not use this file except in compliance with 8 the License. You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12 Unless required by applicable law or agreed to in writing, software 13 distributed under the License is distributed on an "AS IS" BASIS, 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 See the License for the specific language governing permissions and 16 limitations under the License. 17 --> 18 <document xmlns="http://maven.apache.org/XDOC/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 19 xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd"> 20 21 <properties> 22 <title>Java Style Guidelines</title> 23 </properties> 24 25 <body> 26 <section name="Apache Log4j Code Style Guidelines"> 27 <a name="intro"/> 28 <subsection name="Introduction"> 29 <p>This document serves as the <strong>complete</strong> definition of the Log4j project's coding standards for 30 source code in the Java™ Programming Language. It originated from the Google coding standards but incorporates 31 modifications that reflect the desires of the Log4j community.</p> 32 <p>Like other programming style guides, the issues covered span not only aesthetic issues of 33 formatting, but other types of conventions or coding standards as well. However, this document 34 focuses primarily on the <strong>hard-and-fast rules</strong> that we follow universally, and 35 avoids giving <em>advice</em> that isn't clearly enforceable (whether by human or tool).</p> 36 <a name="terminology"/> 37 <h3>Terminology notes</h3> 38 <p>In this document, unless otherwise clarified:</p> 39 <ol> 40 <li>The term <em>class</em> is used inclusively to mean an "ordinary" class, enum class, interface or 41 annotation type (<code>@interface</code>).</li> 42 <li>The term <em>comment</em> always refers to <em>implementation</em> comments. We do not 43 use the phrase "documentation comments", instead using the common term "Javadoc."</li> 44 </ol> 45 <p>Other "terminology notes" will appear occasionally throughout the document.</p> 46 <a name="guide-notes"/> 47 <h3>Guide notes</h3> 48 <p>Example code in this document is <strong>non-normative</strong>. That is, while the examples 49 are in Log4j Style, they may not illustrate the <em>only</em> stylish way to represent the 50 code. Optional formatting choices made in examples should not be enforced as rules.</p> 51 </subsection> 52 <a name="source-file-basics"/> 53 <subsection name="Source File Basics"> 54 <a name="file-name"/> 55 <h3>File name</h3> 56 <p>The source file name consists of the case-sensitive name of the top-level class it contains, 57 plus the <code>.java</code> extension.</p> 58 <a name="file-encoding"/> 59 <h3>2.2 File encoding: UTF-8</h3> 60 <p>Source files are encoded in <strong>UTF-8</strong>.</p> 61 <a name="special-characters"/> 62 <h3>Special characters</h3> 63 <a name="whitespace-characters"/> 64 <h4>Whitespace characters</h4> 65 <p>Aside from the line terminator sequence, the <strong>ASCII horizontal space 66 character</strong> (<strong>0x20</strong>) is the only whitespace character that appears 67 anywhere in a source file. This implies that:</p> 68 <ol> 69 <li>All other whitespace characters in string and character literals are escaped.</li> 70 <li>Tab characters are <strong>not</strong> used for indentation.</li> 71 </ol> 72 <a name="special-escape-sequences"/> 73 <h4>Special escape sequences</h4> 74 <p>For any character that has a special escape sequence 75 (<code>\b</code>, 76 <code>\t</code>, 77 <code>\n</code>, 78 <code>\f</code>, 79 <code>\r</code>, 80 <code>\"</code>, 81 <code>\'</code> and 82 <code>\\</code>), that sequence is used rather than the corresponding octal 83 (e.g. <code>\012</code>) or Unicode (e.g. <code>\u000a</code>) escape.</p> 84 <a name="non-ascii-characters"/> 85 <h4>Non-ASCII characters</h4> 86 <p>For the remaining non-ASCII characters, either the actual Unicode character 87 (e.g. <code>∞</code>) or the equivalent Unicode escape (e.g. <code>\u221e</code>) is used, depending only on which 88 makes the code <strong>easier to read and understand</strong>.</p> 89 <p><strong>Tip:</strong> In the Unicode escape case, and occasionally even when actual 90 Unicode characters are used, an explanatory comment can be very helpful.</p> 91 <p>Examples:</p> 92 <table> 93 <tr><th>Example</th><th>Discussion</th></tr> 94 <tr><td><code>String unitAbbrev = "μs";</code></td><td>Best: perfectly clear even without a comment.</td></tr> 95 <tr><td><code>String unitAbbrev = "\u03bcs"; // "μs"</code></td><td>Allowed, but there's no reason to do this.</td></tr> 96 <tr><td><code>String unitAbbrev = "\u03bcs"; // Greek letter mu, "s"</code></td><td>Allowed, but awkward and prone to mistakes.</td></tr> 97 <tr><td><code>String unitAbbrev = "\u03bcs";</code></td><td>Poor: the reader has no idea what this is.</td></tr> 98 <tr><td><code>return '\ufeff' + content; // byte order mark</code></td><td>Good: use escapes for non-printable characters, and comment if necessary.</td></tr> 99 </table> 100 <p><strong>Tip:</strong> Never make your code less readable simply out of fear that 101 some programs might not handle non-ASCII characters properly. If that should happen, those 102 programs are <strong>broken</strong> and they must be <strong>fixed</strong>.</p> 103 </subsection> 104 <a name="filestructure"/> 105 <a name="source-file-structure"/> 106 <subsection name="Source file structure"> 107 <p>A source file consists of, <strong>in order</strong>:</p> 108 <ol> 109 <li>Apache license</li> 110 <li>Package statement</li> 111 <li>Import statements</li> 112 <li>Exactly one top-level class</li> 113 </ol> 114 <p><strong>Exactly one blank line</strong> separates each section that is present.</p> 115 <a name="license"/> 116 <h3>Apache License</h3> 117 <p>The Apache license belongs here. No other license should appear. Other licenses that apply should be referenced in 118 a NOTICE file</p> 119 <a name="package-statement"/> 120 <h3>Package statement</h3> 121 <p>The package statement is <strong>not line-wrapped</strong>. The column limit 122 (<a href="#column-limit">Column limit: 120</a>) does not apply to package statements.</p> 123 <a name="imports"/> 124 <a name="import-statements"/> 125 <h3>Import statements</h3> 126 <a name="wildcard-imports"/> 127 <h4>No wildcard imports in the main tree</h4> 128 <p><strong>Wildcard imports</strong>, static or otherwise, <strong>are not used</strong>.</p> 129 <h4>Static wildcard imports in the test tree</h4> 130 <p><strong>Wildcard static imports</strong> are encouraged for test imports like JUnit, EasyMock, and Hamcrest.</p> 131 <a name="import-line-wrapping"/> 132 <h4>No line-wrapping</h4> 133 <p>Import statements are <strong>not line-wrapped</strong>. The column limit 134 (<a href="#column-limit">Column limit: 120</a>) does not apply to import statements.</p> 135 <a name="import-ordering-and-spacing"/> 136 <h4>Ordering and spacing</h4> 137 <p>Import statements are divided into the following groups, in this order, with each group 138 separated by a single blank line:</p> 139 <ol> 140 <li>java</li> 141 <li>javax</li> 142 <li>org</li> 143 <li>com</li> 144 <li>All static imports in a single group</li> 145 </ol> 146 <p>Within a group there are no blank lines, and the imported names appear in ASCII sort 147 order. (<strong>Note:</strong> this is not the same as the import <em>statements</em> being in 148 ASCII sort order; the presence of semicolons warps the result.)</p> 149 <p>IDE settings for ordering imports automatically can be found in the source distributions under 150 <code>src/ide</code>. For example:</p> 151 <ul> 152 <li>Eclipse: <code>src/ide/eclipse/4.3.2/organize-imports.importorder</code></li> 153 <li>IntelliJ: <code>src/ide/Intellij/13/IntellijSettings.jar</code></li> 154 </ul> 155 <a name="class-declaration"/> 156 <h3>Class declaration</h3> 157 <a name="oneclassperfile"/> 158 <a name="one-top-level-class"/> 159 <h4>Exactly one top-level class declaration</h4> 160 <p>Each top-level class resides in a source file of its own.</p> 161 <a name="class-member-ordering"/> 162 <h4>Class member ordering</h4> 163 <p>Class members should be grouped in the following order>.</p> 164 <ol> 165 <li>static variables grouped in the order shown below. Within a group variables may appear in any order.</li> 166 <li> 167 <ol> 168 <li>public</li> 169 <li>protected</li> 170 <li>package</li> 171 <li>private</li> 172 </ol> 173 </li> 174 <li>instance variables grouped in the order shown below. Within a group variables may appear in any order</li> 175 <li> 176 <ol> 177 <li>public</li> 178 <li>protected</li> 179 <li>package</li> 180 <li>private</li> 181 </ol> 182 </li> 183 <li>constructors</li> 184 <li>methods may be specified in the following order but may appear in another order if it improves the 185 clarity of the program.</li> 186 <li> 187 <ol> 188 <li>public</li> 189 <li>protected</li> 190 <li>package</li> 191 <li>private</li> 192 </ol> 193 </li> 194 </ol> 195 <a name="overloads"/> 196 <a name="never-split"/> 197 <h5>Overloads: never split</h5> 198 <p>When a class has multiple constructors, or multiple methods with the same name, these appear 199 sequentially, with no intervening members.</p> 200 </subsection> 201 <a name="formatting"/> 202 <subsection name="Formatting"> 203 <p><strong>Terminology Note:</strong> <em>block-like construct</em> refers to 204 the body of a class, method or constructor. Note that, by 205 <a href="array-initializers">array initializers</a>, any array initializer 206 <em>may</em> optionally be treated as if it were a block-like construct.</p> 207 <a name="braces"/> 208 <h3>Braces</h3> 209 <a name="braces-always-used"/> 210 <h4>Braces are used where optional</h4> 211 <p>Braces are used with 212 <code>if</code>, 213 <code>else</code>, 214 <code>for</code>, 215 <code>do</code> and 216 <code>while</code> statements, even when the 217 body is empty or contains only a single statement.</p> 218 <a name="blocks-k-r-style"/> 219 <h4>Nonempty blocks: K & R style</h4> 220 <p>Braces follow the Kernighan and Ritchie style 221 ("<a href="http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html">Egyptian brackets</a>") 222 for <em>nonempty</em> blocks and block-like constructs:</p><ul><li>No line break before the opening brace.</li><li>Line break after the opening brace.</li><li>Line break before the closing brace.</li><li>Line break after the closing brace <em>if</em> that brace terminates a statement or the body 223 of a method, constructor or <em>named</em> class. For example, there is <em>no</em> line break 224 after the brace if it is followed by <code>else</code> or a 225 comma.</li></ul><p>Example:</p> 226 <pre> 227 return new MyClass() { 228 @Override public void method() { 229 if (condition()) { 230 try { 231 something(); 232 } catch (ProblemException e) { 233 recover(); 234 } 235 } 236 } 237 }; 238 </pre><p>A few exceptions for enum classes are given in Section 4.8.1, 239 <a href="enum-classes">Enum classes</a>.</p> 240 <a name="emptyblocks"/> 241 <a name="braces-empty-blocks"/> 242 <h4>Empty blocks: may be concise</h4> 243 <p>An empty block or block-like construct <em>may</em> be closed immediately after it is 244 opened, with no characters or line break in between 245 (<code>{}</code>), <strong>unless</strong> it is part of a 246 <em>multi-block statement</em> (one that directly contains multiple blocks: 247 <code>if/else-if/else</code> or 248 <code>try/catch/finally</code>).</p> 249 <p>Example:</p><pre> 250 void doNothing() {} 251 </pre><a name="block-indentation"/> 252 <h3>Block indentation: +4 spaces</h3> 253 <p>Each time a new block or block-like construct is opened, the indent increases by four 254 spaces. When the block ends, the indent returns to the previous indent level. The indent level 255 applies to both code and comments throughout the block. (See the example in Section 4.1.2, 256 <a href="#blocks-k-r-style">Nonempty blocks: K & R Style</a>.)</p> 257 <a name="one-statement-per-line"/> 258 <h3>One statement per line</h3> 259 <p>Each statement is followed by a line-break.</p> 260 <a name="columnlimit"/> 261 <a name="column-limit"/> 262 <h3>Column limit: 120</h3> 263 <p> 264 The column limit for Log4j is 120 characters. 265 266 Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in 267 <a href="#line-wrapping">Line-wrapping</a>. 268 </p><p><strong>Exceptions:</strong></p> 269 <ol> 270 <li>Lines where obeying the column limit is not possible (for example, a long URL in Javadoc, 271 or a long JSNI method reference).</li> 272 <li><code>package</code> and <code>import</code> statements (see <a href="#package-statement">Package statement</a> and 273 <a href="#import-statements">Import statements</a>).</li> 274 <li>Command lines in a comment that may be cut-and-pasted into a shell.</li> 275 </ol><a name="line-wrapping"/> 276 <h3>Line-wrapping</h3> 277 <p class="terminology"><strong>Terminology Note:</strong> When code that might otherwise legally 278 occupy a single line is divided into multiple lines, typically to avoid overflowing the column 279 limit, this activity is called 280 <em>line-wrapping</em>.</p> 281 <p>There is no comprehensive, deterministic formula showing <em>exactly</em> how to line-wrap in 282 every situation. Very often there are several valid ways to line-wrap the same piece of code.</p> 283 <p class="tip"><strong>Tip:</strong> Extracting a method or local variable may solve the problem 284 without the need to line-wrap.</p> 285 <a name="line-wrapping-where-to-break"/> 286 <h4>Where to break</h4> 287 <p>The prime directive of line-wrapping is: prefer to break at a 288 <strong>higher syntactic level</strong>. Also:</p> 289 <ol> 290 <li>When a line is broken at a <em>non-assignment</em> operator the break comes <em>before</em> 291 the symbol. (Note that this is not the same practice used in Google style for other languages, 292 such as C++ and JavaScript.) 293 <ul> 294 <li>This also applies to the following "operator-like" symbols: the dot separator 295 (<code>.</code>), the ampersand in type bounds 296 (<code><T extends Foo & Bar></code>), and the pipe in 297 catch blocks 298 (<code>catch (FooException | BarException e)</code>).</li> 299 </ul> 300 </li> 301 <li>When a line is broken at an <em>assignment</em> operator the break typically comes 302 <em>after</em> the symbol, but either way is acceptable. 303 <ul> 304 <li>This also applies to the "assignment-operator-like" colon in an enhanced 305 <code>for</code> ("foreach") statement.</li> 306 </ul> 307 </li> 308 <li>A method or constructor name stays attached to the open parenthesis 309 (<code>(</code>) that follows it.</li> 310 <li>A comma (<code>,</code>) stays attached to the token that 311 precedes it.</li> 312 </ol> 313 <a name="indentation"/> 314 <a name="line-wrapping-indent"/> 315 <h4>Indent continuation lines at least +8 spaces</h4> 316 <p>When line-wrapping, each line after the first (each <em>continuation line</em>) is indented 317 at least +8 from the original line.</p> 318 <p>When there are multiple continuation lines, indentation may be varied beyond +8 as 319 desired. In general, two continuation lines use the same indentation level if and only if they 320 begin with syntactically parallel elements.</p> 321 <p>The section on <a href="#horizontal-alignment">Horizontal alignment</a> addresses 322 the discouraged practice of using a variable number of spaces to align certain tokens with 323 previous lines.</p> 324 <a name="whitespace"/> 325 <h3>Whitespace</h3> 326 <a name="vertical-whitespace"/> 327 <h4>Vertical Whitespace</h4> 328 <p>A single blank line appears:</p> 329 <ol> 330 <li><em>Between</em> consecutive members (or initializers) of a class: fields, constructors, 331 methods, nested classes, static initializers, instance initializers. 332 <ul> 333 <li><span class="exception"><strong>Exception:</strong> A blank line between two consecutive 334 fields (having no other code between them) is optional. Such blank lines are used as needed to 335 create <em>logical groupings</em> of fields.</span></li> 336 </ul> 337 </li> 338 <li>Within method bodies, as needed to create <em>logical groupings</em> of statements.</li><li><em>Optionally</em> before the first member or after the last member of the class (neither 339 encouraged nor discouraged).</li> 340 <li>As required by other sections of this document (such as 341 <a href="#import-statements">Import statements</a>).</li> 342 </ol> 343 <p><em>Multiple</em> consecutive blank lines are permitted, but never required (or encouraged).</p> 344 <a name="horizontal-whitespace"/> 345 <h4>Horizontal whitespace</h4> 346 <p>Beyond where required by the language or other style rules, and apart from literals, comments and 347 Javadoc, a single ASCII space also appears in the following places <strong>only</strong>.</p> 348 <ol> 349 <li>Separating any reserved word, such as 350 <code>if</code>, 351 <code>for</code> or 352 <code>catch</code>, from an open parenthesis 353 (<code>(</code>) 354 that follows it on that line</li> 355 <li>Separating any reserved word, such as 356 <code>else</code> or 357 <code>catch</code>, from a closing curly brace 358 (<code>}</code>) that precedes it on that line</li> 359 <li>Before any open curly brace 360 (<code>{</code>), with two exceptions: 361 <ul> 362 <li><code>String[][] x = {{"foo"}};</code> (no space is required 363 between <code>{{</code>, by item 8 below)</li> 364 </ul> 365 </li> 366 <li>On both sides of any binary or ternary operator. This also applies to the following 367 "operator-like" symbols: 368 <ul> 369 <li>the ampersand in a conjunctive type bound: 370 <code><T extends Foo & Bar></code></li> 371 <li>the pipe for a catch block that handles multiple exceptions: 372 <code>catch (FooException | BarException e)</code></li> 373 <li>the colon (<code>:</code>) in an enhanced 374 <code>for</code> ("foreach") statement</li> 375 </ul> 376 </li> 377 <li>After <code>,:;</code> or the closing parenthesis 378 (<code>)</code>) of a cast</li> 379 <li>On both sides of the double slash (<code>//</code>) that 380 begins an end-of-line comment. Here, multiple spaces are allowed, but not required.</li> 381 <li>Between the type and variable of a declaration: 382 <code>List<String> list</code></li> 383 <li><em>Optional</em> just inside both braces of an array initializer 384 <ul> 385 <li><code>new int[] {5, 6}</code> and 386 <code>new int[] { 5, 6 }</code> are both valid</li> 387 </ul> 388 </li> 389 </ol> 390 <p class="note"><strong>Note:</strong> This rule never requires or forbids additional space at the 391 start or end of a line, only <em>interior</em> space.</p> 392 <a name="horizontal-alignment"/> 393 <h4>Horizontal alignment: never required</h4> 394 <p class="terminology"><strong>Terminology Note:</strong> <em>Horizontal alignment</em> is the 395 practice of adding a variable number of additional spaces in your code with the goal of making 396 certain tokens appear directly below certain other tokens on previous lines.</p> 397 <p>This practice is permitted, but is <strong>never required</strong> by Google Style. It is not 398 even required to <em>maintain</em> horizontal alignment in places where it was already used.</p> 399 <p>Here is an example without alignment, then using alignment:</p> 400 <pre> 401 private int x; // this is fine 402 private Color color; // this too 403 404 private int x; // permitted, but future edits 405 private Color color; // may leave it unaligned 406 </pre> 407 <p class="tip"><strong>Tip:</strong> Alignment can aid readability, but it creates problems for 408 future maintenance. Consider a future change that needs to touch just one line. This change may 409 leave the formerly-pleasing formatting mangled, and that is <strong>allowed</strong>. More often 410 it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly 411 triggering a cascading series of reformattings. That one-line change now has a "blast radius." 412 This can at worst result in pointless busywork, but at best it still corrupts version history 413 information, slows down reviewers and exacerbates merge conflicts.</p> 414 <a name="parentheses"/> 415 <a name="grouping-parentheses"/> 416 <h3>Grouping parentheses: recommended</h3> 417 <p>Optional grouping parentheses are omitted only when author and reviewer agree that there is no 418 reasonable chance the code will be misinterpreted without them, nor would they have made the code 419 easier to read. It is <em>not</em> reasonable to assume that every reader has the entire Java 420 operator precedence table memorized.</p> 421 <a name="specific-constructs"/> 422 <h3>Specific constructs</h3> 423 <a name="enum-classes"/> 424 <h4>Enum classes</h4> 425 <p>After each comma that follows an enum constant, a line-break is optional.</p><p>An enum class with no methods 426 and no documentation on its constants may optionally be formatted 427 as if it were an array initializer (see 428 <a href="array-initializers">array initializers</a>).</p><pre> 429 private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS } 430 </pre> 431 <p>Since enum classes <em>are classes</em>, all other rules for formatting classes apply.</p> 432 <a name="localvariables"/> 433 <a name="variable-declarations"/> 434 <h4>Variable declarations</h4> 435 <a name="variables-per-declaration"/> 436 <h5>One variable per declaration</h5> 437 <p>Every variable declaration (field or local) declares only one variable: declarations such as 438 <code>int a, b;</code> are not used.</p> 439 <a name="variables-limited-scope"/> 440 <h5>Declared when needed, initialized as soon as possible</h5> 441 <p>Local variables are <strong>not</strong> habitually declared at the start of their containing 442 block or block-like construct. Instead, local variables are declared close to the point they are 443 first used (within reason), to minimize their scope. Local variable declarations typically have 444 initializers, or are initialized immediately after declaration.</p><a name="s4.8.3-arrays"/> 445 <h4>Arrays</h4> 446 <a name="array-initializers"/> 447 <h5>Array initializers: can be "block-like"</h5> 448 <p>Any array initializer may <em>optionally</em> be formatted as if it were a "block-like 449 construct." For example, the following are all valid (<strong>not</strong> an exhaustive 450 list):</p><pre> 451 new int[] { new int[] { 452 0, 1, 2, 3 0, 453 } 1, 454 2, 455 new int[] { 3, 456 0, 1, } 457 2, 3 458 } new int[] 459 {0, 1, 2, 3} 460 </pre><a name="array-declarations"/> 461 <h5>No C-style array declarations</h5> 462 <p>The square brackets form a part of the <em>type</em>, not the variable: 463 <code>String[] args</code>, not 464 <code>String args[]</code>.</p> 465 <a name="switch"/> 466 <h4>Switch statements</h4> 467 <p class="terminology"><strong>Terminology Note:</strong> Inside the braces of a 468 <em>switch block</em> are one or more <em>statement groups</em>. Each statement group consists of 469 one or more <em>switch labels</em> (either <code>case FOO:</code> or 470 <code>default:</code>), followed by one or more statements.</p> 471 <a name="switch-indentation"/> 472 <h5>Indentation</h5> 473 <p>As with any other block, the contents of a switch block are indented +2.</p> 474 <p>After a switch label, a newline appears, and the indentation level is increased +2, exactly as 475 if a block were being opened. The following switch label returns to the previous indentation 476 level, as if a block had been closed.</p> 477 <a name="fallthrough"/> 478 <a name="switch-fall-through"/> 479 <h5>Fall-through: commented</h5> 480 <p>Within a switch block, each statement group either terminates abruptly (with a 481 <code>break</code>, 482 <code>continue</code>, 483 <code>return</code> or thrown exception), or is marked with a comment 484 to indicate that execution will or <em>might</em> continue into the next statement group. Any 485 comment that communicates the idea of fall-through is sufficient (typically 486 <code>// fall through</code>). This special comment is not required in 487 the last statement group of the switch block. Example:</p><pre> 488 switch (input) { 489 case 1: 490 case 2: 491 prepareOneOrTwo(); 492 // fall through 493 case 3: 494 handleOneTwoOrThree(); 495 break; 496 default: 497 handleLargeNumber(input); 498 } 499 </pre><a name="switch-default"/> 500 <h5>The default case is present</h5> 501 <p>Each switch statement includes a <code>default</code> statement 502 group, even if it contains no code.</p> 503 <a name="annotations"/> 504 <h4>Annotations</h4> 505 <p>Annotations applying to a class, method or constructor appear immediately after the 506 documentation block, and each annotation is listed on a line of its own (that is, one annotation 507 per line). These line breaks do not constitute line-wrapping (Section 508 4.5, <a href="#line-wrapping">Line-wrapping</a>), so the indentation level is not 509 increased. Example:</p><pre> 510 @Override 511 @Nullable 512 public String getNameIfPresent() { ... } 513 </pre><p class="exception"><strong>Exception:</strong> A <em>single</em> parameterless annotation 514 <em>may</em> instead appear together with the first line of the signature, for example:</p><pre> 515 @Override public int hashCode() { ... } 516 </pre><p>Annotations applying to a field also appear immediately after the documentation block, but in 517 this case, <em>multiple</em> annotations (possibly parameterized) may be listed on the same line; 518 for example:</p><pre> 519 @Partial @Mock DataLoader loader; 520 </pre><p>There are no specific rules for formatting parameter and local variable annotations.</p> 521 <a name="comments"/> 522 <h4>Comments</h4> 523 <a name="block-comment-style"/> 524 <h5>Block comment style</h5> 525 <p>Block comments are indented at the same level as the surrounding code. They may be in 526 <code>/* ... */</code> style or 527 <code>// ...</code> style. For multi-line 528 <code>/* ... */</code> comments, subsequent lines must start with 529 <code>*</code> aligned with the <code>*</code> on the previous line.</p><pre> 530 /* 531 * This is // And so /* Or you can 532 * okay. // is this. * even do this. */ 533 */ 534 </pre> 535 <p>Comments are not enclosed in boxes drawn with asterisks or other characters.</p> 536 <p><strong>Tip:</strong> When writing multi-line comments, use the 537 <code>/* ... */</code> style if you want automatic code formatters to 538 re-wrap the lines when necessary (paragraph-style). Most formatters don't re-wrap lines in 539 <code>// ...</code> style comment blocks.</p> 540 <a name="modifiers"/> 541 <h4>Modifiers</h4> 542 <p>Class and member modifiers, when present, appear in the order 543 recommended by the Java Language Specification: 544 </p><pre> 545 public protected private abstract static final transient volatile synchronized native strictfp 546 </pre> 547 <a name="numeric-literals"/> 548 <h4>Numeric Literals</h4> 549 <p><code>long</code>-valued integer literals use an uppercase <code>L</code> suffix, never 550 lowercase (to avoid confusion with the digit <code>1</code>). For example, <code>3000000000L</code> 551 rather than <code>3000000000l</code>.</p> 552 </subsection> 553 <a name="naming"/> 554 <subsection name="Naming"> 555 <a name="identifier-names"/> 556 <h3>Rules common to all identifiers</h3> 557 <p>Identifiers use only ASCII letters and digits, and in two cases noted below, underscores. Thus 558 each valid identifier name is matched by the regular expression <code>\w+</code> .</p> 559 <p> In Google Style special prefixes or 560 suffixes, like those seen in the examples <code>name_</code>, 561 <code>mName</code>, <code>s_name</code> and 562 <code>kName</code>, are <strong>not</strong> used.</p> 563 <a name="specific-identifier-names"/> 564 <h3>Rules by identifier type</h3> 565 <a name="package-names"/> 566 <h4>Package names</h4> 567 <p>Package names are all lowercase, with consecutive words simply concatenated together (no 568 underscores). For example, <code>com.example.deepspace</code>, not 569 <code>com.example.deepSpace</code> or 570 <code>com.example.deep_space</code>.</p> 571 <a name="class-names"/> 572 <h4>Class names</h4> 573 <p>Class names are written in <a href="#camel-case">UpperCamelCase</a>.</p> 574 <p>Class names are typically nouns or noun phrases. For example, 575 <code>Character</code> or 576 <code>ImmutableList</code>. Interface names may also be nouns or 577 noun phrases (for example, <code>List</code>), but may sometimes be 578 adjectives or adjective phrases instead (for example, 579 <code>Readable</code>).</p><p>There are no specific rules or even well-established conventions for naming annotation types.</p><p><em>Test</em> classes are named starting with the name of the class they are testing, and ending 580 with <code>Test</code>. For example, 581 <code>HashTest</code> or 582 <code>HashIntegrationTest</code>.</p> 583 <a name="method-names"/> 584 <h4>Method names</h4> 585 <p>Method names are written in <a href="#s5.3-camel-case">lowerCamelCase</a>.</p> 586 <p>Method names are typically verbs or verb phrases. For example, 587 <code>sendMessage</code> or 588 <code>stop</code>.</p><p>Underscores may appear in JUnit <em>test</em> method names to separate logical components of the 589 name. One typical pattern is <code>test<i><MethodUnderTest></i>_<i><state></i></code>, 590 for example <code>testPop_emptyStack</code>. There is no One Correct 591 Way to name test methods.</p> 592 <a name="constants"/> 593 <a name="constant-names"/> 594 <h4>Constant names</h4> 595 <p>Constant names use <code>CONSTANT_CASE</code>: all uppercase 596 letters, with words separated by underscores. But what <em>is</em> a constant, exactly?</p> 597 <p>Every constant is a static final field, but not all static final fields are constants. Before 598 choosing constant case, consider whether the field really <em>feels like</em> a constant. For 599 example, if any of that instance's observable state can change, it is almost certainly not a 600 constant. Merely <em>intending</em> to never mutate the object is generally not 601 enough. Examples:</p><pre> 602 // Constants 603 static final int NUMBER = 5; 604 static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann"); 605 static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable 606 static final SomeMutableType[] EMPTY_ARRAY = {}; 607 enum SomeEnum { ENUM_CONSTANT } 608 609 // Not constants 610 static String nonFinal = "non-final"; 611 final String nonStatic = "non-static"; 612 static final Set<String> mutableCollection = new HashSet<String>(); 613 static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable); 614 static final Logger logger = Logger.getLogger(MyClass.getName()); 615 static final String[] nonEmptyArray = {"these", "can", "change"}; 616 </pre> 617 <p>These names are typically nouns or noun phrases.</p> 618 <a name="non-constant-field-names"/> 619 <h4>Non-constant field names</h4> 620 <p>Non-constant field names (static or otherwise) are written 621 in <a href="#camel-case">lowerCamelCase</a>.</p> 622 <p>These names are typically nouns or noun phrases. For example, 623 <code>computedValues</code> or 624 <code>index</code>.</p> 625 <a name="parameter-names"/> 626 <h4>Parameter names</h4> 627 <p>Parameter names are written in <a href="#camel-case">lowerCamelCase</a>.</p> 628 <p>One-character parameter names should be avoided.</p> 629 <a name="local-variable-names"/> 630 <h4>Local variable names</h4> 631 <p>Local variable names are written in <a href="#camel-case">lowerCamelCase</a>, and can be 632 abbreviated more liberally than other types of names.</p><p>However, one-character names should be avoided, except for temporary and looping variables.</p><p>Even when final and immutable, local variables are not considered to be constants, and should not 633 be styled as constants.</p> 634 <a name="type-variable-names"/> 635 <h4>Type variable names</h4> 636 <p>Each type variable is named in one of two styles:</p><ul><li>A single capital letter, optionally followed by a single numeral (such as 637 <code>E</code>, <code>T</code>, 638 <code>X</code>, <code>T2</code>) 639 </li><li>A name in the form used for classes (see 640 <a href="#class-names">Class names</a>), followed by the capital letter 641 <code>T</code> (examples: 642 <code>RequestT</code>, 643 <code>FooBarT</code>).</li></ul><a name="acronyms"/> 644 <a name="camelcase"/> 645 <a name="camel-case"/> 646 <h3>Camel case: defined</h3> 647 <p>Sometimes there is more than one reasonable way to convert an English phrase into camel case, 648 such as when acronyms or unusual constructs like "IPv6" or "iOS" are present. To improve 649 predictability, Google Style specifies the following (nearly) deterministic scheme.</p> 650 <p>Beginning with the prose form of the name:</p> 651 <ol> 652 <li>Convert the phrase to plain ASCII and remove any apostrophes. For example, "Müller's 653 algorithm" might become "Muellers algorithm".</li> 654 <li>Divide this result into words, splitting on spaces and any remaining punctuation (typically 655 hyphens). 656 657 <ul> 658 <li><em>Recommended:</em> if any word already has a conventional camel-case appearance in common 659 usage, split this into its constituent parts (e.g., "AdWords" becomes "ad words"). Note 660 that a word such as "iOS" is not really in camel case <em>per se</em>; it defies <em>any</em> 661 convention, so this recommendation does not apply.</li> 662 </ul> 663 </li> 664 <li>Now lowercase <em>everything</em> (including acronyms), then uppercase only the first 665 character of: 666 <ul><li>... each word, to yield <em>upper camel case</em>, or</li> 667 <li>... each word except the first, to yield <em>lower camel case</em></li> 668 </ul> 669 </li> 670 <li>Finally, join all the words into a single identifier.</li> 671 </ol> 672 <p>Note that the casing of the original words is almost entirely disregarded. Examples:</p> 673 <table> 674 <tr><th>Prose form</th><th>Correct</th><th>Incorrect</th></tr> 675 <tr><td>"XML HTTP request"</td><td><code>XmlHttpRequest</code></td><td><code>XMLHTTPRequest</code></td></tr> 676 <tr><td>"new customer ID"</td><td><code>newCustomerId</code></td><td><code>newCustomerID</code></td></tr> 677 <tr><td>"inner stopwatch"</td><td><code>innerStopwatch</code></td><td><code>innerStopWatch</code></td></tr> 678 <tr><td>"supports IPv6 on iOS?"</td><td><code>supportsIpv6OnIos</code></td><td><code>supportsIPv6OnIOS</code></td></tr> 679 <tr><td>"YouTube importer"</td><td><code>YouTubeImporter</code><br/><code>YoutubeImporter</code>*</td><td/></tr> 680 </table> 681 <p>*Acceptable, but not recommended.</p> 682 <p><strong>Note:</strong> Some words are ambiguously hyphenated in the English 683 language: for example "nonempty" and "non-empty" are both correct, so the method names 684 <code>checkNonempty</code> and 685 <code>checkNonEmpty</code> are likewise both correct.</p> 686 </subsection> 687 <subsection name="Programming Practices"> 688 <a name="programming-practices"/> 689 <a name="override-annotation"/> 690 <h3>@Override: always used</h3> 691 <p>A method is marked with the <code>@Override</code> annotation 692 whenever it is legal. This includes a class method overriding a superclass method, a class method 693 implementing an interface method, and an interface method respecifying a superinterface 694 method.</p> 695 <p class="exception"><strong>Exception:</strong><code>@Override</code> may be omitted when the parent method is 696 <code>@Deprecated</code>.</p> 697 <a name="caughtexceptions"/> 698 <a name="caught-exceptions"/> 699 <h3>Caught exceptions: not ignored</h3> 700 <p>Except as noted below, it is very rarely correct to do nothing in response to a caught 701 exception. (Typical responses are to log it, or if it is considered "impossible", rethrow it as an 702 <code>AssertionError</code>.)</p> 703 <p>When it truly is appropriate to take no action whatsoever in a catch block, the reason this is 704 justified is explained in a comment.</p><pre> 705 try { 706 int i = Integer.parseInt(response); 707 return handleNumericResponse(i); 708 } catch (NumberFormatException ok) { 709 // it's not numeric; that's fine, just continue 710 } 711 return handleTextResponse(response); 712 </pre><p><strong>Exception:</strong> In tests, a caught exception may be ignored 713 without comment <em>if</em> it is named <code>expected</code>. The 714 following is a very common idiom for ensuring that the method under test <em>does</em> throw an 715 exception of the expected type, so a comment is unnecessary here.</p><pre> 716 try { 717 emptyStack.pop(); 718 fail(); 719 } catch (NoSuchElementException expected) { 720 } 721 </pre><a name="static-members"/> 722 <h3>Static members: qualified using class</h3> 723 <p>When a reference to a static class member must be qualified, it is qualified with that class's 724 name, not with a reference or expression of that class's type.</p><pre> 725 Foo aFoo = ...; 726 Foo.aStaticMethod(); // good 727 <span>aFoo.aStaticMethod();</span> // bad 728 <span>somethingThatYieldsAFoo().aStaticMethod();</span> // very bad 729 </pre> 730 <a name="finalizers"/> 731 <h3>Finalizers: not used</h3> 732 <p>It is <strong>extremely rare</strong> to override <code>Object.finalize</code>.</p> 733 <p><strong>Tip:</strong> Don't do it. If you absolutely must, first read and understand 734 <a href="http://books.google.com/books?isbn=8131726592"><em>Effective Java</em></a> 735 Item 7, "Avoid Finalizers," very carefully, and <em>then</em> don't do it.</p> 736 </subsection> 737 <a name="javadoc"/> 738 <subsection name="Javadoc"> 739 <a name="javadoc-formatting"/> 740 <h3>Formatting</h3> 741 <a name="javadoc-multi-line"/> 742 <h4>General form</h4> 743 <p>The <em>basic</em> formatting of Javadoc blocks is as seen in this example:</p><pre> 744 /** 745 * Multiple lines of Javadoc text are written here, 746 * wrapped normally... 747 */ 748 public int method(String p1) { ... } 749 </pre><p>... or in this single-line example:</p><pre> 750 /** An especially short bit of Javadoc. */ 751 </pre><p>The basic form is always acceptable. The single-line form may be substituted when there are no 752 at-clauses present, and the entirety of the Javadoc block (including comment markers) can fit on a 753 single line.</p> 754 <a name="javadoc-paragraphs"/> 755 <h4>Paragraphs</h4> 756 <p>One blank line—that is, a line containing only the aligned leading asterisk 757 (<code>*</code>)—appears between paragraphs, and before the group of "at-clauses" if 758 present. Each paragraph but the first has <code><p></code> immediately before the first word, 759 with no space after.</p> 760 <a name="javadoc-at-clauses"/> 761 <h4>At-clauses</h4> 762 <p>Any of the standard "at-clauses" that are used appear in the order <code>@param</code>, 763 <code>@return</code>, <code>@throws</code>, <code>@deprecated</code>, and these four types never 764 appear with an empty description. When an at-clause doesn't fit on a single line, continuation lines 765 are indented four (or more) spaces from the position of the <code>@</code>. 766 </p> 767 <a name="summary-fragment"/> 768 <h3>The summary fragment</h3> 769 <p>The Javadoc for each class and member begins with a brief <strong>summary fragment</strong>. This 770 fragment is very important: it is the only part of the text that appears in certain contexts such as 771 class and method indexes.</p><p>This is a fragment—a noun phrase or verb phrase, not a complete sentence. It does 772 <strong>not</strong> begin with <code>A {@code Foo} is a...</code>, or 773 <code>This method returns...</code>, nor does it form a complete imperative sentence 774 like <code>Save the record.</code>. However, the fragment is capitalized and 775 punctuated as if it were a complete sentence.</p><p class="tip"><strong>Tip:</strong> A common mistake is to write simple Javadoc in the form 776 <code>/** @return the customer ID */</code>. This is incorrect, and should be 777 changed to <code>/** Returns the customer ID. */</code>.</p> 778 <a name="javadoc-optional"/> 779 <a name="javadoc-where-required"/> 780 <h3>Where Javadoc is used</h3> 781 <p>At the <em>minimum</em>, Javadoc is present for every 782 <code>public</code> class, and every 783 <code>public</code> or 784 <code>protected</code> member of such a class, with a few exceptions 785 noted below.</p><p>Other classes and members still have Javadoc <em>as needed</em>. Whenever an implementation 786 comment would be used to define the overall purpose or behavior of a class, method or field, that 787 comment is written as Javadoc instead. (It's more uniform, and more tool-friendly.)</p> 788 <a name="javadoc-exception-self-explanatory"/> 789 <h4>Exception: self-explanatory methods</h4> 790 <p>Javadoc is optional for "simple, obvious" methods like 791 <code>getFoo</code>, in cases where there <em>really and truly</em> is 792 nothing else worthwhile to say but "Returns the foo".</p> 793 <p class="note"><strong>Important:</strong> it is not appropriate to cite this exception to justify 794 omitting relevant information that a typical reader might need to know. For example, for a method 795 named <code>getCanonicalName</code>, don't omit its documentation 796 (with the rationale that it would say only 797 <code>/** Returns the canonical name. */</code>) if a typical reader may have no idea 798 what the term "canonical name" means!</p> 799 <a name="javadoc-exception-overrides"/> 800 <h4>Exception: overrides</h4> 801 <p>Javadoc is not always present on a method that overrides a supertype method. 802 </p> 803 </subsection> 804 </section> 805 </body> 806 </document>