Home | History | Annotate | Download | only in source
      1 <!--
      2    Copyright 2010 The Android Open Source Project 
      3 
      4    Licensed under the Apache License, Version 2.0 (the "License"); 
      5    you may not use this file except in compliance with the License.
      6    You may obtain a copy of the License at
      7 
      8        http://www.apache.org/licenses/LICENSE-2.0
      9 
     10    Unless required by applicable law or agreed to in writing, software
     11    distributed under the License is distributed on an "AS IS" BASIS,
     12    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13    See the License for the specific language governing permissions and
     14    limitations under the License.
     15 -->
     16 
     17 # Code Style Guidelines for Contributors #
     18 
     19 The rules below are not guidelines or recommendations, but strict rules.
     20 Contributions to Android generally *will not be accepted* if they do not
     21 adhere to these rules.
     22 
     23 Not all existing code follows these rules, but all new code is expected to.
     24 
     25 [TOC]
     26 
     27 ## Java Language Rules ##
     28 
     29 We follow standard Java coding conventions. We add a few rules:
     30 
     31 ### Don't Ignore Exceptions ###
     32 
     33 Sometimes it is tempting to write code that completely ignores an exception
     34 like this:
     35 
     36     void setServerPort(String value) {
     37         try {
     38             serverPort = Integer.parseInt(value);
     39         } catch (NumberFormatException e) { }
     40     }
     41 
     42 You must never do this. While you may think that your code will never
     43 encounter this error condition or that it is not important to handle it,
     44 ignoring exceptions like above creates mines in your code for someone else to
     45 trip over some day. You must handle every Exception in your code in some
     46 principled way. The specific handling varies depending on the case.
     47 
     48 *Anytime somebody has an empty catch clause they should have a
     49 creepy feeling. There are definitely times when it is actually the correct
     50 thing to do, but at least you have to think about it. In Java you can't escape
     51 the creepy feeling.* -[James Gosling](http://www.artima.com/intv/solid4.html)
     52 
     53 Acceptable alternatives (in order of preference) are:
     54 
     55 - Throw the exception up to the caller of your method.
     56 
     57         void setServerPort(String value) throws NumberFormatException {
     58             serverPort = Integer.parseInt(value);
     59         }
     60 
     61 - Throw a new exception that's appropriate to your level of abstraction.
     62 
     63         void setServerPort(String value) throws ConfigurationException {
     64             try {
     65                 serverPort = Integer.parseInt(value);
     66             } catch (NumberFormatException e) {
     67                 throw new ConfigurationException("Port " + value + " is not valid.");
     68             }
     69         }
     70 
     71 - Handle the error gracefully and substitute an appropriate value in the
     72 catch {} block.
     73 
     74         /** Set port. If value is not a valid number, 80 is substituted. */
     75 
     76         void setServerPort(String value) {
     77             try {
     78                 serverPort = Integer.parseInt(value);
     79             } catch (NumberFormatException e) {
     80                 serverPort = 80;  // default port for server 
     81             }
     82         }
     83 
     84 - Catch the Exception and throw a new `RuntimeException`. This is dangerous:
     85 only do it if you are positive that if this error occurs, the appropriate
     86 thing to do is crash.
     87 
     88         /** Set port. If value is not a valid number, die. */
     89 
     90         void setServerPort(String value) {
     91             try {
     92                 serverPort = Integer.parseInt(value);
     93             } catch (NumberFormatException e) {
     94                 throw new RuntimeException("port " + value " is invalid, ", e);
     95             }
     96         }
     97 
     98     Note that the original exception is passed to the constructor for
     99     RuntimeException.  If your code must compile under Java 1.3, you will need to
    100     omit the exception that is the cause.
    101 
    102 - Last resort: if you are confident that actually ignoring the exception is
    103 appropriate then you may ignore it, but you must also comment why with a good
    104 reason:
    105 
    106         /** If value is not a valid number, original port number is used. */
    107         void setServerPort(String value) {
    108             try {
    109                 serverPort = Integer.parseInt(value);
    110             } catch (NumberFormatException e) {
    111                 // Method is documented to just ignore invalid user input.
    112                 // serverPort will just be unchanged.
    113             }
    114         }
    115 
    116 ### Don't Catch Generic Exception ###
    117 
    118 Sometimes it is tempting to be lazy when catching exceptions and do
    119 something like this:
    120 
    121     try {
    122         someComplicatedIOFunction();        // may throw IOException 
    123         someComplicatedParsingFunction();   // may throw ParsingException 
    124         someComplicatedSecurityFunction();  // may throw SecurityException 
    125         // phew, made it all the way 
    126     } catch (Exception e) {                 // I'll just catch all exceptions 
    127         handleError();                      // with one generic handler!
    128     }
    129 
    130 You should not do this. In almost all cases it is inappropriate to catch
    131 generic Exception or Throwable, preferably not Throwable, because it includes
    132 Error exceptions as well. It is very dangerous. It means that Exceptions you
    133 never expected (including RuntimeExceptions like ClassCastException) end up
    134 getting caught in application-level error handling. It obscures the failure
    135 handling properties of your code. It means if someone adds a new type of
    136 Exception in the code you're calling, the compiler won't help you realize you
    137 need to handle that error differently. And in most cases you shouldn't be
    138 handling different types of exception the same way, anyway.
    139 
    140 There are rare exceptions to this rule: certain test code and top-level
    141 code where you want to catch all kinds of errors (to prevent them from showing
    142 up in a UI, or to keep a batch job running). In that case you may catch
    143 generic Exception (or Throwable) and handle the error appropriately. You
    144 should think very carefully before doing this, though, and put in comments
    145 explaining why it is safe in this place.
    146 
    147 Alternatives to catching generic Exception:
    148 
    149 - Catch each exception separately as separate catch blocks after a single
    150 try. This can be awkward but is still preferable to catching all Exceptions.
    151 Beware repeating too much code in the catch blocks.</li>
    152 
    153 - Refactor your code to have more fine-grained error handling, with multiple
    154 try blocks. Split up the IO from the parsing, handle errors separately in each
    155 case.
    156 
    157 - Rethrow the exception. Many times you don't need to catch the exception at
    158 this level anyway, just let the method throw it.
    159 
    160 Remember: exceptions are your friend! When the compiler complains you're
    161 not catching an exception, don't scowl. Smile: the compiler just made it
    162 easier for you to catch runtime problems in your code.
    163 
    164 ### Don't Use Finalizers ###
    165 
    166 Finalizers are a way to have a chunk of code executed
    167 when an object is garbage collected.
    168 
    169 Pros: can be handy for doing cleanup, particularly of external resources.
    170 
    171 Cons: there are no guarantees as to when a finalizer will be called,
    172 or even that it will be called at all.
    173 
    174 Decision: we don't use finalizers. In most cases, you can do what
    175 you need from a finalizer with good exception handling. If you absolutely need
    176 it, define a close() method (or the like) and document exactly when that
    177 method needs to be called. See InputStream for an example. In this case it is
    178 appropriate but not required to print a short log message from the finalizer,
    179 as long as it is not expected to flood the logs.
    180 
    181 ### Fully Qualify Imports ###
    182 
    183 When you want to use class Bar from package foo,there
    184 are two possible ways to import it:
    185 
    186 1. `import foo.*;`
    187 
    188 Pros: Potentially reduces the number of import statements.
    189 
    190 1. `import foo.Bar;`
    191 
    192 Pros: Makes it obvious what classes are actually used. Makes
    193 code more readable for maintainers. 
    194 
    195 Decision: Use the latter for importing all Android code. An explicit
    196 exception is made for java standard libraries (`java.util.*`, `java.io.*`, etc.)
    197 and unit test code (`junit.framework.*`)
    198 
    199 ## Java Library Rules ##
    200 
    201 There are conventions for using Android's Java libraries and tools. In some
    202 cases, the convention has changed in important ways and older code might use a
    203 deprecated pattern or library. When working with such code, it's okay to
    204 continue the existing style (see [Consistency](#consistency)). When
    205 creating new components never use deprecated libraries.
    206 
    207 ## Java Style Rules ##
    208 
    209 ### Use Javadoc Standard Comments ###
    210 
    211 Every file should have a copyright statement at the top. Then a package
    212 statement and import statements should follow, each block separated by a blank
    213 line. And then there is the class or interface declaration. In the Javadoc
    214 comments, describe what the class or interface does.
    215 
    216     /*
    217      * Copyright (C) 2010 The Android Open Source Project 
    218      *
    219      * Licensed under the Apache License, Version 2.0 (the "License");
    220      * you may not use this file except in compliance with the License.
    221      * You may obtain a copy of the License at 
    222      *
    223      *      http://www.apache.org/licenses/LICENSE-2.0
    224      *
    225      * Unless required by applicable law or agreed to in writing, software 
    226      * distributed under the License is distributed on an "AS IS" BASIS,
    227      * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    228      * See the License for the specific language governing permissions and 
    229      * limitations under the License.
    230      */
    231 
    232     package com.android.internal.foo;
    233 
    234     import android.os.Blah;
    235     import android.view.Yada;
    236 
    237     import java.sql.ResultSet;
    238     import java.sql.SQLException;
    239 
    240     /**
    241      * Does X and Y and provides an abstraction for Z.
    242      */
    243 
    244     public class Foo {
    245         ...
    246     }
    247 
    248 Every class and nontrivial public method you write *must* contain a
    249 Javadoc comment with at least one sentence describing what the class or method
    250 does. This sentence should start with a 3rd person descriptive verb.
    251 
    252 Examples:
    253 
    254     /** Returns the correctly rounded positive square root of a double value. */
    255     static double sqrt(double a) {
    256         ...
    257     }
    258 
    259 or
    260 
    261     /**
    262      * Constructs a new String by converting the specified array of 
    263      * bytes using the platform's default character encoding.
    264      */
    265     public String(byte[] bytes) {
    266         ...
    267     }
    268 
    269 You do not need to write Javadoc for trivial get and set methods such as
    270 `setFoo()` if all your Javadoc would say is "sets Foo". If the method does
    271 something more complex (such as enforcing a constraint or having an important
    272 side effect), then you must document it. And if it's not obvious what the
    273 property "Foo" means, you should document it.
    274 
    275 Every method you write, whether public or otherwise, would benefit from
    276 Javadoc. Public methods are part of an API and therefore require Javadoc.
    277 
    278 Android does not currently enforce a specific style for writing Javadoc
    279 comments, but you should follow the 
    280 [Sun Javadoc conventions](http://java.sun.com/j2se/javadoc/writingdoccomments/).
    281 
    282 ### Write Short Methods ###
    283 
    284 To the extent that it is feasible, methods should be kept small and
    285 focused. It is, however, recognized that long methods are sometimes
    286 appropriate, so no hard limit is placed on method length. If a method exceeds
    287 40 lines or so, think about whether it can be broken up without harming the
    288 structure of the program.
    289 
    290 ### Define Fields in Standard Places ###
    291 
    292 Fields should be defined either at the top of the file, or immediately before the methods that use them.
    293 
    294 ### Limit Variable Scope ###
    295 
    296 The scope of local variables should be kept to a minimum (*Effective
    297 Java* Item 29). By doing so, you increase the readability and
    298 maintainability of your code and reduce the likelihood of error. Each variable
    299 should be declared in the innermost block that encloses all uses of the
    300 variable.
    301 
    302 Local variables should be declared at the point they are first used. Nearly
    303 every local variable declaration should contain an initializer. If you don't
    304 yet have enough information to initialize a variable sensibly, you should
    305 postpone the declaration until you do.
    306 
    307 One exception to this rule concerns try-catch statements. If a variable is
    308 initialized with the return value of a method that throws a checked exception,
    309 it must be initialized inside a try block. If the value must be used outside
    310 of the try block, then it must be declared before the try block, where it
    311 cannot yet be sensibly initialized:
    312 
    313     // Instantiate class cl, which represents some sort of Set 
    314     Set s = null;
    315     try {
    316         s = (Set) cl.newInstance();
    317     } catch(IllegalAccessException e) {
    318         throw new IllegalArgumentException(cl + " not accessible");
    319     } catch(InstantiationException e) {
    320         throw new IllegalArgumentException(cl + " not instantiable");
    321     }
    322 
    323     // Exercise the set 
    324     s.addAll(Arrays.asList(args));
    325 
    326 But even this case can be avoided by encapsulating the try-catch block in a method:
    327 
    328     Set createSet(Class cl) {
    329         // Instantiate class cl, which represents some sort of Set 
    330         try {
    331             return (Set) cl.newInstance();
    332         } catch(IllegalAccessException e) {
    333             throw new IllegalArgumentException(cl + " not accessible");
    334         } catch(InstantiationException e) {
    335             throw new IllegalArgumentException(cl + " not instantiable");
    336         }
    337     }
    338 
    339     ...
    340 
    341     // Exercise the set 
    342     Set s = createSet(cl);
    343     s.addAll(Arrays.asList(args));
    344 
    345 Loop variables should be declared in the for statement itself unless there
    346 is a compelling reason to do otherwise:
    347 
    348     for (int i = 0; i n; i++) {
    349         doSomething(i);
    350     }
    351 
    352 and
    353 
    354     for (Iterator i = c.iterator(); i.hasNext(); ) {
    355         doSomethingElse(i.next());
    356     }
    357 
    358 ### Order Import Statements ###
    359 
    360 The ordering of import statements is:
    361 
    362 1. Android imports
    363 
    364 1. Imports from third parties (`com`, `junit`, `net`, `org`)
    365 
    366 1. `java` and `javax`
    367 
    368 To exactly match the IDE settings, the imports should be:
    369 
    370 - Alphabetical within each grouping, with capital letters before lower case letters (e.g. Z before a).
    371 
    372 - There should be a blank line between each major grouping (`android`, `com`, `junit`, `net`, `org`, `java`, `javax`).
    373 
    374 Originally there was no style requirement on the ordering. This meant that
    375 the IDE's were either always changing the ordering, or IDE developers had to
    376 disable the automatic import management features and maintain the imports by
    377 hand. This was deemed bad. When java-style was asked, the preferred styles
    378 were all over the map. It pretty much came down to our needing to "pick an
    379 ordering and be consistent." So we chose a style, updated the style guide, and
    380 made the IDEs obey it. We expect that as IDE users work on the code, the
    381 imports in all of the packages will end up matching this pattern without any
    382 extra engineering effort.
    383 
    384 This style was chosen such that:
    385 
    386 - The imports people want to look at first tend to be at the top (`android`)
    387 
    388 - The imports people want to look at least tend to be at the bottom (`java`)
    389 
    390 - Humans can easily follow the style
    391 
    392 - IDEs can follow the style
    393 
    394 The use and location of static imports have been mildly controversial
    395 issues. Some people would prefer static imports to be interspersed with the
    396 remaining imports, some would prefer them reside above or below all other
    397 imports. Additinally, we have not yet come up with a way to make all IDEs use
    398 the same ordering.
    399 
    400 Since most people consider this a low priority issue, just use your
    401 judgement and please be consistent.
    402 
    403 ### Use Spaces for Indentation ###
    404 
    405 We use 4 space indents for blocks. We never use tabs. When in doubt, be
    406 consistent with code around you.
    407 
    408 We use 8 space indents for line wraps, including function calls and
    409 assignments. For example, this is correct:
    410 
    411     Instrument i =
    412             someLongExpression(that, wouldNotFit, on, one, line);
    413 
    414 and this is not correct:
    415 
    416     Instrument i =
    417         someLongExpression(that, wouldNotFit, on, one, line);
    418 
    419 ### Follow Field Naming Conventions ###
    420 
    421 - Non-public, non-static field names start with m.
    422 
    423 - Static field names start with s.
    424 
    425 - Other fields start with a lower case letter.
    426 
    427 - Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
    428 
    429 For example:
    430 
    431     public class MyClass {
    432         public static final int SOME_CONSTANT = 42;
    433         public int publicField;
    434         private static MyClass sSingleton;
    435         int mPackagePrivate;
    436         private int mPrivate;
    437         protected int mProtected;
    438     }
    439 
    440 ### Use Standard Brace Style ###
    441 
    442 Braces do not go on their own line; they go on the same line as the code
    443 before them. So:
    444 
    445     class MyClass {
    446         int func() {
    447             if (something) {
    448                 // ...
    449             } else if (somethingElse) {
    450                 // ...
    451             } else {
    452                 // ...
    453             }
    454         }
    455     }
    456 
    457 We require braces around the statements for a conditional. Except, if the
    458 entire conditional (the condition and the body) fit on one line, you may (but
    459 are not obligated to) put it all on one line. That is, this is legal:
    460 
    461     if (condition) {
    462         body(); 
    463     }
    464 
    465 and this is legal:
    466 
    467     if (condition) body(); 
    468 
    469 but this is still illegal:
    470 
    471     if (condition)
    472         body();  // bad!
    473 
    474 ### Limit Line Length ###
    475 
    476 Each line of text in your code should be at most 100 characters long.
    477 
    478 There has been lots of discussion about this rule and the decision remains
    479 that 100 characters is the maximum.
    480 
    481 Exception: if a comment line contains an example command or a literal URL
    482 longer than 100 characters, that line may be longer than 100 characters for
    483 ease of cut and paste.
    484 
    485 Exception: import lines can go over the limit because humans rarely see
    486 them. This also simplifies tool writing.
    487 
    488 ### Use Standard Java Annotations ###
    489 
    490 Annotations should precede other modifiers for the same language element.
    491 Simple marker annotations (e.g. @Override) can be listed on the same line with
    492 the language element. If there are multiple annotations, or parameterized
    493 annotations, they should each be listed one-per-line in alphabetical
    494 order.<
    495 
    496 Android standard practices for the three predefined annotations in Java are:
    497 
    498 - `@Deprecated`: The @Deprecated annotation must be used whenever the use of the annotated
    499 element is discouraged. If you use the @Deprecated annotation, you must also
    500 have a @deprecated Javadoc tag and it should name an alternate implementation.
    501 In addition, remember that a @Deprecated method is *still supposed to
    502 work.*
    503 
    504     If you see old code that has a @deprecated Javadoc tag, please add the @Deprecated annotation.
    505 
    506 - `@Override`: The @Override annotation must be used whenever a method overrides the
    507 declaration or implementation from a super-class.
    508 
    509     For example, if you use the @inheritdocs Javadoc tag, and derive from a
    510     class (not an interface), you must also annotate that the method @Overrides
    511     the parent class's method.
    512 
    513 - `@SuppressWarnings`: The @SuppressWarnings annotation should only be used under circumstances
    514 where it is impossible to eliminate a warning. If a warning passes this
    515 "impossible to eliminate" test, the @SuppressWarnings annotation *must* be
    516 used, so as to ensure that all warnings reflect actual problems in the
    517 code.
    518 
    519     When a @SuppressWarnings annotation is necessary, it must be prefixed with
    520     a TODO comment that explains the "impossible to eliminate" condition. This
    521     will normally identify an offending class that has an awkward interface. For
    522     example:
    523 
    524         // TODO: The third-party class com.third.useful.Utility.rotate() needs generics 
    525         @SuppressWarnings("generic-cast")
    526         List blix = Utility.rotate(blax);
    527 
    528     When a @SuppressWarnings annotation is required, the code should be
    529     refactored to isolate the software elements where the annotation applies.
    530 
    531 ### Treat Acronyms as Words ###
    532 
    533 Treat acronyms and abbreviations as words in naming variables, methods, and classes. The names are much more readable:
    534 
    535 Good           | Bad
    536 ---------------|-------
    537 XmlHttpRequest | XMLHTTPRequest
    538 getCustomerId  | getCustomerID
    539 class Html     | class HTML
    540 String url     | String URL
    541 long id        | long ID
    542 
    543 Both the JDK and the Android code bases are very inconsistent with regards
    544 to acronyms, therefore, it is virtually impossible to be consistent with the
    545 code around you. Bite the bullet, and treat acronyms as words.
    546 
    547 For further justifications of this style rule, see *Effective Java*
    548 Item 38 and *Java Puzzlers* Number 68.
    549 
    550 ### Use TODO Comments ###
    551 
    552 Use TODO comments for code that is temporary, a short-term solution, or
    553 good-enough but not perfect.
    554 
    555 TODOs should include the string TODO in all caps, followed by a colon:
    556 
    557     // TODO: Remove this code after the UrlTable2 has been checked in.
    558 
    559 and
    560 
    561     // TODO: Change this to use a flag instead of a constant.
    562 
    563 If your TODO is of the form "At a future date do something" make sure that
    564 you either include a very specific date ("Fix by November 2005") or a very
    565 specific event ("Remove this code after all production mixers understand
    566 protocol V7.").
    567 
    568 ### Log Sparingly ###
    569 
    570 While logging is necessary it has a significantly negative impact on
    571 performance and quickly loses its usefulness if it's not kept reasonably
    572 terse. The logging facilities provides five different levels of logging. Below
    573 are the different levels and when and how they should be used.
    574 
    575 - `ERROR`: 
    576 This level of logging should be used when something fatal has happened,
    577 i.e. something that will have user-visible consequences and won't be
    578 recoverable without explicitly deleting some data, uninstalling applications,
    579 wiping the data partitions or reflashing the entire phone (or worse). This
    580 level is always logged. Issues that justify some logging at the ERROR level
    581 are typically good candidates to be reported to a statistics-gathering
    582 server.
    583 
    584 - `WARNING`: 
    585 This level of logging should used when something serious and unexpected
    586 happened, i.e. something that will have user-visible consequences but is
    587 likely to be recoverable without data loss by performing some explicit action,
    588 ranging from waiting or restarting an app all the way to re-downloading a new
    589 version of an application or rebooting the device. This level is always
    590 logged. Issues that justify some logging at the WARNING level might also be
    591 considered for reporting to a statistics-gathering server.
    592 
    593 - `INFORMATIVE:`
    594 This level of logging should used be to note that something interesting to
    595 most people happened, i.e. when a situation is detected that is likely to have
    596 widespread impact, though isn't necessarily an error. Such a condition should
    597 only be logged by a module that reasonably believes that it is the most
    598 authoritative in that domain (to avoid duplicate logging by non-authoritative
    599 components). This level is always logged.
    600 
    601 - `DEBUG`:
    602 This level of logging should be used to further note what is happening on the
    603 device that could be relevant to investigate and debug unexpected behaviors.
    604 You should log only what is needed to gather enough information about what is
    605 going on about your component. If your debug logs are dominating the log then
    606 you probably should be using verbose logging. 
    607 
    608     This level will be logged, even
    609 on release builds, and is required to be surrounded by an `if (LOCAL_LOG)` or `if
    610 (LOCAL_LOGD)` block, where `LOCAL_LOG[D]` is defined in your class or
    611 subcomponent, so that there can exist a possibility to disable all such
    612 logging. There must therefore be no active logic in an `if (LOCAL_LOG)` block.
    613 All the string building for the log also needs to be placed inside the `if
    614 (LOCAL_LOG)` block. The logging call should not be re-factored out into a
    615 method call if it is going to cause the string building to take place outside
    616 of the `if (LOCAL_LOG)` block. 
    617 
    618     There is some code that still says `if
    619 (localLOGV)`. This is considered acceptable as well, although the name is
    620 nonstandard.
    621 
    622 - `VERBOSE`:
    623 This level of logging should be used for everything else. This level will only
    624 be logged on debug builds and should be surrounded by an `if (LOCAL_LOGV)` block
    625 (or equivalent) so that it can be compiled out by default. Any string building
    626 will be stripped out of release builds and needs to appear inside the `if (LOCAL_LOGV)` block.
    627 
    628 *Notes:* 
    629 
    630 - Within a given module, other than at the VERBOSE level, an
    631 error should only be reported once if possible: within a single chain of
    632 function calls within a module, only the innermost function should return the
    633 error, and callers in the same module should only add some logging if that
    634 significantly helps to isolate the issue.
    635 
    636 - In a chain of modules, other than at the VERBOSE level, when a
    637 lower-level module detects invalid data coming from a higher-level module, the
    638 lower-level module should only log this situation to the DEBUG log, and only
    639 if logging provides information that is not otherwise available to the caller.
    640 Specifically, there is no need to log situations where an exception is thrown
    641 (the exception should contain all the relevant information), or where the only
    642 information being logged is contained in an error code. This is especially
    643 important in the interaction between the framework and applications, and
    644 conditions caused by third-party applications that are properly handled by the
    645 framework should not trigger logging higher than the DEBUG level. The only
    646 situations that should trigger logging at the INFORMATIVE level or higher is
    647 when a module or application detects an error at its own level or coming from
    648 a lower level.
    649 
    650 - When a condition that would normally justify some logging is
    651 likely to occur many times, it can be a good idea to implement some
    652 rate-limiting mechanism to prevent overflowing the logs with many duplicate
    653 copies of the same (or very similar) information.
    654 
    655 - Losses of network connectivity are considered common and fully
    656 expected and should not be logged gratuitously. A loss of network connectivity
    657 that has consequences within an app should be logged at the DEBUG or VERBOSE
    658 level (depending on whether the consequences are serious enough and unexpected
    659 enough to be logged in a release build).
    660 
    661 - A full filesystem on a filesystem that is acceessible to or on
    662 behalf of third-party applications should not be logged at a level higher than
    663 INFORMATIVE.
    664 
    665 - Invalid data coming from any untrusted source (including any
    666 file on shared storage, or data coming through just about any network
    667 connections) is considered expected and should not trigger any logging at a
    668 level higher then DEBUG when it's detected to be invalid (and even then
    669 logging should be as limited as possible).
    670 
    671 - Keep in mind that the `+` operator, when used on Strings,
    672 implicitly creates a `StringBuilder` with the default buffer size (16
    673 characters) and potentially quite a few other temporary String objects, i.e.
    674 that explicitly creating StringBuilders isn't more expensive than relying on
    675 the default '+' operator (and can be a lot more efficient in fact). Also keep
    676 in mind that code that calls `Log.v()` is compiled and executed on release
    677 builds, including building the strings, even if the logs aren't being
    678 read.
    679 
    680 - Any logging that is meant to be read by other people and to be
    681 available in release builds should be terse without being cryptic, and should
    682 be reasonably understandable. This includes all logging up to the DEBUG
    683 level.
    684 
    685 - When possible, logging should be kept on a single line if it
    686 makes sense. Line lengths up to 80 or 100 characters are perfectly acceptable,
    687 while lengths longer than about 130 or 160 characters (including the length of
    688 the tag) should be avoided if possible.
    689 
    690 - Logging that reports successes should never be used at levels
    691 higher than VERBOSE.
    692 
    693 - Temporary logging that is used to diagnose an issue that's
    694 hard to reproduce should be kept at the DEBUG or VERBOSE level, and should be
    695 enclosed by if blocks that allow to disable it entirely at compile-time.
    696 
    697 - Be careful about security leaks through the log. Private
    698 information should be avoided. Information about protected content must
    699 definitely be avoided. This is especially important when writing framework
    700 code as it's not easy to know in advance what will and will not be private
    701 information or protected content.
    702 
    703 - `System.out.println()` (or `printf()` for native code) should
    704 never be used. System.out and System.err get redirected to /dev/null, so your
    705 print statements will have no visible effects. However, all the string
    706 building that happens for these calls still gets executed.
    707 
    708 - *The golden rule of logging is that your logs may not
    709 unnecessarily push other logs out of the buffer, just as others may not push
    710 out yours.*
    711 
    712 ### Be Consistent ###
    713 
    714 Our parting thought: BE CONSISTENT. If you're editing code, take a few
    715 minutes to look at the code around you and determine its style. If they use
    716 spaces around their if clauses, you should too. If their comments have little
    717 boxes of stars around them, make your comments have little boxes of stars
    718 around them too.
    719 
    720 The point of having style guidelines is to have a common vocabulary of
    721 coding, so people can concentrate on what you're saying, rather than on how
    722 you're saying it. We present global style rules here so people know the
    723 vocabulary. But local style is also important. If code you add to a a file
    724 looks drastically different from the existing code around it, it throws
    725 readers out of their rhythm when they go to read it. Try to avoid this.</p>
    726 
    727 ## Javatests Style Rules ##
    728 
    729 ### Follow Test Method Naming Conventions ###
    730 
    731 When naming test methods, you can use an underscore to seperate what is
    732 being tested from the specific case being tested. This style makes it easier
    733 to see exactly what cases are being tested.
    734 
    735 For example:
    736 
    737     testMethod_specificCase1 testMethod_specificCase2
    738 
    739 
    740     void testIsDistinguishable_protanopia() {
    741         ColorMatcher colorMatcher = new ColorMatcher(PROTANOPIA)
    742         assertFalse(colorMatcher.isDistinguishable(Color.RED, Color.BLACK))
    743         assertTrue(colorMatcher.isDistinguishable(Color.X, Color.Y))
    744     }
    745 
    746