[
  {
    "path": ".github/CODEOWNERS",
    "content": "# https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax\n\ncsharp-style.md @jbcoe\nhtmlcssguide.html @tonyruscoe\nshellguide.md @eatnumber1 @vapier\n/go/ @chressie @gaal @katrinahoffert @kliegs @matttproud\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "This repository publishes copies of Google's internal style guides to\nassist developers working on Google owned and originated open source\nprojects. Development on these guides does not take place here.\n\nSubstantive changes to the style rules and suggested new rules should\nnot be submitted as issues in this repository. Material changes must be\nproposed, discussed, and approved on the internal forums first.\n\nIf an issue points out a simple mistake — a typo, a broken link, etc. —\nthen a correction might be made. However there is no commitment to do\nso. Issues are normally closed without comment. \n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "These style guides are copies of Google's internal style guides to\nassist developers working on Google owned and originated open source\nprojects. Changes should be made to the internal style guide first and\nonly then copied here.\n\nUnsolicited pull requests will not be merged and are usually closed\nwithout comment. If a PR points out a simple mistake — a typo, a broken\nlink, etc. — then the correction can be made internally and copied here\nthrough the usual process.\n\nSubstantive changes to the style rules and suggested new rules should\nnot be submitted as a PR in this repository. Material changes must be\nproposed, discussed, and approved on the internal forums first.\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, caste, color, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nRepo maintainers are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nRepo maintainers have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\n[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].\n\nCommunity Impact Guidelines were inspired by \n[Mozilla's code of conduct enforcement ladder][Mozilla CoC].\n\nFor answers to common questions about this code of conduct, see the FAQ at\n[https://www.contributor-covenant.org/faq][FAQ].\n\n[homepage]: https://www.contributor-covenant.org\n[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html\n[Mozilla CoC]: https://github.com/mozilla/diversity\n[FAQ]: https://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "LICENSE",
    "content": "Creative Commons Legal Code\n\nAttribution 3.0 Unported\n\n    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n    LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN\n    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS\n    INFORMATION ON AN \"AS-IS\" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES\n    REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR\n    DAMAGES RESULTING FROM ITS USE.\n\nLicense\n\nTHE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE\nCOMMONS PUBLIC LICENSE (\"CCPL\" OR \"LICENSE\"). THE WORK IS PROTECTED BY\nCOPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS\nAUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.\n\nBY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE\nTO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY\nBE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS\nCONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND\nCONDITIONS.\n\n1. Definitions\n\n a. \"Adaptation\" means a work based upon the Work, or upon the Work and\n    other pre-existing works, such as a translation, adaptation,\n    derivative work, arrangement of music or other alterations of a\n    literary or artistic work, or phonogram or performance and includes\n    cinematographic adaptations or any other form in which the Work may be\n    recast, transformed, or adapted including in any form recognizably\n    derived from the original, except that a work that constitutes a\n    Collection will not be considered an Adaptation for the purpose of\n    this License. For the avoidance of doubt, where the Work is a musical\n    work, performance or phonogram, the synchronization of the Work in\n    timed-relation with a moving image (\"synching\") will be considered an\n    Adaptation for the purpose of this License.\n b. \"Collection\" means a collection of literary or artistic works, such as\n    encyclopedias and anthologies, or performances, phonograms or\n    broadcasts, or other works or subject matter other than works listed\n    in Section 1(f) below, which, by reason of the selection and\n    arrangement of their contents, constitute intellectual creations, in\n    which the Work is included in its entirety in unmodified form along\n    with one or more other contributions, each constituting separate and\n    independent works in themselves, which together are assembled into a\n    collective whole. A work that constitutes a Collection will not be\n    considered an Adaptation (as defined above) for the purposes of this\n    License.\n c. \"Distribute\" means to make available to the public the original and\n    copies of the Work or Adaptation, as appropriate, through sale or\n    other transfer of ownership.\n d. \"Licensor\" means the individual, individuals, entity or entities that\n    offer(s) the Work under the terms of this License.\n e. \"Original Author\" means, in the case of a literary or artistic work,\n    the individual, individuals, entity or entities who created the Work\n    or if no individual or entity can be identified, the publisher; and in\n    addition (i) in the case of a performance the actors, singers,\n    musicians, dancers, and other persons who act, sing, deliver, declaim,\n    play in, interpret or otherwise perform literary or artistic works or\n    expressions of folklore; (ii) in the case of a phonogram the producer\n    being the person or legal entity who first fixes the sounds of a\n    performance or other sounds; and, (iii) in the case of broadcasts, the\n    organization that transmits the broadcast.\n f. \"Work\" means the literary and/or artistic work offered under the terms\n    of this License including without limitation any production in the\n    literary, scientific and artistic domain, whatever may be the mode or\n    form of its expression including digital form, such as a book,\n    pamphlet and other writing; a lecture, address, sermon or other work\n    of the same nature; a dramatic or dramatico-musical work; a\n    choreographic work or entertainment in dumb show; a musical\n    composition with or without words; a cinematographic work to which are\n    assimilated works expressed by a process analogous to cinematography;\n    a work of drawing, painting, architecture, sculpture, engraving or\n    lithography; a photographic work to which are assimilated works\n    expressed by a process analogous to photography; a work of applied\n    art; an illustration, map, plan, sketch or three-dimensional work\n    relative to geography, topography, architecture or science; a\n    performance; a broadcast; a phonogram; a compilation of data to the\n    extent it is protected as a copyrightable work; or a work performed by\n    a variety or circus performer to the extent it is not otherwise\n    considered a literary or artistic work.\n g. \"You\" means an individual or entity exercising rights under this\n    License who has not previously violated the terms of this License with\n    respect to the Work, or who has received express permission from the\n    Licensor to exercise rights under this License despite a previous\n    violation.\n h. \"Publicly Perform\" means to perform public recitations of the Work and\n    to communicate to the public those public recitations, by any means or\n    process, including by wire or wireless means or public digital\n    performances; to make available to the public Works in such a way that\n    members of the public may access these Works from a place and at a\n    place individually chosen by them; to perform the Work to the public\n    by any means or process and the communication to the public of the\n    performances of the Work, including by public digital performance; to\n    broadcast and rebroadcast the Work by any means including signs,\n    sounds or images.\n i. \"Reproduce\" means to make copies of the Work by any means including\n    without limitation by sound or visual recordings and the right of\n    fixation and reproducing fixations of the Work, including storage of a\n    protected performance or phonogram in digital form or other electronic\n    medium.\n\n2. Fair Dealing Rights. Nothing in this License is intended to reduce,\nlimit, or restrict any uses free from copyright or rights arising from\nlimitations or exceptions that are provided for in connection with the\ncopyright protection under copyright law or other applicable laws.\n\n3. License Grant. Subject to the terms and conditions of this License,\nLicensor hereby grants You a worldwide, royalty-free, non-exclusive,\nperpetual (for the duration of the applicable copyright) license to\nexercise the rights in the Work as stated below:\n\n a. to Reproduce the Work, to incorporate the Work into one or more\n    Collections, and to Reproduce the Work as incorporated in the\n    Collections;\n b. to create and Reproduce Adaptations provided that any such Adaptation,\n    including any translation in any medium, takes reasonable steps to\n    clearly label, demarcate or otherwise identify that changes were made\n    to the original Work. For example, a translation could be marked \"The\n    original work was translated from English to Spanish,\" or a\n    modification could indicate \"The original work has been modified.\";\n c. to Distribute and Publicly Perform the Work including as incorporated\n    in Collections; and,\n d. to Distribute and Publicly Perform Adaptations.\n e. For the avoidance of doubt:\n\n     i. Non-waivable Compulsory License Schemes. In those jurisdictions in\n        which the right to collect royalties through any statutory or\n        compulsory licensing scheme cannot be waived, the Licensor\n        reserves the exclusive right to collect such royalties for any\n        exercise by You of the rights granted under this License;\n    ii. Waivable Compulsory License Schemes. In those jurisdictions in\n        which the right to collect royalties through any statutory or\n        compulsory licensing scheme can be waived, the Licensor waives the\n        exclusive right to collect such royalties for any exercise by You\n        of the rights granted under this License; and,\n   iii. Voluntary License Schemes. The Licensor waives the right to\n        collect royalties, whether individually or, in the event that the\n        Licensor is a member of a collecting society that administers\n        voluntary licensing schemes, via that society, from any exercise\n        by You of the rights granted under this License.\n\nThe above rights may be exercised in all media and formats whether now\nknown or hereafter devised. The above rights include the right to make\nsuch modifications as are technically necessary to exercise the rights in\nother media and formats. Subject to Section 8(f), all rights not expressly\ngranted by Licensor are hereby reserved.\n\n4. Restrictions. The license granted in Section 3 above is expressly made\nsubject to and limited by the following restrictions:\n\n a. You may Distribute or Publicly Perform the Work only under the terms\n    of this License. You must include a copy of, or the Uniform Resource\n    Identifier (URI) for, this License with every copy of the Work You\n    Distribute or Publicly Perform. You may not offer or impose any terms\n    on the Work that restrict the terms of this License or the ability of\n    the recipient of the Work to exercise the rights granted to that\n    recipient under the terms of the License. You may not sublicense the\n    Work. You must keep intact all notices that refer to this License and\n    to the disclaimer of warranties with every copy of the Work You\n    Distribute or Publicly Perform. When You Distribute or Publicly\n    Perform the Work, You may not impose any effective technological\n    measures on the Work that restrict the ability of a recipient of the\n    Work from You to exercise the rights granted to that recipient under\n    the terms of the License. This Section 4(a) applies to the Work as\n    incorporated in a Collection, but this does not require the Collection\n    apart from the Work itself to be made subject to the terms of this\n    License. If You create a Collection, upon notice from any Licensor You\n    must, to the extent practicable, remove from the Collection any credit\n    as required by Section 4(b), as requested. If You create an\n    Adaptation, upon notice from any Licensor You must, to the extent\n    practicable, remove from the Adaptation any credit as required by\n    Section 4(b), as requested.\n b. If You Distribute, or Publicly Perform the Work or any Adaptations or\n    Collections, You must, unless a request has been made pursuant to\n    Section 4(a), keep intact all copyright notices for the Work and\n    provide, reasonable to the medium or means You are utilizing: (i) the\n    name of the Original Author (or pseudonym, if applicable) if supplied,\n    and/or if the Original Author and/or Licensor designate another party\n    or parties (e.g., a sponsor institute, publishing entity, journal) for\n    attribution (\"Attribution Parties\") in Licensor's copyright notice,\n    terms of service or by other reasonable means, the name of such party\n    or parties; (ii) the title of the Work if supplied; (iii) to the\n    extent reasonably practicable, the URI, if any, that Licensor\n    specifies to be associated with the Work, unless such URI does not\n    refer to the copyright notice or licensing information for the Work;\n    and (iv) , consistent with Section 3(b), in the case of an Adaptation,\n    a credit identifying the use of the Work in the Adaptation (e.g.,\n    \"French translation of the Work by Original Author,\" or \"Screenplay\n    based on original Work by Original Author\"). The credit required by\n    this Section 4 (b) may be implemented in any reasonable manner;\n    provided, however, that in the case of a Adaptation or Collection, at\n    a minimum such credit will appear, if a credit for all contributing\n    authors of the Adaptation or Collection appears, then as part of these\n    credits and in a manner at least as prominent as the credits for the\n    other contributing authors. For the avoidance of doubt, You may only\n    use the credit required by this Section for the purpose of attribution\n    in the manner set out above and, by exercising Your rights under this\n    License, You may not implicitly or explicitly assert or imply any\n    connection with, sponsorship or endorsement by the Original Author,\n    Licensor and/or Attribution Parties, as appropriate, of You or Your\n    use of the Work, without the separate, express prior written\n    permission of the Original Author, Licensor and/or Attribution\n    Parties.\n c. Except as otherwise agreed in writing by the Licensor or as may be\n    otherwise permitted by applicable law, if You Reproduce, Distribute or\n    Publicly Perform the Work either by itself or as part of any\n    Adaptations or Collections, You must not distort, mutilate, modify or\n    take other derogatory action in relation to the Work which would be\n    prejudicial to the Original Author's honor or reputation. Licensor\n    agrees that in those jurisdictions (e.g. Japan), in which any exercise\n    of the right granted in Section 3(b) of this License (the right to\n    make Adaptations) would be deemed to be a distortion, mutilation,\n    modification or other derogatory action prejudicial to the Original\n    Author's honor and reputation, the Licensor will waive or not assert,\n    as appropriate, this Section, to the fullest extent permitted by the\n    applicable national law, to enable You to reasonably exercise Your\n    right under Section 3(b) of this License (right to make Adaptations)\n    but not otherwise.\n\n5. Representations, Warranties and Disclaimer\n\nUNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR\nOFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY\nKIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,\nINCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,\nFITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF\nLATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,\nWHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION\nOF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.\n\n6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE\nLAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR\nANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES\nARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS\nBEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n7. Termination\n\n a. This License and the rights granted hereunder will terminate\n    automatically upon any breach by You of the terms of this License.\n    Individuals or entities who have received Adaptations or Collections\n    from You under this License, however, will not have their licenses\n    terminated provided such individuals or entities remain in full\n    compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will\n    survive any termination of this License.\n b. Subject to the above terms and conditions, the license granted here is\n    perpetual (for the duration of the applicable copyright in the Work).\n    Notwithstanding the above, Licensor reserves the right to release the\n    Work under different license terms or to stop distributing the Work at\n    any time; provided, however that any such election will not serve to\n    withdraw this License (or any other license that has been, or is\n    required to be, granted under the terms of this License), and this\n    License will continue in full force and effect unless terminated as\n    stated above.\n\n8. Miscellaneous\n\n a. Each time You Distribute or Publicly Perform the Work or a Collection,\n    the Licensor offers to the recipient a license to the Work on the same\n    terms and conditions as the license granted to You under this License.\n b. Each time You Distribute or Publicly Perform an Adaptation, Licensor\n    offers to the recipient a license to the original Work on the same\n    terms and conditions as the license granted to You under this License.\n c. If any provision of this License is invalid or unenforceable under\n    applicable law, it shall not affect the validity or enforceability of\n    the remainder of the terms of this License, and without further action\n    by the parties to this agreement, such provision shall be reformed to\n    the minimum extent necessary to make such provision valid and\n    enforceable.\n d. No term or provision of this License shall be deemed waived and no\n    breach consented to unless such waiver or consent shall be in writing\n    and signed by the party to be charged with such waiver or consent.\n e. This License constitutes the entire agreement between the parties with\n    respect to the Work licensed here. There are no understandings,\n    agreements or representations with respect to the Work not specified\n    here. Licensor shall not be bound by any additional provisions that\n    may appear in any communication from You. This License may not be\n    modified without the mutual written agreement of the Licensor and You.\n f. The rights granted under, and the subject matter referenced, in this\n    License were drafted utilizing the terminology of the Berne Convention\n    for the Protection of Literary and Artistic Works (as amended on\n    September 28, 1979), the Rome Convention of 1961, the WIPO Copyright\n    Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996\n    and the Universal Copyright Convention (as revised on July 24, 1971).\n    These rights and subject matter take effect in the relevant\n    jurisdiction in which the License terms are sought to be enforced\n    according to the corresponding provisions of the implementation of\n    those treaty provisions in the applicable national law. If the\n    standard suite of rights granted under applicable copyright law\n    includes additional rights not granted under this License, such\n    additional rights are deemed to be included in the License; this\n    License is not intended to restrict the license of any rights under\n    applicable law.\n\n\nCreative Commons Notice\n\n    Creative Commons is not a party to this License, and makes no warranty\n    whatsoever in connection with the Work. Creative Commons will not be\n    liable to You or any party on any legal theory for any damages\n    whatsoever, including without limitation any general, special,\n    incidental or consequential damages arising in connection to this\n    license. Notwithstanding the foregoing two (2) sentences, if Creative\n    Commons has expressly identified itself as the Licensor hereunder, it\n    shall have all rights and obligations of Licensor.\n\n    Except for the limited purpose of indicating to the public that the\n    Work is licensed under the CCPL, Creative Commons does not authorize\n    the use by either party of the trademark \"Creative Commons\" or any\n    related trademark or logo of Creative Commons without the prior\n    written consent of Creative Commons. Any permitted use will be in\n    compliance with Creative Commons' then-current trademark usage\n    guidelines, as may be published on its website or otherwise made\n    available upon request from time to time. For the avoidance of doubt,\n    this trademark restriction does not form part of this License.\n\n    Creative Commons may be contacted at https://creativecommons.org/.\n"
  },
  {
    "path": "README.md",
    "content": "# Google Style Guides\n\nEvery major open-source project has its own style guide: a set of conventions\n(sometimes arbitrary) about how to write code for that project. It is much\neasier to understand a large codebase when all the code in it is in a consistent\nstyle.\n\n“Style” covers a lot of ground, from “use camelCase for variable names” to\n“never use global variables” to “never use exceptions.” This project\n([google/styleguide](https://github.com/google/styleguide)) links to the style\nguidelines we use for Google code. If you are modifying a project that\noriginated at Google, you may be pointed to this page to see the style guides\nthat apply to that project.\n\n\n*   [AngularJS Style Guide][angular]\n*   [Common Lisp Style Guide][cl]\n*   [C++ Style Guide][cpp]\n*   [C# Style Guide][csharp]\n*   [Go Style Guide][go]\n*   [HTML/CSS Style Guide][htmlcss]\n*   [JavaScript Style Guide][js]\n*   [Java Style Guide][java]\n*   [JSON Style Guide][json]\n*   [Markdown Style Guide][markdown]\n*   [Objective-C Style Guide][objc]\n*   [Python Style Guide][py]\n*   [R Style Guide][r]\n*   [Shell Style Guide][sh]\n*   [Swift Style Guide][swift]\n*   [TypeScript Style Guide][ts]\n*   [Vim script Style Guide][vim]\n\nThis project also contains [google-c-style.el][emacs], an Emacs settings file\nfor Google style.\n\nWe used to host the cpplint tool, but we stopped making internal updates public.\nAn open source community has forked the project, so users are encouraged to use\nhttps://github.com/cpplint/cpplint instead.\n\nIf your project requires that you create a new XML document format, the\n[XML Document Format Style Guide][xml] may be helpful. In addition to actual\nstyle rules, it also contains advice on designing your own vs. adapting an\nexisting format, on XML instance document formatting, and on elements vs.\nattributes.\n\nThe style guides in this project are licensed under the CC-By 3.0 License, which\nencourages you to share these documents. See\n[https://creativecommons.org/licenses/by/3.0/][ccl] for more details.\n\nThe following Google style guide lives outside of this project:\n\n*  [Effective Dart][dart]\n*  [Kotlin Style Guide][kotlin]\n\nSince projects are largely maintained in a [VCS], writing good commit messages\nis important to long term project health. Please refer to [How to Write a Git\nCommit Message](https://cbea.ms/git-commit/) as an excellent resource. While it\nexplicitly refers to the Git [SCM], its principles apply to any system, and many\nGit conventions are trivial to translate to others.\n\n## Contributing\n\nWith few exceptions, these style guides are copies of Google's internal style\nguides to assist developers working on Google owned and originated open source\nprojects. Changes to the style guides are made to the internal style guides\nfirst and eventually copied into the versions found here. **External\ncontributions are not accepted.** Pull requests are regularly closed without\ncomment.\n\nPeople can file [issues using the GitHub tracker][gh-tracker]. Issues that raise\nquestions, justify changes on technical merits, or point out obvious mistakes\nmay get some engagement and could in theory lead to changes, but we are\nprimarily optimizing for Google's internal needs.\n\n<a rel=\"license\" href=\"https://creativecommons.org/licenses/by/3.0/\"><img alt=\"Creative Commons License\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by/3.0/88x31.png\" /></a>\n\n[cpp]: https://google.github.io/styleguide/cppguide.html\n[csharp]: https://google.github.io/styleguide/csharp-style.html\n[swift]: https://google.github.io/swift/\n[objc]: objcguide.md\n[gh-tracker]: https://github.com/google/styleguide/issues\n[go]: go/\n[java]: https://google.github.io/styleguide/javaguide.html\n[json]: https://google.github.io/styleguide/jsoncstyleguide.xml\n[kotlin]: https://developer.android.com/kotlin/style-guide\n[py]: https://google.github.io/styleguide/pyguide.html\n[r]: https://google.github.io/styleguide/Rguide.html\n[sh]: https://google.github.io/styleguide/shellguide.html\n[htmlcss]: https://google.github.io/styleguide/htmlcssguide.html\n[js]: https://google.github.io/styleguide/jsguide.html\n[markdown]: https://google.github.io/styleguide/docguide/style.html\n[ts]: https://google.github.io/styleguide/tsguide.html\n[angular]: https://google.github.io/styleguide/angularjs-google-style.html\n[cl]: https://google.github.io/styleguide/lispguide.xml\n[vim]: https://google.github.io/styleguide/vimscriptguide.xml\n[emacs]: https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el\n[xml]: https://google.github.io/styleguide/xmlstyle.html\n[dart]: https://www.dartlang.org/guides/language/effective-dart\n[ccl]: https://creativecommons.org/licenses/by/3.0/\n[SCM]: https://en.wikipedia.org/wiki/Source_control_management\n[VCS]: https://en.wikipedia.org/wiki/Version_control_system\n"
  },
  {
    "path": "Rguide.md",
    "content": "# Google's R Style Guide\n\nR is a high-level programming language used primarily for statistical computing\nand graphics. The goal of the R Programming Style Guide is to make our R code\neasier to read, share, and verify.\n\nThe Google R Style Guide is a fork of the\n[Tidyverse Style Guide](https://style.tidyverse.org/) by Hadley Wickham\n[license](https://creativecommons.org/licenses/by-sa/2.0/). Google modifications\nwere developed in collaboration with the internal R user community. The rest of\nthis document explains Google's primary differences with the Tidyverse guide,\nand why these differences exist.\n\n## Syntax\n\n### Naming conventions\n\nGoogle prefers identifying functions with `BigCamelCase` to clearly distinguish\nthem from other objects.\n\n```\n# Good\nDoNothing <- function() {\n  return(invisible(NULL))\n}\n```\n\nThe names of private functions should begin with a dot. This helps communicate\nboth the origin of the function and its intended use.\n\n```\n# Good\n.DoNothingPrivately <- function() {\n  return(invisible(NULL))\n}\n```\n\nWe previously recommended naming objects with `dot.case`. We're moving away from\nthat, as it creates confusion with S3 methods.\n\n### Don't use attach()\n\nThe possibilities for creating errors when using `attach()` are numerous.\n\n## Pipes\n\n### Right-hand assignment\n\nWe do not support using right-hand assignment.\n\n```\n# Bad\niris %>%\n  dplyr::summarize(max_petal = max(Petal.Width)) -> results\n```\n\nThis convention differs substantially from practices in other languages and\nmakes it harder to see in code where an object is defined. E.g. searching for\n`foo <-` is easier than searching for `foo <-` and `-> foo` (possibly split over\nlines).\n\n### Use explicit returns\n\nDo not rely on R's implicit return feature. It is better to be clear about your\nintent to `return()` an object.\n\n```\n# Good\nAddValues <- function(x, y) {\n  return(x + y)\n}\n\n# Bad\nAddValues <- function(x, y) {\n  x + y\n}\n```\n\n### Qualifying namespaces\n\nUsers should explicitly qualify namespaces for all external functions.\n\n```\n# Good\npurrr::map()\n```\n\nWe discourage using the `@import` Roxygen tag to bring in all functions into a\nNAMESPACE. Google has a very big R codebase, and importing all functions creates\ntoo much risk for name collisions.\n\nWhile there is a small performance penalty for using `::`, it makes it easier to\nunderstand dependencies in your code. There are some exceptions to this rule.\n\n*   Infix functions (`%name%`) always need to be imported.\n*   Certain `rlang` pronouns, notably `.data`, need to be imported.\n*   Functions from default R packages, including `datasets`, `utils`,\n   `grDevices`, `graphics`, `stats` and `methods`. If needed, you can `@import`\n   the full package.\n\nWhen importing functions, place the `@importFrom` tag in the Roxygen header\nabove the function where the external dependency is used.\n\n## Documentation\n\n### Package-level documentation\n\nAll packages should have a package documentation file, in a\n`packagename-package.R` file.\n"
  },
  {
    "path": "Rguide.xml",
    "content": "<?xml version=\"1.0\"?>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n  <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n    <meta http-equiv=\"refresh\" content=\"0; URL=Rguide.html\"/>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"styleguide.css\"/>\n    <title>Google's R Style Guide</title>\n  </head>\n  <body>\n    <h1>Google's R Style Guide</h1>\n    <p>\n      The style guide has moved to <a href=\"Rguide.html\">Rguide.html</a>\n    </p>\n  </body>\n</html>\n"
  },
  {
    "path": "_includes/head-custom.html",
    "content": "<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"/styleguide/favicon.ico\">\n"
  },
  {
    "path": "angularjs-google-style.html",
    "content": "\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"https://www.w3.org/TR/REC-html40/strict.dtd\">\n<html>\n<head>\n    <META http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n    <script src=\"include/styleguide.js\"></script>\n    <link href=\"/styleguide/favicon.ico\" type=\"image/x-icon\" rel=\"shortcut icon\">\n    <script src=\"include/jsguide.js\"></script>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"styleguide.css\">\n    <script src=\"https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js\"></script>\n    <title>Google's AngularJS Style Guide</title>\n    <style type=\"text/css\"><!--\n    th { background-color: #ddd; }\n    //--></style>\n</head>\n<body onload=\"initStyleGuide();\">\n<h1 class=\"external\">An AngularJS Style Guide for Closure Users at Google</h1>\n\n<h2 id=\"Background\" class=\"ignoreLink\">Background</h2>\n\n<p class=\"external\">This is the external version of a document that was primarily written for Google\n    engineers. It describes a recommended style for AngularJS apps that use Closure, as used\n    internally at Google. Members of the broader AngularJS community should feel free to apply\n    (or not apply) these recommendations, as relevant to their own use cases.</p>\n\n<p class=\"external\">This document describes style for AngularJS apps in google3. This guide\n    supplements and extends the <a href=\"https://google.github.io/styleguide/jsguide.html\">\n        Google JavaScript Style Guide</a>.\n</p>\n\n<p><b>Style Note</b>: Examples on the AngularJS external webpage, and many external apps, are\n    written in a style that freely uses closures, favors functional inheritance, and does not often use\n    <a class=\"external\"\n                               href=\"https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System\">\n        JavaScript types</a>. Google follows a more rigorous Javascript style to support JSCompiler\n    optimizations and large code bases - see the javascript-style mailing list.\n    This is not an Angular-specific issue, and is not discussed further in this style guide.\n    (But if you want further reading:\n    <a  href=\"http://martinfowler.com/bliki/Lambda.html\">Martin Fowler on closures</a>,\n    <a href=\"http://jibbering.com/faq/notes/closures/\">much longer description</a>, appendix A of the\n    <a href=\"https://books.google.com/books/about/Closure_The_Definitive_Guide.html?id=p7uyWPcVGZsC\">\n        closure book</a> has a good description of inheritance patterns and why it prefers\n    pseudoclassical,\n    <a href=\"https://books.google.com/books/about/JavaScript.html?id=PXa2bby0oQ0C\">\n        Javascript, the Good Parts</a> as a counter.)</p>\n\n<h2>1 Angular Language Rules</h2>\n\n<h3 id=\"googprovide\">Manage dependencies with Closure's goog.require and goog.provide</h3>\n<p>Choose a namespace for your project, and use goog.provide and goog.require.</p>\n<pre class=\"prettyprint lang-js\">\ngoog.provide('hello.about.AboutCtrl');\ngoog.provide('hello.versions.Versions');\n</pre>\n\n<p><b>Why?</b>\n    Google BUILD rules integrate nicely with closure provide/require.</p>\n\n<h3 id=\"modules\">Modules</h3>\n\n<p>Your main application module should be in your root client directory. A module should never be\n    altered other than the one where it is defined.</p>\n\n<p>Modules may either be defined in the same file as their components (this works well for a module\n    that contains exactly one service) or in a separate file for wiring pieces together.</p>\n\n<p><b>Why?</b>\n    A module should be consistent for anyone that wants to include it as a reusable component.\n    If a module can mean different things depending on which files are included, it is not consistent.\n</p>\n\n<h3 id=\"moduledeps\">\n    Modules should reference other modules using the Angular Module's \"name\" property\n</h3>\n\n<p>For example:</p>\n\n<pre class=\"prettyprint lang-js\">\n// file submodulea.js:\n  goog.provide('my.submoduleA');\n\n  my.submoduleA = angular.module('my.submoduleA', []);\n  // ...\n\n// file app.js\n  goog.require('my.submoduleA');\n\n  Yes: my.application.module = angular.module('hello', [my.submoduleA.name]);\n  <font color=\"red\">\n      No: my.application.module = angular.module('hello', ['my.submoduleA']);\n  </font></pre>\n\n<p><b>Why?</b>\n    Using a property of my.submoduleA prevents Closure presubmit failures complaining that the file is\n    required but never used. Using the .name property avoids duplicating strings.</p>\n\n<h3 id=\"externs\">Use a common externs file</h3>\n\n<p>This maximally allows the JS compiler to enforce type safety in the presence of externally\n    provided types from Angular, and means you don't have to worry about Angular vars being obfuscated\n    in a confusing way. </p>\n\n<p>Note to readers outside Google: the current externs file is located in an internal-to-Google\n    directory, but an example can be found on github <a href=\"https://github.com/angular/angular.js/pull/4722\">\n        here</a>.</p>\n\n<h3 id=\"compilerflags\">JSCompiler Flags</h3>\n<p><b>Reminder</b>: According to the JS style guide, customer facing code must be compiled.</p>\n\n<p><b>Recommended</b>: Use the JSCompiler (the closure compiler that works with js_binary by\n    default) and ANGULAR_COMPILER_FLAGS_FULL from //javascript/angular/build_defs/build_defs for\n    your base flags.\n</p>\n\n<p>Note - if you are using @export for methods, you will need to add the compiler flag</p>\n<pre>\n\"--generate_exports\",\n</pre>\n\n<p>If you are using @export for properties, you will need to add the flags:</p>\n<pre>\n\"--generate_exports\",\n\"--remove_unused_prototype_props_in_externs=false\",\n\"--export_local_property_definitions\",\n</pre>\n\n<h3 id=\"controllers\">Controllers and Scopes</h3>\n<p>Controllers are classes. Methods should be defined on MyCtrl.prototype.</p>\n\n<p>Google Angular applications should use the <b>'controller as'</b> style to export the controller\n    onto the scope. This is fully implemented in Angular 1.2 and can be mimicked in pre-Angular 1.2\n    builds.\n</p>\n\n<p>Pre Angular 1.2, this looks like:</p>\n<pre class=\"prettyprint lang-js\">\n/**\n * Home controller.\n *\n * @param {!angular.Scope} $scope\n * @constructor\n * @ngInject\n * @export\n */\nhello.mainpage.HomeCtrl = function($scope) {\n  /** @export */\n  $scope.homeCtrl = this; // This is a bridge until Angular 1.2 controller-as\n\n  /**\n   * @type {string}\n   * @export\n   */\n  this.myColor = 'blue';\n};\n\n\n/**\n * @param {number} a\n * @param {number} b\n * @export\n */\nhello.mainpage.HomeCtrl.prototype.add = function(a, b) {\n  return a + b;\n};\n</pre>\n\n<p>And the template:</p>\n\n<pre>\n&lt;div ng-controller=\"hello.mainpage.HomeCtrl\"/&gt;\n  &lt;span ng-class=\"homeCtrl.myColor\"&gt;I'm in a color!&lt;/span&gt;\n  &lt;span&gt;{{homeCtrl.add(5, 6)}}&lt;/span&gt;\n&lt;/div&gt;\n</pre>\n\n<p>After Angular 1.2, this looks like:</p>\n\n<pre class=\"prettyprint lang-js\">\n/**\n * Home controller.\n *\n * @constructor\n * @ngInject\n * @export\n */\nhello.mainpage.HomeCtrl = function() {\n  /**\n   * @type {string}\n   * @export\n   */\n  this.myColor = 'blue';\n};\n\n\n/**\n * @param {number} a\n * @param {number} b\n * @export\n */\nhello.mainpage.HomeCtrl.prototype.add = function(a, b) {\n  return a + b;\n};\n</pre>\n\n<p>If you are compiling with property renaming, expose properties and methods using the @export\n    annotation. Remember to @export the constructor as well.</p>\n\n<p>And in the template:</p>\n\n<pre>\n&lt;div ng-controller=\"hello.mainpage.HomeCtrl as homeCtrl\"/&gt;\n  &lt;span ng-class=\"homeCtrl.myColor\"&gt;I'm in a color!&lt;/span&gt;\n  &lt;span&gt;{{homeCtrl.add(5, 6)}}&lt;/span&gt;\n&lt;/div&gt;\n</pre>\n\n<p><b>Why?</b>\n    Putting methods and properties directly onto the controller, instead of building up a scope\n    object, fits better with the Google Closure class style. Additionally, using 'controller as'\n    makes it obvious which controller you are accessing when multiple controllers apply to an element.\n    Since there is always a '.' in the bindings, you don't have to worry about prototypal inheritance\n    masking primitives.</p>\n\n<h3 id=\"directives\">Directives</h3>\n\n<p>All DOM manipulation should be done inside directives. Directives should be kept small and use\n    composition. Files defining directives should goog.provide a static function which returns the\n    directive definition object.</p>\n\n<pre class=\"prettyprint lang-js\">\ngoog.provide('hello.pane.paneDirective');\n\n/**\n * Description and usage\n * @return {angular.Directive} Directive definition object.\n */\nhello.pane.paneDirective = function() {\n  // ...\n};\n</pre>\n\n<p><b>Exception</b>: DOM manipulation may occur in services for DOM elements disconnected from the\n    rest of the view, e.g. dialogs or keyboard shortcuts.</p>\n\n<h3 id=\"services\">Services</h3>\n\n<p>Services registered on the module with <code>module.service</code> are classes.\n    Use <code>module.service</code> instead of <code>module.provider</code> or\n    <code>module.factory</code> unless you need to do initialization beyond just creating a\n    new instance of the class.</p>\n\n<pre class=\"prettyprint lang-js\">\n/**\n * @param {!angular.$http} $http The Angular http service.\n * @constructor\n */\nhello.request.Request = function($http) {\n  /** @type {!angular.$http} */\n  this.http_ = $http;\n};\n\nhello.request.Request.prototype.get = function() {/*...*/};\n</pre>\n\n<p>In the module:</p>\n\n<pre class=\"prettyprint lang-js\">\nmodule.service('request', hello.request.Request);\n</pre>\n\n\n<h2>2 Angular Style Rules</h2>\n\n<h3 id=\"dollarsign\">Reserve $ for Angular properties and services</h3>\n<p>Do not use $ to prepend your own object properties and service identifiers. Consider this style\n    of naming reserved by AngularJS and jQuery.</p>\n\n<p>Yes:</p>\n<pre class=\"prettyprint lang-js\">\n  $scope.myModel = { value: 'foo' }\n  myModule.service('myService', function() { /*...*/ });\n  var MyCtrl = function($http) {this.http_ = $http;};\n</pre>\n\n<p><font color=\"red\">No:</font></p>\n<pre class=\"prettyprint\">\n  $scope.$myModel = { value: 'foo' } // BAD\n  $scope.myModel = { $value: 'foo' } // BAD\n  myModule.service('$myService', function() { ... }); // BAD\n  var MyCtrl = function($http) {this.$http_ = $http;}; // BAD\n</pre>\n\n<p><b>Why?</b>\n    It's useful to distinguish between Angular / jQuery builtins and things you add yourself.\n    In addition, $ is not an acceptable character for variables names in the JS style guide.\n</p>\n\n<h3 id=\"customelements\">Custom elements</h3>\n\n<p>For custom elements (e.g. <code>&lt;ng-include src=\"template\"&gt;&lt;/ng-include&gt;</code>), IE8\n    requires special support (html5shiv-like hacks) to enable css styling.  Be aware of this\n    restriction in apps targeting old versions of IE.</p>\n\n<h2>3 Angular Tips, Tricks, and Best Practices</h2>\n\n<p>These are not strict style guide rules, but are placed here as reference for folks getting\n    started with Angular at Google.</p>\n\n<h3 id=\"testing\">Testing</h3>\n\n<p>Angular is designed for test-driven development.</p>\n\n<p>The recommended unit testing setup is Jasmine + Karma (though you could use closure tests\n    or js_test)</p>\n\n<p>Angular provides easy adapters to load modules and use the injector in Jasmine tests.\n<ul>\n    <li><a href = \"https://docs.angularjs.org/api/angular.mock.module\">module</a>\n    <li><a href=\"https://docs.angularjs.org/api/angular.mock.inject\">inject</a>\n</ul>\n</p>\n\n\n<h3 id=\"appstructure\">Consider using the Best Practices for App Structure</h3>\n<p>\n    This  <a href=\"https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub\">directory structure doc</a> describes how to structure your application with controllers in\n    nested subdirectories and all components (e.g. services and directives) in a 'components' dir.\n</p>\n\n\n<h3 id=\"scopeinheritance\">Be aware of how scope inheritance works</h3>\n\n<p>See <a href=\"https://github.com/angular/angular.js/wiki/Understanding-Scopes#wiki-JSproto\">\n    The Nuances of Scope Prototypal Inheritance</a></p>\n\n<h3 id=\"nginject\">Use @ngInject for easy dependency injection compilation</h3>\n<p>This removes the need to add <code>myCtrl['$inject'] = ...</code> to prevent minification from\n    messing up Angular's dependency injection.</p>\n\n<p>Usage:</p>\n<pre class=\"prettyprint lang-js\">\n/**\n * My controller.\n * @param {!angular.$http} $http\n * @param {!my.app.myService} myService\n * @constructor\n * @export\n * @ngInject\n */\nmy.app.MyCtrl = function($http, myService) {\n  //...\n};\n</pre>\n\n<h2 id=\"bestpractices\">4 Best practices links and docs</h2>\n\n<ul>\n    <li><a href=\"https://github.com/angular/angular.js/wiki/Best-Practices\">\n        Best Practices</a> from Angular on GitHub</li>\n    <li><a href=\"https://www.youtube.com/watch?v=ZhfUv0spHCY\">\n        Meetup video</a> (not Google specific)</li>\n</ul>\n<address>\n    Last modified Feb 07 2013\n</address>\n</body>\n<html>\n"
  },
  {
    "path": "assets/css/style.scss",
    "content": "---\n# Keep this YAML front matter block to trigger Jekyll processing.\n# See https://jekyllrb.com/docs/frontmatter for more information.\n---\n\n@import \"{{ site.theme }}\";\n\n// Hide “This site is open source. Improve this page.”\n.footer {\n  display: none;\n}\n"
  },
  {
    "path": "cppguide.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Google C++ Style Guide</title>\n<link rel=\"stylesheet\" href=\"include/styleguide.css\">\n<script src=\"include/styleguide.js\"></script>\n<link rel=\"shortcut icon\" href=\"/styleguide/favicon.ico\">\n</head>\n<body onload=\"initStyleGuide();\">\n<div id=\"content\">\n<h1>Google C++ Style Guide</h1>\n<div class=\"horizontal_toc\" id=\"tocDiv\"></div>\n\n<h2 id=\"Background\" class=\"ignoreLink\">Background</h2>\n\n<p>C++ is one of the main development languages  used by\nmany of Google's open-source projects. As every C++\nprogrammer knows, the language has many powerful features, but\nthis power brings with it complexity, which in turn can make\ncode more bug-prone and harder to read and maintain.</p>\n\n<p>The goal of this guide is to manage this complexity by\ndescribing in detail the dos and don'ts of writing C++\ncode. These rules exist to\nkeep  the codebase manageable while still allowing\ncoders to use C++ language features productively.</p>\n\n<p><em>Style</em>, also known as readability, is what we call\nthe conventions that govern our C++ code. The term Style is a\nbit of a misnomer, since these conventions cover far more than\njust source file formatting.</p>\n\n<p>\nMost open-source projects developed by\nGoogle conform to the requirements in this guide.\n</p>\n\n\n\n<p>Note that this guide is not a C++ tutorial: we assume that\nthe reader is familiar with the language. </p>\n\n<h3 id=\"Goals\">Goals of the Style Guide</h3>\n\n<p>Why do we have this document?</p>\n\n<p>There are a few core goals that we believe this guide should\nserve. These are the fundamental <b>why</b>s that\nunderlie all of the individual rules. By bringing these ideas to\nthe fore, we hope to ground discussions and make it clearer to our\nbroader community why the rules are in place and why particular\ndecisions have been made. If you understand what goals each rule is\nserving, it should be clearer to everyone when a rule may be waived\n(some can be), and what sort of argument or alternative would be\nnecessary to change a rule in the guide.</p>\n\n<p>The goals of the style guide as we currently see them are as follows:</p>\n<dl>\n<dt>Style rules should pull their weight</dt>\n<dd>The benefit of a style rule\nmust be large enough to justify asking all of our engineers to\nremember it. The benefit is measured relative to the codebase we would\nget without the rule, so a rule against a very harmful practice may\nstill have a small benefit if people are unlikely to do it\nanyway. This principle mostly explains the rules we don't have, rather\nthan the rules we do: for example, <code>goto</code> contravenes many\nof the following principles, but is already vanishingly rare, so the Style\nGuide doesn't discuss it.</dd>\n\n<dt>Optimize for the reader, not the writer</dt>\n<dd>Our codebase (and most individual components submitted to it) is\nexpected to continue for quite some time. As a result, more time will\nbe spent reading most of our code than writing it. We explicitly\nchoose to optimize for the experience of our average software engineer\nreading, maintaining, and debugging code in our codebase rather than\nease when writing said code.  \"Leave a trace for the reader\" is a\nparticularly common sub-point of this principle: When something\nsurprising or unusual is happening in a snippet of code (for example,\ntransfer of pointer ownership), leaving textual hints for the reader\nat the point of use is valuable (<code>std::unique_ptr</code>\ndemonstrates the ownership transfer unambiguously at the call\nsite). </dd>\n\n<dt>Be consistent with existing code</dt>\n<dd>Using one style consistently through our codebase lets us focus on\nother (more important) issues. Consistency also allows for automation:\ntools that format your code or adjust your <code>#include</code>s only\nwork properly when your code is consistent with the expectations of\nthe tooling. In many cases, rules that are attributed to \"Be\nConsistent\" boil down to \"Just pick one and stop worrying about it\";\nthe potential value of allowing flexibility on these points is\noutweighed by the cost of having people argue over them. However,\nthere are limits to consistency; it is a good tie breaker when there\nis no clear technical argument, nor a long-term direction. It applies\nmore heavily locally (per file, or for a tightly-related set of\ninterfaces). Consistency should not generally be used as a\njustification to do things in an old style without considering the\nbenefits of the new style, or the tendency of the codebase to converge\non newer styles over time.</dd>\n\n<dt>Be consistent with the broader C++ community when appropriate</dt>\n<dd>Consistency with the way other organizations use C++ has value for\nthe same reasons as consistency within our codebase. If a feature in\nthe C++ standard solves a problem, or if some idiom is widely known\nand accepted, that's an argument for using it. However, sometimes\nstandard features and idioms are flawed, or were just designed without\nour codebase's needs in mind. In those cases (as described below) it's\nappropriate to constrain or ban standard features.  In some cases we\nprefer a homegrown or third-party library over a library defined in\nthe C++ Standard, either out of perceived superiority or insufficient\nvalue to transition the codebase to the standard interface.</dd>\n\n<dt>Avoid surprising or dangerous constructs</dt>\n<dd>C++ has features that are more surprising or dangerous than one\nmight think at a glance. Some style guide restrictions are in place to\nprevent falling into these pitfalls. There is a high bar for style\nguide waivers on such restrictions, because waiving such rules often\ndirectly risks compromising program correctness.\n</dd>\n\n<dt>Avoid constructs that our average C++ programmer would find tricky\nor hard to maintain</dt>\n<dd>C++ has features that may not be generally appropriate because of\nthe complexity they introduce to the code. In widely used\ncode, it may be more acceptable to use\ntrickier language constructs, because any benefits of more complex\nimplementation are multiplied widely by usage, and the cost in understanding\nthe complexity does not need to be paid again when working with new\nportions of the codebase. When in doubt, waivers to rules of this type\ncan be sought by asking\nyour project leads. This is specifically\nimportant for our codebase because code ownership and team membership\nchanges over time: even if everyone that works with some piece of code\ncurrently understands it, such understanding is not guaranteed to hold a\nfew years from now.</dd>\n\n<dt>Be mindful of our scale</dt>\n<dd>With a codebase of 100+ million lines and thousands of engineers,\nsome mistakes and simplifications for one engineer can become costly\nfor many. For instance it's particularly important to\navoid polluting the global namespace: name collisions across a\ncodebase of hundreds of millions of lines are difficult to work with\nand hard to avoid if everyone puts things into the global\nnamespace.</dd>\n\n<dt>Concede to optimization when necessary</dt>\n<dd>Performance optimizations can sometimes be necessary and\nappropriate, even when they conflict with the other principles of this\ndocument.</dd>\n</dl>\n\n<p>The intent of this document is to provide maximal guidance with\nreasonable restriction. As always, common sense and good taste should\nprevail. By this we specifically refer to the established conventions\nof the entire Google C++ community, not just your personal preferences\nor those of your team. Be skeptical about and reluctant to use\nclever or unusual constructs: the absence of a prohibition is not the\nsame as a license to proceed.  Use your judgment, and if you are\nunsure, please don't hesitate to ask your project leads to get additional\ninput.</p>\n\n\n\n<h2 id=\"C++_Version\">C++ Version</h2>\n\n<p>Currently, code should target C++20, i.e., should not use C++23\n  features. The C++ version targeted by this guide will advance\n  (aggressively) over time.</p>\n\n\n\n<p>Do not use\n  <a href=\"#Nonstandard_Extensions\">non-standard extensions</a>.</p>\n\n<div>\n<p>Consider portability to other environments before using features\nfrom C++17 and C++20 in your project.</p>\n</div>\n\n<h2 id=\"Header_Files\">Header Files</h2>\n\n<p>In general, every <code>.cc</code> file should have an\nassociated <code>.h</code> file. There are some common\nexceptions, such as unit tests and small <code>.cc</code> files containing\njust a <code>main()</code> function.</p>\n\n<p>Correct use of header files can make a huge difference to\nthe readability, size and performance of your code.</p>\n\n<p>The following rules will guide you through the various\npitfalls of using header files.</p>\n\n<a id=\"The_-inl.h_Files\"></a>\n<h3 id=\"Self_contained_Headers\">Self-contained Headers</h3>\n\n<p>Header files should be self-contained (compile on their own) and\nend in <code>.h</code>.  Non-header files that are meant for inclusion\nshould end in <code>.inc</code> and be used sparingly.</p>\n\n<p>All header files should be self-contained. Users and refactoring\ntools should not have to adhere to special conditions to include the\nheader. Specifically, a header should\nhave <a href=\"#The__define_Guard\">header guards</a> and include all\nother headers it needs.</p>\n\n<p>When a header declares inline functions or templates that clients of the\nheader will instantiate, the inline functions and templates must also have\ndefinitions in the header, either directly or in files it includes.  Do not move\nthese definitions to separately included header (<code>-inl.h</code>) files;\nthis practice was common in the past, but is no longer allowed.  When all\ninstantiations of a template occur in one <code>.cc</code> file, either because\nthey're <a href=\"https://en.cppreference.com/w/cpp/language/class_template#Explicit_instantiation\">\nexplicit</a> or because the definition is accessible to only\nthe <code>.cc</code> file, the template definition can be kept in that file.</p>\n\n<p>There are rare cases where a file designed to be included is not\nself-contained.  These are typically intended to be included at unusual\nlocations, such as the middle of another file.  They might not\nuse <a href=\"#The__define_Guard\">header guards</a>, and might not include\ntheir prerequisites.  Name such files with the <code>.inc</code>\nextension.  Use sparingly, and prefer self-contained headers when\npossible.</p>\n\n<h3 id=\"The__define_Guard\">The #define Guard</h3>\n\n<p>All header files should have <code>#define</code> guards to\nprevent multiple inclusion. The format of the symbol name\nshould be\n\n<code><i>&lt;PROJECT&gt;</i>_<i>&lt;PATH&gt;</i>_<i>&lt;FILE&gt;</i>_H_</code>.</p>\n\n\n\n<div>\n<p>To guarantee uniqueness, they should\nbe based on the full path in a project's source tree. For\nexample, the file <code>foo/src/bar/baz.h</code> in\nproject <code>foo</code> should have the following\nguard:</p>\n</div>\n\n<pre class=\"goodcode\">#ifndef FOO_BAR_BAZ_H_\n#define FOO_BAR_BAZ_H_\n\n...\n\n#endif  // FOO_BAR_BAZ_H_\n</pre>\n\n\n\n<h3 id=\"Include_What_You_Use\">Include What You Use</h3>\n\n<p>If a source or header file refers to a symbol defined elsewhere,\nthe file should directly include a header file which properly intends\nto provide a declaration or definition of that symbol. It should not\ninclude header files for any other reason.\n</p>\n\n<p>Do not rely on transitive inclusions. This allows people to remove\nno-longer-needed <code>#include</code> statements from their headers without\nbreaking clients. This also applies to related headers\n- <code>foo.cc</code> should include <code>bar.h</code> if it uses a\nsymbol from it even if <code>foo.h</code>\nincludes <code>bar.h</code>.</p>\n\n<h3 id=\"Forward_Declarations\">Forward Declarations</h3>\n\n<p>Avoid using forward declarations where possible.\n  Instead, <a href=\"#Include_What_You_Use\">include the headers you need</a>.\n</p>\n\n\n<p class=\"definition\"></p>\n<p>A \"forward declaration\" is a declaration of an entity\n  without an associated definition.</p>\n<pre class=\"neutralcode\">// In a C++ source file:\nclass B;\nvoid FuncInB();\nextern int variable_in_b;\nABSL_DECLARE_FLAG(flag_in_b);\n</pre>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Forward declarations can save compile time, as\n  <code>#include</code>s force the compiler to open\n  more files and process more input.</li>\n\n  <li>Forward declarations can save on unnecessary\n  recompilation. <code>#include</code>s can force\n  your code to be recompiled more often, due to unrelated\n  changes in the header.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>Forward declarations can hide a dependency, allowing\n  user code to skip necessary recompilation when headers\n  change.</li>\n\n  <li>A forward declaration as opposed to an <code>#include</code> statement\n    makes it difficult for automatic tooling to discover the module\n    defining the symbol.</li>\n\n  <li>A forward declaration may be broken by subsequent\n  changes to the library. Forward declarations of functions\n  and templates can prevent the header owners from making\n  otherwise-compatible changes to their APIs, such as\n  widening a parameter type, adding a template parameter\n  with a default value, or migrating to a new namespace.</li>\n\n  <li>Forward declaring symbols from namespace\n  <code>std::</code> yields undefined behavior.</li>\n\n  <li>It can be difficult to determine whether a forward\n  declaration or a full <code>#include</code> is needed.\n  Replacing an <code>#include</code> with a forward\n  declaration can silently change the meaning of\n  code:\n<pre class=\"neutralcode\">// b.h:\nstruct B {};\nstruct D : B {};\n\n// good_user.cc:\n#include \"b.h\"\nvoid f(B*);\nvoid f(void*);\nvoid test(D* x) { f(x); }  // Calls f(B*)\n</pre>\n  If the <code>#include</code> was replaced with forward\n  decls for <code>B</code> and <code>D</code>,\n  <code>test()</code> would call <code>f(void*)</code>.\n  </li>\n\n  <li>Forward declaring multiple symbols from a header\n  can be more verbose than simply\n  <code>#include</code>ing the header.</li>\n\n  <li>Structuring code to enable forward declarations\n  (e.g., using pointer members instead of object members)\n  can make the code slower and more complex.</li>\n\n\n</ul>\n\n<p class=\"decision\"></p>\n<p>Try to avoid forward declarations of entities\ndefined in another project.</p>\n\n<a id=\"Inline_Functions\"></a>\n<h3 id=\"Defining_Functions_in_Header_Files\">Defining Functions in Header Files</h3>\n\n<p>Include the definition of a function at its point of declaration in a header file only\nwhen the definition is short. If the definition otherwise has a reason be in the header,\nput it in an internal part of the file. If necessary to make the definition ODR-safe, mark\nit with an <code>inline</code> specifier.</p>\n\n<p class=\"definition\"></p>\n<p>Functions defined in header files are sometimes referred to as \"inline functions\",\nwhich is a somewhat overloaded term that refers to several distinct but overlapping\nsituations:</p>\n\n<ol>\n  <li>A <em>textually inline</em> symbol's definition is exposed to the reader at\n  the point of declaration.</li>\n  <li>A function or variable defined in a header file is <em>expandable inline</em>\n  since its definition is available for\n  <a href=\"https://en.wikipedia.org/wiki/Inline_expansion\">inline expansion</a>\n  by the compiler, which can lead to more efficient object code.</li>\n  <li><em>ODR-safe</em> entities do not violate the\n  <a href=\"https://en.cppreference.com/w/cpp/language/definition\">\"One Definition Rule\"</a>,\n  which often requires the <a href=\"https://en.cppreference.com/w/cpp/language/inline\">inline</a>\n  keyword for things defined in header files\n  .</li>\n</ol>\n\n<p>While functions tend to be a more common source of confusion, these definitions apply to\nvariables as well, and so do the rules here.</p>\n\n<p class=\"pros\"></p>\n\n<ul>\n<li>Defining a function textually in-line reduces boilerplate code for simple functions\nlike accessors and mutators.</li>\n\n<li> As noted above, function definitions in header files <i>can</i> lead to\nmore efficient object code for small functions due to inline expansion by the\ncompiler.</li>\n\n<li>Function templates and <code>constexpr</code> functions generally need to\nbe defined in the header file that declares them (but not necessarily the public part).</li>\n</ul>\n\n<p class=\"cons\"></p>\n\n<ul>\n<li>Embedding a function definition in the public API makes the API harder to skim,\nand incurs cognitive overhead for readers of that API- the more complex the function\nthe higher the cost.</li>\n\n<li>Public definitions expose implementation details that are at best harmless and\noften extraneous.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Only define a function at its public declaration if it is short, say, 10 lines or fewer. Put\nlonger function bodies in the <code>.cc</code> file unless they must be in the header for\nperformance or technical reasons.</p>\n\n<p>Even if a definition must be in the header, this is not a sufficient reason to put it within\nthe public part. Instead, the definition can be in an internal part of the header, such as the\n<a href=\"#Access_Control\">private</a> section of a class, within a namespace that includes the word\n<code>internal</code>, or below a comment like <code>// Implementation details only\nbelow here</code>.</p>\n\n<p>Once a definition is in a header file, it must be ODR-safe by having the <code>inline</code>\nspecifier or being implicitly specified inline by being a function template or defined in a class\nbody when first declared.</p>\n\n<pre class=\"goodcode\">template &lt;typename T&gt;\nclass Foo {\n public:\n  int bar() { return bar_; }\n\n  void MethodWithHugeBody();\n\n private:\n  int bar_;\n};\n\n// Implementation details only below here\n\ntemplate &lt;typename T&gt;\nvoid Foo&lt;T&gt;::MethodWithHugeBody() {\n  ...\n}\n</pre>\n\n<h3 id=\"Names_and_Order_of_Includes\">Names and Order of Includes</h3>\n\n<p>Include headers in the following order: Related header, C system headers,\nC++ standard library headers,\nother libraries' headers, your project's\nheaders.</p>\n\n<p>\nAll of a project's header files should be\nlisted as descendants of the project's source\ndirectory without use of UNIX directory aliases\n<code>.</code> (the current directory) or <code>..</code>\n(the parent directory). For example,\n\n<code>google-awesome-project/src/base/logging.h</code>\nshould be included as:</p>\n\n<pre class=\"goodcode\">#include \"base/logging.h\"\n</pre>\n\n<p>Headers should only be included using an angle-bracketed path if the library\nrequires you to do so. In particular, the following headers require angle\nbrackets:</p>\n\n<ul>\n<li>C and C++ standard library headers (e.g., <code>&lt;stdlib.h&gt;</code>\n  and <code>&lt;string&gt;</code>).</li>\n<li>POSIX, Linux, and Windows system headers (e.g., <code>&lt;unistd.h&gt;</code>\n  and <code>&lt;windows.h&gt;</code>).</li>\n<li>In rare cases, third_party libraries (e.g., <code>&lt;Python.h&gt;</code>).</li>\n</ul>\n\n<p>In <code><var>dir/foo</var>.cc</code> or\n<code><var>dir/foo_test</var>.cc</code>, whose main\npurpose is to implement or test the stuff in\n<code><var>dir2/foo2</var>.h</code>, order your includes\nas follows:</p>\n\n<ol>\n  <li><code><var>dir2/foo2</var>.h</code>.</li>\n\n  <li>A blank line</li>\n\n  <li>C system headers, and any other headers in angle brackets with the\n    <code>.h</code> extension, e.g., <code>&lt;unistd.h&gt;</code>,\n    <code>&lt;stdlib.h&gt;</code>, <code>&lt;Python.h&gt;</code>.</li>\n\n  <li>A blank line</li>\n\n  <li>C++ standard library headers (without file extension), e.g.,\n    <code>&lt;algorithm&gt;</code>, <code>&lt;cstddef&gt;</code>.</li>\n\n  <li>A blank line</li>\n\n  <div>\n  <li>Other libraries' <code>.h</code> files.</li>\n\n  <li>A blank line</li>\n  </div>\n\n  <li>\n  Your project's <code>.h</code>\n  files.</li>\n</ol>\n\n<p>Separate each non-empty group with one blank line.</p>\n\n<p>With the preferred ordering, if the related header\n<code><var>dir2/foo2</var>.h</code> omits any necessary\nincludes, the build of <code><var>dir/foo</var>.cc</code>\nor <code><var>dir/foo</var>_test.cc</code> will break.\nThus, this rule ensures that build breaks show up first\nfor the people working on these files, not for innocent\npeople in other packages.</p>\n\n<p><code><var>dir/foo</var>.cc</code> and\n<code><var>dir2/foo2</var>.h</code> are usually in the same\ndirectory (e.g., <code>base/basictypes_test.cc</code> and\n<code>base/basictypes.h</code>), but may sometimes be in different\ndirectories too.</p>\n\n\n\n<p>Note that the C headers such as <code>stddef.h</code>\nare essentially interchangeable with their C++ counterparts\n(<code>cstddef</code>).\nEither style is acceptable, but prefer consistency with existing code.</p>\n\n<p>Within each section the includes should be ordered\nalphabetically. Note that older code might not conform to\nthis rule and should be fixed when convenient.</p>\n\n<p>For example, the includes in\n\n<code>google-awesome-project/src/foo/internal/fooserver.cc</code>\nmight look like this:</p>\n\n<pre class=\"goodcode\">#include \"foo/server/fooserver.h\"\n\n#include &lt;sys/types.h&gt;\n#include &lt;unistd.h&gt;\n\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\n#include \"base/basictypes.h\"\n#include \"foo/server/bar.h\"\n#include \"third_party/absl/flags/flag.h\"\n</pre>\n\n<p><b>Exception:</b></p>\n\n<p>Sometimes, system-specific code needs\nconditional includes. Such code can put conditional\nincludes after other includes. Of course, keep your\nsystem-specific code small and localized. Example:</p>\n\n<pre class=\"goodcode\">#include \"foo/public/fooserver.h\"\n\n#ifdef _WIN32\n#include &lt;windows.h&gt;\n#endif  // _WIN32\n</pre>\n\n<h2 id=\"Scoping\">Scoping</h2>\n\n<h3 id=\"Namespaces\">Namespaces</h3>\n\n<p>With few exceptions, place code in a namespace. Namespaces\nshould have unique names based on the project name, and possibly\nits path. Do not use <i>using-directives</i> (e.g.,\n<code>using namespace foo</code>). Do not use\ninline namespaces. For unnamed namespaces, see\n<a href=\"#Internal_Linkage\">Internal Linkage</a>.\n\n</p><p class=\"definition\"></p>\n<p>Namespaces subdivide the global scope\ninto distinct, named scopes, and so are useful for preventing\nname collisions in the global scope.</p>\n\n<p class=\"pros\"></p>\n\n<p>Namespaces provide a method for preventing name conflicts\nin large programs while allowing most code to use reasonably\nshort names.</p>\n\n<p>For example, if two different projects have a class\n<code>Foo</code> in the global scope, these symbols may\ncollide at compile time or at runtime. If each project\nplaces their code in a namespace, <code>project1::Foo</code>\nand <code>project2::Foo</code> are now distinct symbols that\ndo not collide, and code within each project's namespace\ncan continue to refer to <code>Foo</code> without the prefix.</p>\n\n<p>Inline namespaces automatically place their names in\nthe enclosing scope. Consider the following snippet, for\nexample:</p>\n\n<pre class=\"neutralcode\">namespace outer {\ninline namespace inner {\n  void foo();\n}  // namespace inner\n}  // namespace outer\n</pre>\n\n<p>The expressions <code>outer::inner::foo()</code> and\n<code>outer::foo()</code> are interchangeable. Inline\nnamespaces are primarily intended for ABI compatibility\nacross versions.</p>\n\n<p class=\"cons\"></p>\n\n<p>Namespaces can be confusing, because they complicate\nthe mechanics of figuring out what definition a name refers\nto.</p>\n\n<p>Inline namespaces, in particular, can be confusing\nbecause names aren't actually restricted to the namespace\nwhere they are declared. They are only useful as part of\nsome larger versioning policy.</p>\n\n<p>In some contexts, it's necessary to repeatedly refer to\nsymbols by their fully-qualified names. For deeply-nested\nnamespaces, this can add a lot of clutter.</p>\n\n<p class=\"decision\"></p>\n\n<p>Namespaces should be used as follows:</p>\n\n<ul>\n  <li>Follow the rules on <a href=\"#Namespace_Names\">Namespace Names</a>.\n  </li><li>Terminate multi-line namespaces with comments as shown in the given examples.\n  </li><li>\n\n  <p>Namespaces wrap the entire source file after\n  includes,\n  <a href=\"https://gflags.github.io/gflags/\">\n  gflags</a> definitions/declarations\n  and forward declarations of classes from other namespaces.</p>\n\n<pre class=\"goodcode\">// In the .h file\nnamespace mynamespace {\n\n// All declarations are within the namespace scope.\n// Notice the lack of indentation.\nclass MyClass {\n public:\n  ...\n  void Foo();\n};\n\n}  // namespace mynamespace\n</pre>\n\n<pre class=\"goodcode\">// In the .cc file\nnamespace mynamespace {\n\n// Definition of functions is within scope of the namespace.\nvoid MyClass::Foo() {\n  ...\n}\n\n}  // namespace mynamespace\n</pre>\n\n  <p>More complex <code>.cc</code> files might have additional details,\n  like flags or using-declarations.</p>\n\n<pre class=\"goodcode\">#include \"a.h\"\n\nABSL_FLAG(bool, someflag, false, \"a flag\");\n\nnamespace mynamespace {\n\nusing ::foo::Bar;\n\n...code for mynamespace...    // Code goes against the left margin.\n\n}  // namespace mynamespace\n</pre>\n  </li>\n\n  <li>To place generated protocol\n  message code in a namespace, use the\n  <code>package</code> specifier in the\n  <code>.proto</code> file. See\n\n\n  <a href=\"https://protobuf.dev/reference/cpp/cpp-generated/#package\">\n  Protocol Buffer Packages</a>\n  for details.</li>\n\n  <li>Do not declare anything in namespace\n  <code>std</code>, including forward declarations of\n  standard library classes. Declaring entities in\n  namespace <code>std</code> is undefined behavior, i.e.,\n  not portable. To declare entities from the standard\n  library, include the appropriate header file.</li>\n\n  <li><p>You may not use a <i>using-directive</i>\n  to make all names from a namespace available.</p>\n\n<pre class=\"badcode\">// Forbidden -- This pollutes the namespace.\nusing namespace foo;\n</pre>\n  </li>\n\n  <li><p>Do not use <i>Namespace aliases</i> at namespace scope\n  in header files except in explicitly marked\n  internal-only namespaces, because anything imported into a namespace\n  in a header file becomes part of the public API exported by that file.\n  Namespace aliases can be used when those conditions don't apply, but\n  they must have <a href=\"#Naming_Aliases\">appropriate names</a>.</p>\n\n<pre class=\"goodcode\">// In a .h file, an alias must not be a separate API, or must be hidden in an\n// implementation detail.\nnamespace librarian {\n\nnamespace internal {  // Internal, not part of the API.\nnamespace sidetable = ::pipeline_diagnostics::sidetable;\n}  // namespace internal\n\ninline void my_inline_function() {\n  // Local to a function.\n  namespace baz = ::foo::bar::baz;\n  ...\n}\n\n}  // namespace librarian\n</pre>\n\n<pre class=\"goodcode\">// Remove uninteresting parts of some commonly used names in .cc files.\nnamespace sidetable = ::pipeline_diagnostics::sidetable;\n</pre>\n\n  </li><li>Do not use inline namespaces.</li>\n\n  <li><p>Use namespaces with \"internal\" in the name to document parts of an API that\n    should not be mentioned by users of the API.\n    </p>\n\n<pre class=\"badcode\">// We shouldn't use this internal name in non-absl code.\nusing ::absl::container_internal::ImplementationDetail;\n</pre>\n\n    <p>Note that there is still a risk of collision between libraries within a\n    nested <code>internal</code> namespace, so give each library within a\n    namespace a unique internal namespace by adding the library's\n    filename. For example, <code>gshoe/widget.h</code> would use\n    <code>gshoe::internal_widget</code> as opposed to just\n    <code>gshoe::internal</code>.</p>\n  </li>\n\n  <li><p>Single-line nested namespace declarations\n\n    are preferred in new code, but are not required.</p>\n<pre class=\"goodcode\">namespace my_project::my_component {\n\n  ...\n\n}  // namespace my_project::my_component\n</pre>\n  </li>\n</ul>\n\n<a id=\"Unnamed_Namespaces_and_Static_Variables\"></a>\n<h3 id=\"Internal_Linkage\">Internal Linkage</h3>\n\n<p>When definitions in a <code>.cc</code> file do not need to be\nreferenced outside that file, give them internal linkage by placing\nthem in an unnamed namespace or declaring them <code>static</code>.\nDo not use either of these constructs in <code>.h</code> files.\n\n</p><p class=\"definition\"></p>\n<p>All declarations can be given internal linkage by placing them in unnamed\nnamespaces. Functions and variables can also be given internal linkage by\ndeclaring them <code>static</code>. This means that anything you're declaring\ncan't be accessed from another file. If a different file declares something with\nthe same name, then the two entities are completely independent.</p>\n\n<p class=\"decision\"></p>\n\n<p>Use of internal linkage in <code>.cc</code> files is encouraged\nfor all code that does not need to be referenced elsewhere.\nDo not use internal linkage in <code>.h</code> files.</p>\n\n<p>Format unnamed namespaces like named namespaces. In the\n  terminating comment, leave the namespace name empty:</p>\n\n<pre class=\"goodcode\">namespace {\n...\n}  // namespace\n</pre>\n\n<h3 id=\"Nonmember,_Static_Member,_and_Global_Functions\">Nonmember, Static Member, and Global Functions</h3>\n\n<p>Prefer placing nonmember functions in a namespace; use completely global\nfunctions rarely. Do not use a class simply to group static members. Static\nmethods of a class should generally be closely related to instances of the\nclass or the class's static data.</p>\n\n\n<p class=\"pros\"></p>\n<p>Nonmember and static member functions can be useful in\nsome situations. Putting nonmember functions in a\nnamespace avoids polluting the global namespace.</p>\n\n<p class=\"cons\"></p>\n<p>Nonmember and static member functions may make more sense\nas members of a new class, especially if they access\nexternal resources or have significant dependencies.</p>\n\n<p class=\"decision\"></p>\n<p>Sometimes it is useful to define a\nfunction not bound to a class instance. Such a function\ncan be either a static member or a nonmember function.\nNonmember functions should not depend on external\nvariables, and should nearly always exist in a namespace.\nDo not create classes only to group static members;\nthis is no different than just giving the names a\ncommon prefix, and such grouping is usually unnecessary anyway.</p>\n\n<p>If you define a nonmember function and it is only\nneeded in its <code>.cc</code> file, use\n<a href=\"#Internal_Linkage\">internal linkage</a> to limit\nits scope.</p>\n\n<h3 id=\"Local_Variables\">Local Variables</h3>\n\n<p>Place a function's variables in the narrowest scope\npossible, and initialize variables in the declaration.</p>\n\n<p>C++ allows you to declare variables anywhere in a function.\nWe encourage you to declare them in a scope as local as\npossible, and as close to the first use as possible.\nThis makes it easier for the reader to find the\ndeclaration and see what type the variable is and what it\nwas initialized to. In particular, initialization should\nbe used instead of declaration and assignment, e.g.,:</p>\n\n<pre class=\"badcode\">int i;\ni = f();      // Bad -- initialization separate from declaration.\n</pre>\n\n<pre class=\"goodcode\">int i = f();  // Good -- declaration has initialization.\n</pre>\n\n\n<pre class=\"badcode\">int jobs = NumJobs();\n// More code...\nf(jobs);      // Bad -- declaration separate from use.\n</pre>\n\n<pre class=\"goodcode\">int jobs = NumJobs();\nf(jobs);      // Good -- declaration immediately (or closely) followed by use.\n</pre>\n\n<pre class=\"badcode\">std::vector&lt;int&gt; v;\nv.push_back(1);  // Prefer initializing using brace initialization.\nv.push_back(2);\n</pre>\n\n<pre class=\"goodcode\">std::vector&lt;int&gt; v = {1, 2};  // Good -- v starts initialized.\n</pre>\n\n<p>Variables needed for <code>if</code>, <code>while</code>\nand <code>for</code> statements should normally be declared\nwithin those statements, so that such variables are confined\nto those scopes. For example:</p>\n\n<pre class=\"goodcode\">while (const char* p = strchr(str, '/')) str = p + 1;\n</pre>\n\n<p>There is one caveat: if the variable is an object, its\nconstructor is invoked every time it enters scope and is\ncreated, and its destructor is invoked every time it goes\nout of scope.</p>\n\n<pre class=\"badcode\">// Inefficient implementation:\nfor (int i = 0; i &lt; 1000000; ++i) {\n  Foo f;  // My ctor and dtor get called 1000000 times each.\n  f.DoSomething(i);\n}\n</pre>\n\n<p>It may be more efficient to declare such a variable\nused in a loop outside that loop:</p>\n\n<pre class=\"goodcode\">Foo f;  // My ctor and dtor get called once each.\nfor (int i = 0; i &lt; 1000000; ++i) {\n  f.DoSomething(i);\n}\n</pre>\n\n<h3 id=\"Static_and_Global_Variables\">Static and Global Variables</h3>\n\n<p>Objects with\n<a href=\"http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration\">\nstatic storage duration</a> are forbidden unless they are\n<a href=\"http://en.cppreference.com/w/cpp/types/is_destructible\">trivially\ndestructible</a>. Informally this means that the destructor does not do\nanything, even taking member and base destructors into account. More formally it\nmeans that the type has no user-defined or virtual destructor and that all bases\nand non-static members are trivially destructible.\nStatic function-local variables may use dynamic initialization.\nUse of dynamic initialization for static class member variables or variables at\nnamespace scope is discouraged, but allowed in limited circumstances; see below\nfor details.</p>\n\n<p>As a rule of thumb: a global variable satisfies these requirements if its\ndeclaration, considered in isolation, could be <code>constexpr</code>.</p>\n\n<p class=\"definition\"></p>\n<p>Every object has a <dfn>storage duration</dfn>, which correlates with its\nlifetime. Objects with static storage duration live from the point of their\ninitialization until the end of the program. Such objects appear as variables at\nnamespace scope (\"global variables\"), as static data members of classes, or as\nfunction-local variables that are declared with the <code>static</code>\nspecifier. Function-local static variables are initialized when control first\npasses through their declaration; all other objects with static storage duration\nare initialized as part of program start-up. All objects with static storage\nduration are destroyed at program exit (which happens before unjoined threads\nare terminated).</p>\n\n<p>Initialization may be <dfn>dynamic</dfn>, which means that something\nnon-trivial happens during initialization. (For example, consider a constructor\nthat allocates memory, or a variable that is initialized with the current\nprocess ID.) The other kind of initialization is <dfn>static</dfn>\ninitialization. The two aren't quite opposites, though: static\ninitialization <em>always</em> happens to objects with static storage duration\n(initializing the object either to a given constant or to a representation\nconsisting of all bytes set to zero), whereas dynamic initialization happens\nafter that, if required.</p>\n\n<p class=\"pros\"></p>\n<p>Global and static variables are very useful for a large number of\napplications: named constants, auxiliary data structures internal to some\ntranslation unit, command-line flags, logging, registration mechanisms,\nbackground infrastructure, etc.</p>\n\n<p class=\"cons\"></p>\n<p>Global and static variables that use dynamic initialization or have\nnon-trivial destructors create complexity that can easily lead to hard-to-find\nbugs. Dynamic initialization is not ordered across translation units, and\nneither is destruction (except that destruction\nhappens in reverse order of initialization). When one initialization refers to\nanother variable with static storage duration, it is possible that this causes\nan object to be accessed before its lifetime has begun (or after its lifetime\nhas ended). Moreover, when a program starts threads that are not joined at exit,\nthose threads may attempt to access objects after their lifetime has ended if\ntheir destructor has already run.</p>\n\n<p class=\"decision\"></p>\n<h4>Decision on destruction</h4>\n\n<p>When destructors are trivial, their execution is not subject to ordering at\nall (they are effectively not \"run\"); otherwise we are exposed to the risk of\naccessing objects after the end of their lifetime. Therefore, we only allow\nobjects with static storage duration if they are trivially destructible.\nFundamental types (like pointers and <code>int</code>) are trivially\ndestructible, as are arrays of trivially destructible types. Note that\nvariables marked with <code>constexpr</code> are trivially destructible.</p>\n<pre class=\"goodcode\">const int kNum = 10;  // Allowed\n\nstruct X { int n; };\nconst X kX[] = {{1}, {2}, {3}};  // Allowed\n\nvoid foo() {\n  static const char* const kMessages[] = {\"hello\", \"world\"};  // Allowed\n}\n\n// Allowed: constexpr guarantees trivial destructor.\nconstexpr std::array&lt;int, 3&gt; kArray = {1, 2, 3};</pre>\n<pre class=\"badcode\">// bad: non-trivial destructor\nconst std::string kFoo = \"foo\";\n\n// Bad for the same reason, even though kBar is a reference (the\n// rule also applies to lifetime-extended temporary objects).\nconst std::string&amp; kBar = StrCat(\"a\", \"b\", \"c\");\n\nvoid bar() {\n  // Bad: non-trivial destructor.\n  static std::map&lt;int, int&gt; kData = {{1, 0}, {2, 0}, {3, 0}};\n}</pre>\n\n<p>Note that references are not objects, and thus they are not subject to the\nconstraints on destructibility. The constraint on dynamic initialization still\napplies, though. In particular, a function-local static reference of the form\n<code>static T&amp; t = *new T;</code> is allowed.</p>\n\n<h4>Decision on initialization</h4>\n\n<p>Initialization is a more complex topic. This is because we must not only\nconsider whether class constructors execute, but we must also consider the\nevaluation of the initializer:</p>\n<pre class=\"neutralcode\">int n = 5;    // Fine\nint m = f();  // ? (Depends on f)\nFoo x;        // ? (Depends on Foo::Foo)\nBar y = g();  // ? (Depends on g and on Bar::Bar)\n</pre>\n\n<p>All but the first statement expose us to indeterminate initialization\nordering.</p>\n\n<p>The concept we are looking for is called <em>constant initialization</em> in\nthe formal language of the C++ standard. It means that the initializing\nexpression is a constant expression, and if the object is initialized by a\nconstructor call, then the constructor must be specified as\n<code>constexpr</code>, too:</p>\n<pre class=\"goodcode\">struct Foo { constexpr Foo(int) {} };\n\nint n = 5;  // Fine, 5 is a constant expression.\nFoo x(2);   // Fine, 2 is a constant expression and the chosen constructor is constexpr.\nFoo a[] = { Foo(1), Foo(2), Foo(3) };  // Fine</pre>\n\n<p>Constant initialization is always allowed. Constant initialization of\nstatic storage duration variables should be marked with <code>constexpr</code>\nor <code>constinit</code>.\nAny non-local static storage\nduration variable that is not so marked should be presumed to have\ndynamic initialization, and reviewed very carefully.</p>\n\n<p>By contrast, the following initializations are problematic:</p>\n\n<pre class=\"badcode\">// Some declarations used below.\ntime_t time(time_t*);      // Not constexpr!\nint f();                   // Not constexpr!\nstruct Bar { Bar() {} };\n\n// Problematic initializations.\ntime_t m = time(nullptr);  // Initializing expression not a constant expression.\nFoo y(f());                // Ditto\nBar b;                     // Chosen constructor Bar::Bar() not constexpr.</pre>\n\n<p>Dynamic initialization of nonlocal variables is discouraged, and in general\nit is forbidden. However, we do permit it if no aspect of the program depends\non the sequencing of this initialization with respect to all other\ninitializations. Under those restrictions, the ordering of the initialization\ndoes not make an observable difference. For example:</p>\n<pre class=\"goodcode\">int p = getpid();  // Allowed, as long as no other static variable\n                   // uses p in its own initialization.</pre>\n\n<p>Dynamic initialization of static local variables is allowed (and common).</p>\n\n\n\n<h4>Common patterns</h4>\n\n<ul>\n  <li>Global strings: if you require a named global or static string constant,\n    consider using a <code>constexpr</code> variable of\n    <code>string_view</code>, character array, or character pointer, pointing\n    to a string literal. String literals have static storage duration already\n    and are usually sufficient.\n    See <a href=\"https://abseil.io/tips/140\">TotW #140</a>.</li>\n  <li>Maps, sets, and other dynamic containers: if you require a static, fixed\n    collection, such as a set to search against or a lookup table, you cannot\n    use the dynamic containers from the standard library as a static variable,\n    since they have non-trivial destructors. Instead, consider\n\n\n    a simple array of trivial types, e.g., an array of arrays of ints (for a \"map from int to\n    int\"), or an array of pairs (e.g., pairs of <code>int</code> and <code>const\n    char*</code>). For small collections, linear search is entirely sufficient\n    (and efficient, due to memory locality); consider using the facilities from\n    <a href=\"https://github.com/abseil/abseil-cpp/blob/master/absl/algorithm/container.h\">absl/algorithm/container.h</a>\n    for the standard operations. If necessary, keep the collection in sorted\n    order and use a binary search algorithm.\n\n    If you do really prefer a dynamic container from the standard library, consider using\n    a function-local static pointer, as described below\n    .</li>\n  <li>Smart pointers (<code>std::unique_ptr</code>, <code>std::shared_ptr</code>): smart\n    pointers execute cleanup during destruction and are therefore forbidden.\n    Consider whether your use case fits into one of the other patterns described\n    in this section. One simple solution is to use a plain pointer to a\n    dynamically allocated object and never delete it (see last item).</li>\n  <li>Static variables of custom types: if you require static, constant data of\n    a type that you need to define yourself, give the type a trivial destructor\n    and a <code>constexpr</code> constructor.</li>\n  <li>If all else fails, you can create an object dynamically and never delete\n    it by using a function-local static pointer or reference (e.g.,\n    <code>static const auto&amp; impl = *new T(args...);</code>).</li>\n</ul>\n\n<h3 id=\"thread_local\">thread_local Variables</h3>\n\n<p><code>thread_local</code> variables that aren't declared inside a function\nmust be initialized with a true compile-time constant,\nand this must be enforced by using the\n<a href=\"https://en.cppreference.com/w/cpp/language/constinit\">\n  <code>constinit</code></a>\nattribute. Prefer\n<code>thread_local</code> over other ways of defining thread-local data.</p>\n\n<p class=\"definition\"></p>\n<p>Variables can be declared with the\n<code>thread_local</code> specifier:</p>\n<pre class=\"neutralcode\">thread_local Foo foo = ...;\n</pre>\n<p>Such a variable is actually a collection of objects, so that when different\nthreads access it, they are actually accessing different objects.\n<code>thread_local</code> variables are much like\n<a href=\"#Static_and_Global_Variables\">static storage duration variables</a>\nin many respects. For instance, they can be declared at namespace scope,\ninside functions, or as static class members, but not as ordinary class\nmembers.</p>\n\n<p><code>thread_local</code> variable instances are initialized much like\nstatic variables, except that they must be initialized separately for each\nthread, rather than once at program startup. This means that\n<code>thread_local</code> variables declared within a function are safe, but\nother <code>thread_local</code> variables are subject to the same\ninitialization-order issues as static variables (and more besides).</p>\n\n<p><code>thread_local</code> variables have a subtle destruction-order issue:\nduring thread shutdown, <code>thread_local</code> variables will be destroyed\nin the opposite order of their initialization (as is generally true in C++).\nIf code triggered by the destructor of any <code>thread_local</code> variable\nrefers to any already-destroyed <code>thread_local</code> on that thread, we will\nget a particularly hard to diagnose use-after-free.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Thread-local data is inherently safe from races (because only one thread\n    can ordinarily access it), which makes <code>thread_local</code> useful for\n    concurrent programming.</li>\n  <li><code>thread_local</code> is the only standard-supported way of creating\n    thread-local data.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>Accessing a <code>thread_local</code> variable may trigger execution of\n    an unpredictable and uncontrollable amount of other code during thread-start or\n    first use on a given thread.</li>\n  <li><code>thread_local</code> variables are effectively global variables,\n    and have all the drawbacks of global variables other than lack of\n    thread-safety.</li>\n  <li>The memory consumed by a <code>thread_local</code> variable scales with\n    the number of running threads (in the worst case), which can be quite large\n    in a  program.</li>\n  <li>Data members cannot be <code>thread_local</code> unless they are also\n    <code>static</code>.</li>\n  <li>We may suffer from use-after-free bugs if <code>thread_local</code> variables\n    have complex destructors. In particular, the destructor of any such variable must not\n    call any code (transitively) that refers to any potentially-destroyed\n    <code>thread_local</code>. This property is hard to enforce.</li>\n\n  <li>Approaches for avoiding use-after-free in global/static contexts do not work for\n    <code>thread_local</code>s. Specifically, skipping destructors for globals and static\n    variables is allowable because their lifetimes end at program shutdown. Thus, any \"leak\"\n    is managed immediately by the OS cleaning up our memory and other resources. By\n    contrast, skipping destructors for <code>thread_local</code> variables leads to resource\n    leaks proportional to the total number of threads that terminate during the lifetime of\n    the program.</li>\n\n</ul>\n\n<p class=\"decision\"></p>\n  <p><code>thread_local</code> variables at class or namespace scope must be\n  initialized with a true compile-time constant (i.e., they must have no\n  dynamic initialization). To enforce this, <code>thread_local</code> variables\n  at class or namespace scope must be annotated with\n  <a href=\"https://en.cppreference.com/w/cpp/language/constinit\">\n    <code>constinit</code></a>\n  (or <code>constexpr</code>, but that should be rare):</p>\n\n  <pre class=\"goodcode\">   constinit thread_local Foo foo = ...;\n  </pre>\n\n  <p><code>thread_local</code> variables inside a function have no initialization\n    concerns, but still risk use-after-free during thread exit. Note that you can use\n    a function-scope <code>thread_local</code> to simulate a class- or\n    namespace-scope <code>thread_local</code> by defining a function or\n    static method that exposes it:</p>\n\n<pre class=\"goodcode\">Foo&amp; MyThreadLocalFoo() {\n  thread_local Foo result = ComplicatedInitialization();\n  return result;\n}\n</pre>\n\n  <p>Note that <code>thread_local</code> variables will be destroyed whenever a thread exits.\n    If the destructor of any such variable refers to any other (potentially-destroyed)\n    <code>thread_local</code> we will suffer from hard to diagnose use-after-free bugs.\n    Prefer trivial types, or types that provably run no user-provided code at destruction to\n    minimize the potential of accessing any other <code>thread_local</code>.\n  </p>\n\n<p><code>thread_local</code> should be preferred over other mechanisms for\ndefining thread-local data.</p>\n\n<h2 id=\"Classes\">Classes</h2>\n\n<p>Classes are the fundamental unit of code in C++. Naturally,\nwe use them extensively. This section lists the main dos and\ndon'ts you should follow when writing a class.</p>\n\n<h3 id=\"Doing_Work_in_Constructors\">Doing Work in Constructors</h3>\n\n<p>Avoid virtual method calls in constructors, and avoid\ninitialization that can fail if you can't signal an error.</p>\n\n<p class=\"definition\"></p>\n<p>It is possible to perform arbitrary initialization in the body\nof the constructor.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>No need to worry about whether the class has been initialized or\n  not.</li>\n\n  <li>Objects that are fully initialized by constructor call can\n  be <code>const</code> and may also be easier to use with standard containers\n  or algorithms.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>If the work calls virtual functions, these calls\n  will not get dispatched to the subclass\n  implementations. Future modification to your class can\n  quietly introduce this problem even if your class is\n  not currently subclassed, causing much confusion.</li>\n\n  <li>There is no easy way for constructors to signal errors, short of\n  crashing the program (not always appropriate) or using exceptions\n  (which are <a href=\"#Exceptions\">forbidden</a>).</li>\n\n  <li>If the work fails, we now have an object whose initialization\n  code failed, so it may be an unusual state requiring a <code>bool\n  IsValid()</code> state checking mechanism (or similar) which is easy\n  to forget to call.</li>\n\n  <li>You cannot take the address of a constructor, so whatever work\n  is done in the constructor cannot easily be handed off to, for\n  example, another thread.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Constructors should never call virtual functions. If appropriate\nfor your code ,\nterminating the program may be an appropriate error handling\nresponse. Otherwise, consider a factory function\nor <code>Init()</code> method as described in\n<a href=\"https://abseil.io/tips/42\">TotW #42</a>\n.\nAvoid <code>Init()</code> methods on objects with\nno other states that affect which public methods may be called\n(semi-constructed objects of this form are particularly hard to work\nwith correctly).</p>\n\n<a id=\"Explicit_Constructors\"></a>\n<h3 id=\"Implicit_Conversions\">Implicit Conversions</h3>\n\n<p>Do not define implicit conversions. Use the <code>explicit</code>\nkeyword for conversion operators and single-argument\nconstructors.</p>\n\n<p class=\"definition\"></p>\n<p>Implicit conversions allow an\nobject of one type (called the <dfn>source type</dfn>) to\nbe used where a different type (called the <dfn>destination\ntype</dfn>) is expected, such as when passing an\n<code>int</code> argument to a function that takes a\n<code>double</code> parameter.</p>\n\n<p>In addition to the implicit conversions defined by the language,\nusers can define their own, by adding appropriate members to the\nclass definition of the source or destination type. An implicit\nconversion in the source type is defined by a type conversion operator\nnamed after the destination type (e.g., <code>operator\nbool()</code>). An implicit conversion in the destination\ntype is defined by a constructor that can take the source type as\nits only argument (or only argument with no default value).</p>\n\n<p>The <code>explicit</code> keyword can be applied to a constructor\nor a conversion operator, to ensure that it can only be\nused when the destination type is explicit at the point of use,\ne.g., with a cast. This applies not only to implicit conversions, but to\nlist initialization syntax:</p>\n<pre class=\"neutralcode\">class Foo {\n  explicit Foo(int x, double y);\n  ...\n};\n\nvoid Func(Foo f);\n</pre>\n<pre class=\"badcode\">Func({42, 3.14});  // Error\n</pre>\n<p>This kind of code isn't technically an implicit conversion, but the\nlanguage treats it as one as far as <code>explicit</code> is concerned.</p>\n\n<p class=\"pros\"></p>\n<ul>\n<li>Implicit conversions can make a type more usable and\n    expressive by eliminating the need to explicitly name a type\n    when it's obvious.</li>\n<li>Implicit conversions can be a simpler alternative to\n    overloading, such as when a single\n    function with a <code>string_view</code> parameter takes the\n    place of separate overloads for <code>std::string</code> and\n    <code>const char*</code>.</li>\n<li>List initialization syntax is a concise and expressive\n    way of initializing objects.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n<li>Implicit conversions can hide type-mismatch bugs, where the\n    destination type does not match the user's expectation, or\n    the user is unaware that any conversion will take place.</li>\n\n<li>Implicit conversions can make code harder to read, particularly\n    in the presence of overloading, by making it less obvious what\n    code is actually getting called.</li>\n\n<li>Constructors that take a single argument may accidentally\n    be usable as implicit type conversions, even if they are not\n    intended to do so.</li>\n\n<li>When a single-argument constructor is not marked\n    <code>explicit</code>, there's no reliable way to tell whether\n    it's intended to define an implicit conversion, or the author\n    simply forgot to mark it.</li>\n\n<li>Implicit conversions can lead to call-site ambiguities, especially\n    when there are bidirectional implicit conversions. This can be caused\n    either by having two types that both provide an implicit conversion,\n    or by a single type that has both an implicit constructor and an\n    implicit type conversion operator.</li>\n\n<li>List initialization can suffer from the same problems if\n    the destination type is implicit, particularly if the\n    list has only a single element.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Type conversion operators, and constructors that are\ncallable with a single argument, must be marked\n<code>explicit</code> in the class definition. As an\nexception, copy and move constructors should not be\n<code>explicit</code>, since they do not perform type\nconversion.</p>\n\n<p>Implicit conversions can sometimes be necessary and appropriate for\ntypes that are designed to be interchangeable, for example when objects\nof two types are just different representations of the same underlying\nvalue. In that case, contact\nyour project leads to request a waiver\nof this rule.\n</p>\n\n<p>Constructors that cannot be called with a single argument\nmay omit <code>explicit</code>. Constructors that\ntake a single <code>std::initializer_list</code> parameter should\nalso omit <code>explicit</code>, in order to support copy-initialization\n(e.g., <code>MyType m = {1, 2};</code>).</p>\n\n<h3 id=\"Copyable_Movable_Types\">Copyable and Movable Types</h3>\n<a id=\"Copy_Constructors\"></a>\n\n<p>A class's public API must make clear whether the class is copyable,\nmove-only, or neither copyable nor movable. Support copying and/or\nmoving if these operations are clear and meaningful for your type.</p>\n\n<p class=\"definition\"></p>\n<p>A movable type is one that can be initialized and assigned\nfrom temporaries.</p>\n\n<p>A copyable type is one that can be initialized or assigned from\nany other object of the same type (so is also movable by definition), with the\nstipulation that the value of the source does not change.\n<code>std::unique_ptr&lt;int&gt;</code> is an example of a movable but not\ncopyable type (since the value of the source\n<code>std::unique_ptr&lt;int&gt;</code> must be modified during assignment to\nthe destination). <code>int</code> and <code>std::string</code> are examples of\nmovable types that are also copyable. (For <code>int</code>, the move and copy\noperations are the same; for <code>std::string</code>, there exists a move operation\nthat is less expensive than a copy.)</p>\n\n<p>For user-defined types, the copy behavior is defined by the copy\nconstructor and the copy-assignment operator. Move behavior is defined by the\nmove constructor and the move-assignment operator, if they exist, or by the\ncopy constructor and the copy-assignment operator otherwise.</p>\n\n<p>The copy/move constructors can be implicitly invoked by the compiler\nin some situations, e.g., when passing objects by value.</p>\n\n<p class=\"pros\"></p>\n<p>Objects of copyable and movable types can be passed and returned by value,\nwhich makes APIs simpler, safer, and more general. Unlike when passing objects\nby pointer or reference, there's no risk of confusion over ownership,\nlifetime, mutability, and similar issues, and no need to specify them in the\ncontract. It also prevents non-local interactions between the client and the\nimplementation, which makes them easier to understand, maintain, and optimize by\nthe compiler. Further, such objects can be used with generic APIs that\nrequire pass-by-value, such as most containers, and they allow for additional\nflexibility in e.g., type composition.</p>\n\n<p>Copy/move constructors and assignment operators are usually\neasier to define correctly than alternatives\nlike <code>Clone()</code>, <code>CopyFrom()</code> or <code>Swap()</code>,\nbecause they can be generated by the compiler, either implicitly or\nwith <code>= default</code>.  They are concise, and ensure\nthat all data members are copied. Copy and move\nconstructors are also generally more efficient, because they don't\nrequire heap allocation or separate initialization and assignment\nsteps, and they're eligible for optimizations such as\n\n<a href=\"http://en.cppreference.com/w/cpp/language/copy_elision\">\ncopy elision</a>.</p>\n\n<p>Move operations allow the implicit and efficient transfer of\nresources out of rvalue objects. This allows a plainer coding style\nin some cases.</p>\n\n<p class=\"cons\"></p>\n<p>Some types do not need to be copyable, and providing copy\noperations for such types can be confusing, nonsensical, or outright\nincorrect. Types representing singleton objects (<code>Registerer</code>),\nobjects tied to a specific scope (<code>Cleanup</code>), or closely coupled to\nobject identity (<code>Mutex</code>) cannot be copied meaningfully.\nCopy operations for base class types that are to be used\npolymorphically are hazardous, because use of them can lead to\n<a href=\"https://en.wikipedia.org/wiki/Object_slicing\">object slicing</a>.\nDefaulted or carelessly-implemented copy operations can be incorrect, and the\nresulting bugs can be confusing and difficult to diagnose.</p>\n\n<p>Copy constructors are invoked implicitly, which makes the\ninvocation easy to miss. This may cause confusion for programmers used to\nlanguages where pass-by-reference is conventional or mandatory. It may also\nencourage excessive copying, which can cause performance problems.</p>\n\n<p class=\"decision\"></p>\n\n<p>Every class's public interface must make clear which copy and move\noperations the class supports. This should usually take the form of explicitly\ndeclaring and/or deleting the appropriate operations in the <code>public</code>\nsection of the declaration.</p>\n\n<p>Specifically, a copyable class should explicitly declare the copy\noperations, a move-only class should explicitly declare the move operations, and\na non-copyable/movable class should explicitly delete the copy operations. A\ncopyable class may also declare move operations in order to support efficient\nmoves. Explicitly declaring or deleting all four copy/move operations is\npermitted, but not required. If you provide a copy or move assignment operator,\nyou must also provide the corresponding constructor.</p>\n\n<pre class=\"goodcode\">class Copyable {\n public:\n  Copyable(const Copyable&amp; other) = default;\n  Copyable&amp; operator=(const Copyable&amp; other) = default;\n\n  // The implicit move operations are suppressed by the declarations above.\n  // You may explicitly declare move operations to support efficient moves.\n};\n\nclass MoveOnly {\n public:\n  MoveOnly(MoveOnly&amp;&amp; other) = default;\n  MoveOnly&amp; operator=(MoveOnly&amp;&amp; other) = default;\n\n  // The copy operations are implicitly deleted, but you can\n  // spell that out explicitly if you want:\n  MoveOnly(const MoveOnly&amp;) = delete;\n  MoveOnly&amp; operator=(const MoveOnly&amp;) = delete;\n};\n\nclass NotCopyableOrMovable {\n public:\n  // Not copyable or movable\n  NotCopyableOrMovable(const NotCopyableOrMovable&amp;) = delete;\n  NotCopyableOrMovable&amp; operator=(const NotCopyableOrMovable&amp;)\n      = delete;\n\n  // The move operations are implicitly disabled, but you can\n  // spell that out explicitly if you want:\n  NotCopyableOrMovable(NotCopyableOrMovable&amp;&amp;) = delete;\n  NotCopyableOrMovable&amp; operator=(NotCopyableOrMovable&amp;&amp;)\n      = delete;\n};\n</pre>\n\n<p>These declarations/deletions can be omitted only if they are obvious:</p>\n<ul>\n<li>If the class has no <code>private</code> section, like a\n    <a href=\"#Structs_vs._Classes\">struct</a> or an interface-only base class,\n    then the copyability/movability can be determined by the\n    copyability/movability of any public data members.\n</li><li>If a base class clearly isn't copyable or movable, derived classes\n    naturally won't be either.  An interface-only base class that leaves these\n    operations implicit is not sufficient to make concrete subclasses clear.\n</li><li>Note that if you explicitly declare or delete either the constructor or\n    assignment operation for copy, the other copy operation is not obvious and\n    must be declared or deleted.  Likewise for move operations.\n</li></ul>\n\n<p>A type should not be copyable/movable if the meaning of\ncopying/moving is unclear to a casual user, or if it incurs unexpected\ncosts. Move operations for copyable types are strictly a performance\noptimization and are a potential source of bugs and complexity, so\navoid defining them unless they are significantly more efficient than\nthe corresponding copy operations.  If your type provides copy operations, it is\nrecommended that you design your class so that the default implementation of\nthose operations is correct. Remember to review the correctness of any\ndefaulted operations as you would any other code.</p>\n\n<p>To eliminate the risk of slicing, prefer to make base classes abstract,\nby making their constructors protected, by declaring their destructors protected,\nor by giving them one or more pure virtual member functions. Prefer to avoid\nderiving from concrete classes.</p>\n\n<h3 id=\"Structs_vs._Classes\">Structs vs. Classes</h3>\n\n<p>Use a <code>struct</code> only for passive objects that\n      carry data; everything else is a <code>class</code>.</p>\n\n<p>The <code>struct</code> and <code>class</code>\nkeywords behave almost identically in C++. We add our own\nsemantic meanings to each keyword, so you should use the\nappropriate keyword for the data-type you're\ndefining.</p>\n\n<p><code>structs</code> should be used for passive objects that carry\ndata, and may have associated constants. All fields must be public. The\nstruct type itself must not have invariants that imply relationships between\ndifferent fields, since direct user access to those fields may\nbreak those invariants, but users of a struct may have requirements and\nguarantees on particular uses of it. Constructors, destructors, and helper\nmethods may be present; however, these methods must not require or enforce\nany invariants.</p>\n\n<p>If more functionality or invariants are required, or struct has wide visibility and expected to\nevolve, then a <code>class</code> is more appropriate. If in doubt, make it a <code>class</code>.\n</p>\n\n<p>For consistency with STL, you can use\n<code>struct</code> instead of <code>class</code> for\nstateless types, such as traits,\n<a href=\"#Template_metaprogramming\">template metafunctions</a>,\nand some functors.</p>\n\n<p>Note that member variables in structs and classes have\n<a href=\"#Variable_Names\">different naming rules</a>.</p>\n\n<h3 id=\"Structs_vs._Tuples\">Structs vs. Pairs and Tuples</h3>\n\n<p>Prefer to use a <code>struct</code> instead of a pair or a\ntuple whenever the elements can have meaningful names.</p>\n\n<p>\n  While using pairs and tuples can avoid the need to define a custom type,\n  potentially saving work when <em>writing</em> code, a meaningful field\n  name will almost always be much clearer when <em>reading</em> code than\n  <code>.first</code>, <code>.second</code>, or <code>std::get&lt;X&gt;</code>.\n  While C++14's introduction of <code>std::get&lt;Type&gt;</code> to access a\n  tuple element by type rather than index (when the type is unique) can\n  sometimes partially mitigate this, a field name is usually substantially\n  clearer and more informative than a type.\n</p>\n\n<p>\n  Pairs and tuples may be appropriate in generic code where there are not\n  specific meanings for the elements of the pair or tuple. Their use may\n  also be required in order to interoperate with existing code or APIs.\n</p>\n\n<a id=\"Multiple_Inheritance\"></a>\n<h3 id=\"Inheritance\">Inheritance</h3>\n\n<p>Composition is often more appropriate than inheritance.\nWhen using inheritance, make it <code>public</code>.</p>\n\n<p class=\"definition\"></p>\n<p> When a sub-class\ninherits from a base class, it includes the definitions\nof all the data and operations that the base class\ndefines. \"Interface inheritance\" is inheritance from a\npure abstract base class (one with no state or defined\nmethods); all other inheritance is \"implementation\ninheritance\".</p>\n\n<p class=\"pros\"></p>\n<p>Implementation inheritance reduces code size by re-using\nthe base class code as it specializes an existing type.\nBecause inheritance is a compile-time declaration, you\nand the compiler can understand the operation and detect\nerrors. Interface inheritance can be used to\nprogrammatically enforce that a class expose a particular\nAPI. Again, the compiler can detect errors, in this case,\nwhen a class does not define a necessary method of the\nAPI.</p>\n\n<p class=\"cons\"></p>\n<p>For implementation inheritance, because the code\nimplementing a sub-class is spread between the base and\nthe sub-class, it can be more difficult to understand an\nimplementation. The sub-class cannot override functions\nthat are not virtual, so the sub-class cannot change\nimplementation.</p>\n\n<p>Multiple inheritance is especially problematic, because\nit often imposes a higher performance overhead (in fact,\nthe performance drop from single inheritance to multiple\ninheritance can often be greater than the performance\ndrop from ordinary to virtual dispatch), and because\nit risks leading to \"diamond\" inheritance patterns,\nwhich are prone to ambiguity, confusion, and outright bugs.</p>\n\n<p class=\"decision\"></p>\n\n<p>All inheritance should be <code>public</code>. If you\nwant to do private inheritance, you should be including\nan instance of the base class as a member instead. You may use\n<code>final</code> on classes when you don't intend to support using\nthem as base classes.</p>\n\n<p>Do not overuse implementation inheritance. Composition\nis often more appropriate. Try to restrict use of\ninheritance to the \"is-a\" case: <code>Bar</code>\nsubclasses <code>Foo</code> if it can reasonably be said\nthat <code>Bar</code> \"is a kind of\"\n<code>Foo</code>.</p>\n\n<p>Limit the use of <code>protected</code> to those\nmember functions that might need to be accessed from\nsubclasses. Note that <a href=\"#Access_Control\">data\nmembers should be <code>private</code></a>.</p>\n\n<p>Explicitly annotate overrides of virtual functions or virtual\ndestructors with exactly one of an <code>override</code> or (less\nfrequently) <code>final</code> specifier. Do not\nuse <code>virtual</code> when declaring an override.\nRationale: A function or destructor marked\n<code>override</code> or <code>final</code> that is\nnot an override of a base class virtual function will\nnot compile, and this helps catch common errors. The\nspecifiers serve as documentation; if no specifier is\npresent, the reader has to check all ancestors of the\nclass in question to determine if the function or\ndestructor is virtual or not.</p>\n\n<p>Multiple inheritance is permitted, but multiple <em>implementation</em>\ninheritance is strongly discouraged.</p>\n\n<h3 id=\"Operator_Overloading\">Operator Overloading</h3>\n\n<p>Overload operators judiciously. Do not use user-defined literals.</p>\n\n<p class=\"definition\"></p>\n<p>C++ permits user code to\n<a href=\"http://en.cppreference.com/w/cpp/language/operators\">declare\noverloaded versions of the built-in operators</a> using the\n<code>operator</code> keyword, so long as one of the parameters\nis a user-defined type. The <code>operator</code> keyword also\npermits user code to define new kinds of literals using\n<code>operator\"\"</code>, and to define type-conversion functions\nsuch as <code>operator bool()</code>.</p>\n\n<p class=\"pros\"></p>\n<p>Operator overloading can make code more concise and\nintuitive by enabling user-defined types to behave the same\nas built-in types. Overloaded operators are the idiomatic names\nfor certain operations (e.g., <code>==</code>, <code>&lt;</code>,\n<code>=</code>, and <code>&lt;&lt;</code>), and adhering to\nthose conventions can make user-defined types more readable\nand enable them to interoperate with libraries that expect\nthose names.</p>\n\n<p>User-defined literals are a very concise notation for\ncreating objects of user-defined types.</p>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>Providing a correct, consistent, and unsurprising\n  set of operator overloads requires some care, and failure\n  to do so can lead to confusion and bugs.</li>\n\n  <li>Overuse of operators can lead to obfuscated code,\n  particularly if the overloaded operator's semantics\n  don't follow convention.</li>\n\n  <li>The hazards of function overloading apply just as\n  much to operator overloading, if not more so.</li>\n\n  <li>Operator overloads can fool our intuition into\n  thinking that expensive operations are cheap, built-in\n  operations.</li>\n\n  <li>Finding the call sites for overloaded operators may\n  require a search tool that's aware of C++ syntax, rather\n  than, e.g., grep.</li>\n\n  <li>If you get the argument type of an overloaded operator\n  wrong, you may get a different overload rather than a\n  compiler error. For example, <code>foo &lt; bar</code>\n  may do one thing, while <code>&amp;foo &lt; &amp;bar</code>\n  does something totally different.</li>\n\n  <li>Certain operator overloads are inherently hazardous.\n  Overloading unary <code>&amp;</code> can cause the same\n  code to have different meanings depending on whether\n  the overload declaration is visible. Overloads of\n  <code>&amp;&amp;</code>, <code>||</code>, and <code>,</code>\n  (comma) cannot match the evaluation-order semantics of the\n  built-in operators.</li>\n\n  <li>Operators are often defined outside the class,\n  so there's a risk of different files introducing\n  different definitions of the same operator. If both\n  definitions are linked into the same binary, this results\n  in undefined behavior, which can manifest as subtle\n  run-time bugs.</li>\n\n  <li>User-defined literals (UDLs) allow the creation of new\n  syntactic forms that are unfamiliar even to experienced C++\n  programmers, such as <code>\"Hello World\"sv</code> as a\n  shorthand for <code>std::string_view(\"Hello World\")</code>.\n  Existing notations are clearer, though less terse.</li>\n\n  <li>Because they can't be namespace-qualified, uses of UDLs also require\n  use of either using-directives (which <a href=\"#Namespaces\">we ban</a>) or\n  using-declarations (which <a href=\"#Aliases\">we ban in header files</a> except\n  when the imported names are part of the interface exposed by the header\n  file in question).  Given that header files would have to avoid UDL\n  suffixes, we prefer to avoid having conventions for literals differ\n  between header files and source files.\n  </li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Define overloaded operators only if their meaning is\nobvious, unsurprising, and consistent with the corresponding\nbuilt-in operators. For example, use <code>|</code> as a\nbitwise- or logical-or, not as a shell-style pipe.</p>\n\n<p>Define operators only on your own types. More precisely,\ndefine them in the same headers, <code>.cc</code> files, and namespaces\nas the types they operate on. That way, the operators are available\nwherever the type is, minimizing the risk of multiple\ndefinitions. If possible, avoid defining operators as templates,\nbecause they must satisfy this rule for any possible template\narguments. If you define an operator, also define\nany related operators that make sense, and make sure they\nare defined consistently.</p>\n\n<p>Prefer to define non-modifying binary operators as\nnon-member functions. If a binary operator is defined as a\nclass member, implicit conversions will apply to the\nright-hand argument, but not the left-hand one. It will\nconfuse your users if <code>a + b</code> compiles but\n<code>b + a</code> doesn't.</p>\n\n<p>For a type <code>T</code> whose values can be compared for\nequality, define a non-member <code>operator==</code> and document when\ntwo values of type <code>T</code> are considered equal.\nIf there is a single obvious notion of when a value <code>t1</code>\nof type <code>T</code> is less than another such value <code>t2</code> then\nyou may also define <code>operator&lt;=&gt;</code>, which should be\nconsistent with <code>operator==</code>.\nPrefer not to overload the other comparison and ordering operators.</p>\n\n<p>Don't go out of your way to avoid defining operator\noverloads. For example, prefer to define <code>==</code>,\n<code>=</code>, and <code>&lt;&lt;</code>, rather than\n<code>Equals()</code>, <code>CopyFrom()</code>, and\n<code>PrintTo()</code>. Conversely, don't define\noperator overloads just because other libraries expect\nthem. For example, if your type doesn't have a natural\nordering, but you want to store it in a <code>std::set</code>,\nuse a custom comparator rather than overloading\n<code>&lt;</code>.</p>\n\n<p>Do not overload <code>&amp;&amp;</code>, <code>||</code>,\n<code>,</code> (comma), or unary <code>&amp;</code>. Do not overload\n<code>operator\"\"</code>, i.e., do not introduce user-defined\nliterals.  Do not use any such literals provided by others\n(including the standard library).</p>\n\n<p>Type conversion operators are covered in the section on\n<a href=\"#Implicit_Conversions\">implicit conversions</a>.\nThe <code>=</code> operator is covered in the section on\n<a href=\"#Copy_Constructors\">copy constructors</a>. Overloading\n<code>&lt;&lt;</code> for use with streams is covered in the\nsection on <a href=\"#Streams\">streams</a>. See also the rules on\n<a href=\"#Function_Overloading\">function overloading</a>, which\napply to operator overloading as well.</p>\n\n<h3 id=\"Access_Control\">Access Control</h3>\n\n<p>Make classes' data members <code>private</code>, unless they are\n<a href=\"#Constant_Names\">constants</a>. This simplifies reasoning about invariants, at the cost\nof some easy boilerplate in the form of accessors (usually <code>const</code>) if necessary.</p>\n\n<p>For technical\nreasons, we allow data members of a test fixture class defined in a <code>.cc</code> file to\nbe <code>protected</code> when using\n\n\n<a href=\"https://github.com/google/googletest\">Google\nTest</a>.\nIf a test fixture class is defined outside of the <code>.cc</code> file it is used in, for example\nin a <code>.h</code> file, make data members <code>private</code>.</p>\n\n<h3 id=\"Declaration_Order\">Declaration Order</h3>\n\n<p>Group similar declarations together, placing <code>public</code> parts\nearlier.</p>\n\n<p>A class definition should usually start with a\n<code>public:</code> section, followed by\n<code>protected:</code>, then <code>private:</code>.  Omit\nsections that would be empty.</p>\n\n<p>Within each section, prefer grouping similar\nkinds of declarations together, and prefer the\nfollowing order:</p>\n\n<ol>\n  <li>Types and type aliases (<code>typedef</code>, <code>using</code>,\n    <code>enum</code>, nested structs and classes, and <code>friend</code> types)</li>\n\n  <li>(Optionally, for structs only) non-<code>static</code> data members</li>\n\n  <li>Static constants</li>\n\n  <li>Factory functions</li>\n\n  <li>Constructors and assignment operators</li>\n\n  <li>Destructor</li>\n\n  <li>\n    All other functions (<code>static</code> and non-<code>static</code> member\n    functions, and <code>friend</code> functions)\n  </li>\n\n  <li>All other data members (static and non-static)</li>\n</ol>\n\n<p>Do not put large method definitions inline in the\nclass definition. Usually, only trivial or\nperformance-critical, and very short, methods may be\ndefined inline. See <a href=\"#Defining_Functions_in_Header_Files\">Defining\nFunctions in Header Files</a> for more details.</p>\n\n<h2 id=\"Functions\">Functions</h2>\n\n<a id=\"Function_Parameter_Ordering\"></a>\n<a id=\"Output_Parameters\"></a>\n<h3 id=\"Inputs_and_Outputs\">Inputs and Outputs</h3>\n\n<p>The output of a C++ function is naturally provided via\na return value and sometimes via output parameters (or in/out parameters).</p>\n\n<p>Prefer using return values over output parameters:\nthey improve readability, and often provide the same or better performance.\nSee\n<a href=\"https://abseil.io/tips/176\">TotW #176</a>.</p>\n\n<p>Prefer to return by value or, failing that, return by reference.\nAvoid returning a raw pointer unless it can be null.</p>\n\n<p>Parameters are either inputs to the function, outputs from the\nfunction, or both. Non-optional input parameters should usually be values\nor <code>const</code> references, while non-optional output and\ninput/output parameters should usually be references (which cannot be null).\nGenerally, use <code>std::optional</code> to represent optional by-value\ninputs, and use a <code>const</code> pointer when the non-optional form would\nhave used a reference. Use non-<code>const</code> pointers to represent\noptional outputs and optional input/output parameters.</p>\n\n\n\n<p>\nAvoid defining functions that require a reference parameter to outlive the call.\nIn some cases reference parameters can bind to temporaries, leading to lifetime\nbugs. Instead, find a way to eliminate the lifetime requirement\n(for example, by copying the parameter), or pass retained parameters by\npointer and document the lifetime and non-null requirements.\nSee <a href=\"https://abseil.io/tips/116\">TotW 116</a> for more.</p>\n\n<p>When ordering function parameters, put all input-only\nparameters before any output parameters. In particular,\ndo not add new parameters to the end of the function just\nbecause they are new; place new input-only parameters before\nthe output parameters. This is not a hard-and-fast rule. Parameters that\nare both input and output muddy the waters, and, as always,\nconsistency with related functions may require you to bend the rule.\nVariadic functions may also require unusual parameter ordering.</p>\n\n<h3 id=\"Write_Short_Functions\">Write Short Functions</h3>\n\n<p>Prefer small and focused functions.</p>\n\n<p>We recognize that long functions are sometimes\nappropriate, so no hard limit is placed on functions\nlength. If a function exceeds about 40 lines, think about\nwhether it can be broken up without harming the structure\nof the program.</p>\n\n<p>Even if your long function works perfectly now,\nsomeone modifying it in a few months may add new\nbehavior. This could result in bugs that are hard to\nfind. Keeping your functions short and simple makes it\neasier for other people to read and modify your code.\nSmall functions are also easier to test.</p>\n\n<p>You could find long and complicated functions when\nworking with\nsome code. Do not be\nintimidated by modifying existing code: if working with\nsuch a function proves to be difficult, you find that\nerrors are hard to debug, or you want to use a piece of\nit in several different contexts, consider breaking up\nthe function into smaller and more manageable pieces.</p>\n\n<h3 id=\"Function_Overloading\">Function Overloading</h3>\n\n<p>Use overloaded functions (including constructors) only if a\nreader looking at a call site can get a good idea of what\nis happening without having to first figure out exactly\nwhich overload is being called.</p>\n\n<p class=\"definition\"></p>\n<p>You may write a function that takes a <code>const\nstd::string&amp;</code> and overload it with another that\ntakes <code>const char*</code>. However, in this case consider\n<code>std::string_view\n</code>\ninstead.</p>\n\n<pre class=\"neutralcode\">class MyClass {\n public:\n  void Analyze(const std::string&amp; text);\n  void Analyze(const char* text, size_t textlen);\n};\n</pre>\n\n<p class=\"pros\"></p>\n<p>Overloading can make code more intuitive by allowing an\nidentically-named function to take different arguments.\nIt may be necessary for templatized code, and it can be\nconvenient for Visitors.</p>\n<p>Overloading based on <code>const</code> or ref qualification\nmay make utility code more usable, more efficient, or both.\nSee <a href=\"https://abseil.io/tips/148\">TotW #148</a> for more.</p>\n\n<p class=\"cons\"></p>\n<p>If a function is overloaded by the argument types alone,\na reader may have to understand C++'s complex matching\nrules in order to tell what's going on. Also many people\nare confused by the semantics of inheritance if a derived\nclass overrides only some of the variants of a\nfunction.</p>\n\n<p class=\"decision\"></p>\n<p>You may overload a function when there are no semantic differences\nbetween variants. These overloads may vary in types, qualifiers, or\nargument count. However, a reader of such a call must not need to know\nwhich member of the overload set is chosen, only that <b>something</b>\nfrom the set is being called.</p>\n\n<p>To reflect this unified design, prefer a single, comprehensive \"umbrella\"\ncomment that documents the entire overload set and is placed before the first\ndeclaration.</p>\n\n<p>Where a reader might have difficulty connecting the umbrella\ncomment to a specific overload, it's okay to have a comment for specific overloads.</p>\n\n<h3 id=\"Default_Arguments\">Default Arguments</h3>\n\n<p>Default arguments are allowed on non-virtual functions\nwhen the default is guaranteed to always have the same\nvalue. Follow the same restrictions as for <a href=\"#Function_Overloading\">function overloading</a>, and\nprefer overloaded functions if the readability gained with\ndefault arguments doesn't outweigh the downsides below.</p>\n\n<p class=\"pros\"></p>\n<p>Often you have a function that uses default values, but\noccasionally you want to override the defaults. Default\nparameters allow an easy way to do this without having to\ndefine many functions for the rare exceptions. Compared\nto overloading the function, default arguments have a\ncleaner syntax, with less boilerplate and a clearer\ndistinction between 'required' and 'optional'\narguments.</p>\n\n<p class=\"cons\"></p>\n<p>Defaulted arguments are another way to achieve the\nsemantics of overloaded functions, so all the <a href=\"#Function_Overloading\">reasons not to overload\nfunctions</a> apply.</p>\n\n<p>The defaults for arguments in a virtual function call are\ndetermined by the static type of the target object, and\nthere's no guarantee that all overrides of a given function\ndeclare the same defaults.</p>\n\n<p>Default parameters are re-evaluated at each call site,\nwhich can bloat the generated code. Readers may also expect\nthe default's value to be fixed at the declaration instead\nof varying at each call.</p>\n\n<p>Function pointers are confusing in the presence of\ndefault arguments, since the function signature often\ndoesn't match the call signature. Adding\nfunction overloads avoids these problems.</p>\n\n<p class=\"decision\"></p>\n<p>Default arguments are banned on virtual functions, where\nthey don't work properly, and in cases where the specified\ndefault might not evaluate to the same value depending on\nwhen it was evaluated. (For example, don't write <code>void\nf(int n = counter++);</code>.)</p>\n\n<p>In some other cases, default arguments can improve the\nreadability of their function declarations enough to\novercome the downsides above, so they are allowed. When in\ndoubt, use overloads.</p>\n\n<h3 id=\"trailing_return\">Trailing Return Type Syntax</h3>\n\n<p>Use trailing return types only where using the ordinary syntax (leading\n  return types) is impractical or much less readable.</p>\n\n<p class=\"definition\"></p>\n<p>C++ allows two different forms of function declarations. In the older\n  form, the return type appears before the function name. For example:</p>\n<pre class=\"neutralcode\">int Foo(int x);\n</pre>\n<p>The newer form uses the <code>auto</code>\n  keyword before the function name and a trailing return type after\n  the argument list. For example, the declaration above could\n  equivalently be written:</p>\n<pre class=\"neutralcode\">auto Foo(int x) -&gt; int;\n</pre>\n<p>The trailing return type is in the function's scope. This doesn't\n  make a difference for a simple case like <code>int</code> but it matters\n  for more complicated cases, like types declared in class scope or\n  types written in terms of the function parameters.</p>\n\n<p class=\"pros\"></p>\n<p>Trailing return types are the only way to explicitly specify the\n  return type of a <a href=\"#Lambda_expressions\">lambda expression</a>.\n  In some cases the compiler is able to deduce a lambda's return type,\n  but not in all cases. Even when the compiler can deduce it automatically,\n  sometimes specifying it explicitly would be clearer for readers.\n</p>\n<p>Sometimes it's easier and more readable to specify a return type\n  after the function's parameter list has already appeared. This is\n  particularly true when the return type depends on template parameters.\n  For example:</p>\n  <pre class=\"neutralcode\">    template &lt;typename T, typename U&gt;\n    auto Add(T t, U u) -&gt; decltype(t + u);\n  </pre>\n  versus\n  <pre class=\"neutralcode\">    template &lt;typename T, typename U&gt;\n    decltype(declval&lt;T&amp;&gt;() + declval&lt;U&amp;&gt;()) Add(T t, U u);\n  </pre>\n\n<p class=\"cons\"></p>\n<p>Trailing return type syntax has no analogue in C++-like languages\n  such as C and Java, so some readers may find it unfamiliar.</p>\n<p>Existing codebases have an enormous number of function\n  declarations that aren't going to get changed to use the new syntax,\n  so the realistic choices are using the old syntax only or using a mixture\n  of the two. Using a single version is better for uniformity of style.</p>\n\n<p class=\"decision\"></p>\n<p>In most cases, continue to use the older style of function\n  declaration where the return type goes before the function name.\n  Use the new trailing-return-type form only in cases where it's\n  required (such as lambdas) or where, by putting the type after the\n  function's parameter list, it allows you to write the type in a much\n  more readable way. The latter case should be rare; it's mostly an\n  issue in fairly complicated template code, which is\n  <a href=\"#Template_metaprogramming\">discouraged in most cases</a>.</p>\n\n\n<h2 id=\"Google-Specific_Magic\">Google-Specific Magic</h2>\n\n\n\n<div>\n<p>There are various tricks and utilities that\nwe use to make C++ code more robust, and various ways we use\nC++ that may differ from what you see elsewhere.</p>\n</div>\n\n\n\n<h3 id=\"Ownership_and_Smart_Pointers\">Ownership and Smart Pointers</h3>\n\n<p>Prefer to have single, fixed owners for dynamically\nallocated objects. Prefer to transfer ownership with smart\npointers.</p>\n\n<p class=\"definition\"></p>\n<p>\"Ownership\" is a bookkeeping technique for managing\ndynamically allocated memory (and other resources). The\nowner of a dynamically allocated object is an object or\nfunction that is responsible for ensuring that it is\ndeleted when no longer needed. Ownership can sometimes be\nshared, in which case the last owner is typically\nresponsible for deleting it. Even when ownership is not\nshared, it can be transferred from one piece of code to\nanother.</p>\n\n<p>\"Smart\" pointers are classes that act like pointers,\ne.g., by overloading the <code>*</code> and\n<code>-&gt;</code> operators. Some smart pointer types\ncan be used to automate ownership bookkeeping, to ensure\nthese responsibilities are met.\n<a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\">\n<code>std::unique_ptr</code></a> is a smart pointer type\nwhich expresses exclusive ownership\nof a dynamically allocated object; the object is deleted\nwhen the <code>std::unique_ptr</code> goes out of scope.\nIt cannot be copied, but can be <em>moved</em> to\nrepresent ownership transfer.\n<a href=\"http://en.cppreference.com/w/cpp/memory/shared_ptr\">\n<code>std::shared_ptr</code></a> is a smart pointer type\nthat expresses shared ownership of\na dynamically allocated object. <code>std::shared_ptr</code>s\ncan be copied; ownership of the object is shared among\nall copies, and the object is deleted when the last\n<code>std::shared_ptr</code> is destroyed. </p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>It's virtually impossible to manage dynamically\n  allocated memory without some sort of ownership\n  logic.</li>\n\n  <li>Transferring ownership of an object can be cheaper\n  than copying it (if copying it is even possible).</li>\n\n  <li>Transferring ownership can be simpler than\n  'borrowing' a pointer or reference, because it reduces\n  the need to coordinate the lifetime of the object\n  between the two users.</li>\n\n  <li>Smart pointers can improve readability by making\n  ownership logic explicit, self-documenting, and\n  unambiguous.</li>\n\n  <li>Smart pointers can eliminate manual ownership\n  bookkeeping, simplifying the code and ruling out large\n  classes of errors.</li>\n\n  <li>For <code>const</code> objects, shared ownership can be a simple\n  and efficient alternative to deep copying.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>Ownership must be represented and transferred via\n  pointers (whether smart or plain). Pointer semantics\n  are more complicated than value semantics, especially\n  in APIs: you have to worry not just about ownership,\n  but also aliasing, lifetime, and mutability, among\n  other issues.</li>\n\n  <li>The performance costs of value semantics are often\n  overestimated, so the performance benefits of ownership\n  transfer might not justify the readability and\n  complexity costs.</li>\n\n  <li>APIs that transfer ownership force their clients\n  into a single memory management model.</li>\n\n  <li>Code using smart pointers is less explicit about\n  where the resource releases take place.</li>\n\n  <li><code>std::unique_ptr</code> expresses ownership\n  transfer using move semantics, which can be complex and\n  may confuse some programmers.</li>\n\n  <li>Shared ownership can be a tempting alternative to\n  careful ownership design, obfuscating the design of a\n  system.</li>\n\n  <li>Shared ownership requires explicit bookkeeping at\n  run-time, which can be costly.</li>\n\n  <li>In some cases (e.g., cyclic references), objects\n  with shared ownership may never be deleted.</li>\n\n  <li>Smart pointers are not perfect substitutes for\n  plain pointers.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>If dynamic allocation is necessary, prefer to keep\nownership with the code that allocated it. If other code\nneeds access to the object, consider passing it a copy,\nor passing a pointer or reference without transferring\nownership. Prefer to use <code>std::unique_ptr</code> to\nmake ownership transfer explicit. For example:</p>\n\n<pre class=\"goodcode\">std::unique_ptr&lt;Foo&gt; FooFactory();\nvoid FooConsumer(std::unique_ptr&lt;Foo&gt; ptr);\n</pre>\n\n\n\n<p>Do not design your code to use shared ownership\nwithout a very good reason. One such reason is to avoid\nexpensive copy operations, but you should only do this if\nthe performance benefits are significant, and the\nunderlying object is immutable (i.e.,\n<code>std::shared_ptr&lt;const Foo&gt;</code>).  If you\ndo use shared ownership, prefer to use\n<code>std::shared_ptr</code>.</p>\n\n<p>Never use <code>std::auto_ptr</code>. Instead, use\n<code>std::unique_ptr</code>.</p>\n\n<h3 id=\"cpplint\">cpplint</h3>\n\n<p>Use <code>cpplint.py</code> to detect style errors.</p>\n\n<p><code>cpplint.py</code>\nis a tool that reads a source file and identifies many\nstyle errors. It is not perfect, and has both false\npositives and false negatives, but it is still a valuable\ntool. </p>\n\n\n\n<div>\n<p>Some projects have instructions on\nhow to run <code>cpplint.py</code> from their project\ntools. If the project you are contributing to does not,\nyou can download\n<a href=\"https://raw.githubusercontent.com/cpplint/cpplint/HEAD/cpplint.py\">\n<code>cpplint.py</code></a> separately.</p>\n</div>\n\n\n\n<h2 id=\"Other_C++_Features\">Other C++ Features</h2>\n\n<h3 id=\"Rvalue_references\">Rvalue References</h3>\n\n<p>Use rvalue references only in certain special cases listed below.</p>\n\n<p class=\"definition\"></p>\n<p> Rvalue references\nare a type of reference that can only bind to temporary\nobjects. The syntax is similar to traditional reference\nsyntax. For example, <code>void f(std::string&amp;&amp;\ns);</code> declares a function whose argument is an\nrvalue reference to a <code>std::string</code>.</p>\n\n<p id=\"Forwarding_references\"> When the token '&amp;&amp;' is applied to\nan unqualified template argument in a function\nparameter, special template argument deduction\nrules apply. Such a reference is called a forwarding reference.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Defining a move constructor (a constructor taking\n  an rvalue reference to the class type) makes it\n  possible to move a value instead of copying it. If\n  <code>v1</code> is a <code>std::vector&lt;std::string&gt;</code>,\n  for example, then <code>auto v2(std::move(v1))</code>\n  will probably just result in some simple pointer\n  manipulation instead of copying a large amount of data.\n  In many cases this can result in a major performance\n  improvement.</li>\n\n  <li>Rvalue references make it possible to implement\n  types that are movable but not copyable, which can be\n  useful for types that have no sensible definition of\n  copying but where you might still want to pass them as\n  function arguments, put them in containers, etc.</li>\n\n  <li><code>std::move</code> is necessary to make\n  effective use of some standard-library types, such as\n  <code>std::unique_ptr</code>.</li>\n\n  <li><a href=\"#Forwarding_references\">Forwarding references</a> which\n  use the rvalue reference token make it possible to write a\n  generic function wrapper that forwards its arguments to\n  another function, and works whether or not its\n  arguments are temporary objects and/or const.\n  This is called 'perfect forwarding'.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>Rvalue references are not yet widely understood. Rules like reference\n  collapsing and the special deduction rule for forwarding references\n  are somewhat obscure.</li>\n\n  <li>Rvalue references are often misused. Using rvalue\n  references is counter-intuitive in signatures where the argument is expected\n  to have a valid specified state after the function call, or where no move\n  operation is performed.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Do not use rvalue references (or apply the <code>&amp;&amp;</code>\nqualifier to methods), except as follows:</p>\n<ul>\n  <li>You may use them to define move constructors and move assignment\n  operators (as described in\n  <a href=\"#Copyable_Movable_Types\">Copyable and Movable Types</a>).\n  </li>\n\n  <li>You may use them to define <code>&amp;&amp;</code>-qualified methods that\n  logically \"consume\" <code>*this</code>, leaving it in an unusable\n  or empty state. Note that this applies only to method qualifiers (which come\n  after the closing parenthesis of the function signature); if you want to\n  \"consume\" an ordinary function parameter, prefer to pass it by value.</li>\n\n  <li>You may use forwarding references in conjunction with <code>\n  <a href=\"http://en.cppreference.com/w/cpp/utility/forward\">std::forward</a></code>,\n  to support perfect forwarding.</li>\n\n  <li>You may use them to define pairs of overloads, such as one taking\n  <code>Foo&amp;&amp;</code> and the other taking <code>const Foo&amp;</code>.\n  Usually the preferred solution is just to pass by value, but an overloaded\n  pair of functions sometimes yields better performance, for example if the\n  functions sometimes don't consume the input. As always: if you're writing\n  more complicated code for the sake of performance, make sure you have evidence\n  that it actually helps.</li>\n</ul>\n\n<h3 id=\"Friends\">Friends</h3>\n\n<p>We allow use of <code>friend</code> classes and functions,\nwithin reason.</p>\n\n<p>Friends should usually be defined in the same file so\nthat the reader does not have to look in another file to\nfind uses of the private members of a class. A common use\nof <code>friend</code> is to have a\n<code>FooBuilder</code> class be a friend of\n<code>Foo</code> so that it can construct the inner state\nof <code>Foo</code> correctly, without exposing this\nstate to the world. In some cases it may be useful to\nmake a unit test class a friend of the class it tests.</p>\n\n<p>Friends extend, but do not break, the encapsulation\nboundary of a class. In some cases this is better than\nmaking a member <code>public</code> when you want to give only one\nother class access to it. However, most classes should\ninteract with other classes solely through their public\nmembers.</p>\n\n<h3 id=\"Exceptions\">Exceptions</h3>\n\n<p>We do not use C++ exceptions.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Exceptions allow higher levels of an application to\n  decide how to handle \"can't happen\" failures in deeply\n  nested functions, without the obscuring and error-prone\n  bookkeeping of error codes.</li>\n\n\n\n  <div>\n  <li>Exceptions are used by most other\n  modern languages. Using them in C++ would make it more\n  consistent with Python, Java, and the C++ that others\n  are familiar with.</li>\n  </div>\n\n  <li>Some third-party C++ libraries use exceptions, and\n  turning them off internally makes it harder to\n  integrate with those libraries.</li>\n\n  <li>Exceptions are the only way for a constructor to\n  fail. We can simulate this with a factory function or\n  an <code>Init()</code> method, but these require heap\n  allocation or a new \"invalid\" state, respectively.</li>\n\n  <li>Exceptions are really handy in testing\n  frameworks.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>When you add a <code>throw</code> statement to an\n  existing function, you must examine all of its\n  transitive callers. Either they must make at least the\n  basic exception safety guarantee, or they must never\n  catch the exception and be happy with the program\n  terminating as a result. For instance, if\n  <code>f()</code> calls <code>g()</code> calls\n  <code>h()</code>, and <code>h</code> throws an\n  exception that <code>f</code> catches, <code>g</code>\n  has to be careful or it may not clean up properly.</li>\n\n  <li>More generally, exceptions make the control flow of\n  programs difficult to evaluate by looking at code:\n  functions may return in places you don't expect. This\n  causes maintainability and debugging difficulties. You\n  can minimize this cost via some rules on how and where\n  exceptions can be used, but at the cost of more that a\n  developer needs to know and understand.</li>\n\n  <li>Exception safety requires both RAII and different\n  coding practices. Lots of supporting machinery is\n  needed to make writing correct exception-safe code\n  easy. Further, to avoid requiring readers to understand\n  the entire call graph, exception-safe code must isolate\n  logic that writes to persistent state into a \"commit\"\n  phase. This will have both benefits and costs (perhaps\n  where you're forced to obfuscate code to isolate the\n  commit). Allowing exceptions would force us to always\n  pay those costs even when they're not worth it.</li>\n\n  <li>Turning on exceptions adds data to each binary\n  produced, increasing compile time (probably slightly)\n  and possibly increasing address space pressure.\n  </li>\n\n  <li>The availability of exceptions may encourage\n  developers to throw them when they are not appropriate\n  or recover from them when it's not safe to do so. For\n  example, invalid user input should not cause exceptions\n  to be thrown. We would need to make the style guide\n  even longer to document these restrictions!</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>On their face, the benefits of using exceptions\noutweigh the costs, especially in new projects. However,\nfor existing code, the introduction of exceptions has\nimplications on all dependent code. If exceptions can be\npropagated beyond a new project, it also becomes\nproblematic to integrate the new project into existing\nexception-free code. Because most existing C++ code at\nGoogle is not prepared to deal with exceptions, it is\ncomparatively difficult to adopt new code that generates\nexceptions.</p>\n\n<p>Given that Google's existing code is not\nexception-tolerant, the costs of using exceptions are\nsomewhat greater than the costs in a new project. The\nconversion process would be slow and error-prone. We\ndon't believe that the available alternatives to\nexceptions, such as error codes and assertions, introduce\na significant burden. </p>\n\n<p>Our advice against using exceptions is not predicated\non philosophical or moral grounds, but practical ones.\n Because we'd like to use our open-source\nprojects at Google and it's difficult to do so if those\nprojects use exceptions, we need to advise against\nexceptions in Google open-source projects as well.\nThings would probably be different if we had to do it all\nover again from scratch.</p>\n\n<p>This prohibition also applies to exception handling related\nfeatures such as <code>std::exception_ptr</code> and\n<code>std::nested_exception</code>.</p>\n\n<p>There is an <a href=\"#Windows_Code\">exception</a> to\nthis rule (no pun intended) for Windows code.</p>\n\n<h3 id=\"noexcept\"><code>noexcept</code></h3>\n\n<p>Specify <code>noexcept</code> when it is useful and correct.</p>\n\n<p class=\"definition\"></p>\n<p>The <code>noexcept</code> specifier is used to specify whether\na function will throw exceptions or not. If an exception\nescapes from a function marked <code>noexcept</code>, the program\ncrashes via <code>std::terminate</code>.</p>\n\n<p>The <code>noexcept</code> operator performs a compile-time\ncheck that returns true if an expression is declared to not\nthrow any exceptions.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Specifying move constructors as <code>noexcept</code>\n  improves performance in some cases, e.g.,\n  <code>std::vector&lt;T&gt;::resize()</code> moves rather than\n  copies the objects if T's move constructor is\n  <code>noexcept</code>.</li>\n\n  <li>Specifying <code>noexcept</code> on a function can\n  trigger compiler optimizations in environments where\n  exceptions are enabled, e.g., compiler does not have to\n  generate extra code for stack-unwinding, if it knows\n  that no exceptions can be thrown due to a\n  <code>noexcept</code> specifier.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>\n\n  In projects following this guide\n  that have exceptions disabled it is hard\n  to ensure that <code>noexcept</code>\n  specifiers are correct, and hard to define what\n  correctness even means.</li>\n\n  <li>It's hard, if not impossible, to undo <code>noexcept</code>\n  because it eliminates a guarantee that callers may be relying\n  on, in ways that are hard to detect.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>You may use <code>noexcept</code> when it is useful for\nperformance if it accurately reflects the intended semantics\nof your function, i.e., that if an exception is somehow thrown\nfrom within the function body then it represents a fatal error.\nYou can assume that <code>noexcept</code> on move constructors\nhas a meaningful performance benefit. If you think\nthere is significant performance benefit from specifying\n<code>noexcept</code> on some other function, please discuss it\nwith\nyour project leads.</p>\n\n<p>Prefer unconditional <code>noexcept</code> if exceptions are\ncompletely disabled (i.e., most Google C++ environments).\nOtherwise, use conditional <code>noexcept</code> specifiers\nwith simple conditions, in ways that evaluate false only in\nthe few cases where the function could potentially throw.\nThe tests might include type traits check on whether the\ninvolved operation might throw (e.g.,\n<code>std::is_nothrow_move_constructible</code> for\nmove-constructing objects), or on whether allocation can throw\n(e.g., <code>absl::default_allocator_is_nothrow</code> for\nstandard default allocation). Note in many cases the only\npossible cause for an exception is allocation failure (we\nbelieve move constructors should not throw except due to\nallocation failure), and there are many applications where it's\nappropriate to treat memory exhaustion as a fatal error rather\nthan an exceptional condition that your program should attempt\nto recover from.  Even for other\npotential failures you should prioritize interface simplicity\nover supporting all possible exception throwing scenarios:\ninstead of writing a complicated <code>noexcept</code> clause\nthat depends on whether a hash function can throw, for example,\nsimply document that your component doesn't support hash\nfunctions throwing and make it unconditionally\n<code>noexcept</code>.</p>\n\n<h3 id=\"Run-Time_Type_Information__RTTI_\">Run-Time Type\nInformation (RTTI)</h3>\n\n<p>Avoid using run-time type information (RTTI).</p>\n\n<p class=\"definition\"></p>\n<p> RTTI allows a\nprogrammer to query the C++ class of an object at\nrun-time. This is done by use of <code>typeid</code> or\n<code>dynamic_cast</code>.</p>\n\n<p class=\"pros\"></p>\n<p>The standard alternatives to RTTI (described below)\nrequire modification or redesign of the class hierarchy\nin question. Sometimes such modifications are infeasible\nor undesirable, particularly in widely-used or mature\ncode.</p>\n\n<p>RTTI can be useful in some unit tests. For example, it\nis useful in tests of factory classes where the test has\nto verify that a newly created object has the expected\ndynamic type. It is also useful in managing the\nrelationship between objects and their mocks.</p>\n\n<p>RTTI is useful when considering multiple abstract\nobjects. Consider</p>\n\n<pre class=\"neutralcode\">bool Base::Equal(Base* other) = 0;\nbool Derived::Equal(Base* other) {\n  Derived* that = dynamic_cast&lt;Derived*&gt;(other);\n  if (that == nullptr)\n    return false;\n  ...\n}\n</pre>\n\n<p class=\"cons\"></p>\n<p>Querying the type of an object at run-time frequently\nmeans a design problem. Needing to know the type of an\nobject at runtime is often an indication that the design\nof your class hierarchy is flawed.</p>\n\n<p>Undisciplined use of RTTI makes code hard to maintain.\nIt can lead to type-based decision trees or switch\nstatements scattered throughout the code, all of which\nmust be examined when making further changes.</p>\n\n<p class=\"decision\"></p>\n<p>RTTI has legitimate uses but is prone to abuse, so you\nmust be careful when using it. You may use it freely in\nunit tests, but avoid it when possible in other code. In\nparticular, think twice before using RTTI in new code. If\nyou find yourself needing to write code that behaves\ndifferently based on the class of an object, consider one\nof the following alternatives to querying the type:</p>\n\n<ul>\n  <li>Virtual methods are the preferred way of executing\n  different code paths depending on a specific subclass\n  type. This puts the work within the object itself.</li>\n\n  <li>If the work belongs outside the object and instead\n  in some processing code, consider a double-dispatch\n  solution, such as the Visitor design pattern. This\n  allows a facility outside the object itself to\n  determine the type of class using the built-in type\n  system.</li>\n</ul>\n\n<p>When the logic of a program guarantees that a given\ninstance of a base class is in fact an instance of a\nparticular derived class, then a\n<code>dynamic_cast</code> may be used freely on the\nobject.  Usually one\ncan use a <code>static_cast</code> as an alternative in\nsuch situations.</p>\n\n<p>Decision trees based on type are a strong indication\nthat your code is on the wrong track.</p>\n\n<pre class=\"badcode\">if (typeid(*data) == typeid(D1)) {\n  ...\n} else if (typeid(*data) == typeid(D2)) {\n  ...\n} else if (typeid(*data) == typeid(D3)) {\n...\n</pre>\n\n<p>Code such as this usually breaks when additional\nsubclasses are added to the class hierarchy. Moreover,\nwhen properties of a subclass change, it is difficult to\nfind and modify all the affected code segments.</p>\n\n<p>Do not hand-implement an RTTI-like workaround. The\narguments against RTTI apply just as much to workarounds\nlike class hierarchies with type tags. Moreover,\nworkarounds disguise your true intent.</p>\n\n<h3 id=\"Casting\">Casting</h3>\n\n<p>Use C++-style casts\nlike <code>static_cast&lt;float&gt;(double_value)</code>, or brace\ninitialization for conversion of arithmetic types like\n<code>int64_t y = int64_t{1} &lt;&lt; 42</code>. Do not use\ncast formats like <code>(int)x</code> unless the cast is to\n<code>void</code>. You may use cast formats like <code>T(x)</code> only when\n<code>T</code> is a class type.</p>\n\n<p class=\"definition\"></p>\n<p> C++ introduced a\ndifferent cast system from C that distinguishes the types\nof cast operations.</p>\n\n<p class=\"pros\"></p>\n<p>The problem with C casts is the ambiguity of the operation;\nsometimes you are doing a <em>conversion</em>\n(e.g., <code>(int)3.5</code>) and sometimes you are doing\na <em>cast</em> (e.g., <code>(int)\"hello\"</code>). Brace\ninitialization and C++ casts can often help avoid this\nambiguity. Additionally, C++ casts are more visible when searching for\nthem.</p>\n\n<p class=\"cons\"></p>\n<p>The C++-style cast syntax is verbose and cumbersome.</p>\n\n<p class=\"decision\"></p>\n<p>In general, do not use C-style casts. Instead, use these C++-style\ncasts when explicit type conversion is necessary.\n</p>\n\n<ul>\n  <li>Use brace initialization to convert arithmetic types\n  (e.g., <code>int64_t{x}</code>).  This is the safest approach because code\n  will not compile if conversion can result in information loss.  The\n  syntax is also concise.</li>\n\n  <li>When explicitly converting to a class type, use a function-style cast;\n  e.g., prefer <code>std::string(some_cord)</code> to\n  <code>static_cast&lt;std::string&gt;(some_cord)</code>.</li>\n\n  <li>Use <code>absl::implicit_cast</code>\n  to safely cast up a type hierarchy,\n  e.g., casting a <code>Foo*</code> to a\n  <code>SuperclassOfFoo*</code> or casting a\n  <code>Foo*</code> to a <code>const Foo*</code>. C++\n  usually does this automatically but some situations\n  need an explicit up-cast, such as use of the\n  <code>?:</code> operator.</li>\n\n  <li>Use <code>static_cast</code> as the equivalent of a C-style cast\n  that does value conversion, when you need to\n  explicitly up-cast a pointer from a class to its superclass, or when\n  you need to explicitly cast a pointer from a superclass to a\n  subclass.  In this last case, you must be sure your object is\n  actually an instance of the subclass.</li>\n\n\n\n  <li>Use <code>const_cast</code> to remove the\n  <code>const</code> qualifier (see <a href=\"#Use_of_const\">const</a>).</li>\n\n  <li>Use <code>reinterpret_cast</code> to do unsafe conversions of\n  pointer types to and from integer and other pointer\n  types,\n  including <code>void*</code>. Use this\n  only if you know what you are doing and you understand the aliasing\n  issues. Also, consider dereferencing the pointer (without a cast) and\n  using <code>std::bit_cast</code> to cast the resulting value.</li>\n\n  <li>Use <code>std::bit_cast</code> to interpret the raw bits of a\n  value using a different type of the same size (a type pun), such as\n  interpreting the bits of a <code>double</code> as\n  <code>int64_t</code>.</li>\n</ul>\n\n<p>See the <a href=\"#Run-Time_Type_Information__RTTI_\">\nRTTI section</a> for guidance on the use of\n<code>dynamic_cast</code>.</p>\n\n<h3 id=\"Streams\">Streams</h3>\n\n<p>Use streams where appropriate, and stick to \"simple\"\nusages. Overload <code>&lt;&lt;</code> for streaming only for types\nrepresenting values, and write only the user-visible value, not any\nimplementation details.</p>\n\n<p class=\"definition\"></p>\n<p>Streams are the standard I/O abstraction in C++, as\nexemplified by the standard header <code>&lt;iostream&gt;</code>.\nThey are widely used in Google code, mostly for debug logging\nand test diagnostics.</p>\n\n<p class=\"pros\"></p>\n<p>The <code>&lt;&lt;</code> and <code>&gt;&gt;</code>\nstream operators provide an API for formatted I/O that\nis easily learned, portable, reusable, and extensible.\n<code>printf</code>, by contrast, doesn't even support\n<code>std::string</code>, to say nothing of user-defined types,\nand is very difficult to use portably.\n<code>printf</code> also obliges you to choose among the\nnumerous slightly different versions of that function,\nand navigate the dozens of conversion specifiers.</p>\n\n<p>Streams provide first-class support for console I/O\nvia <code>std::cin</code>, <code>std::cout</code>,\n<code>std::cerr</code>, and <code>std::clog</code>.\nThe C APIs do as well, but are hampered by the need to\nmanually buffer the input. </p>\n\n<p class=\"cons\"></p>\n<ul>\n<li>Stream formatting can be configured by mutating the\nstate of the stream. Such mutations are persistent, so\nthe behavior of your code can be affected by the entire\nprevious history of the stream, unless you go out of your\nway to restore it to a known state every time other code\nmight have touched it. User code can not only modify the\nbuilt-in state, it can add new state variables and behaviors\nthrough a registration system.</li>\n\n<li>It is difficult to precisely control stream output, due\nto the above issues, the way code and data are mixed in\nstreaming code, and the use of operator overloading (which\nmay select a different overload than you expect).</li>\n\n<li>The practice of building up output through chains\nof <code>&lt;&lt;</code> operators interferes with\ninternationalization, because it bakes word order into the\ncode, and streams' support for localization is <a href=\"http://www.boost.org/doc/libs/1_48_0/libs/locale/doc/html/rationale.html#rationale_why\">\nflawed</a>.</li>\n\n\n\n\n\n<li>The streams API is subtle and complex, so programmers must\ndevelop experience with it in order to use it effectively.</li>\n\n<li>Resolving the many overloads of <code>&lt;&lt;</code> is\nextremely costly for the compiler. When used pervasively in a\nlarge codebase, it can consume as much as 20% of the parsing\nand semantic analysis time.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Use streams only when they are the best tool for the job.\nThis is typically the case when the I/O is ad-hoc, local,\nhuman-readable, and targeted at other developers rather than\nend-users. Be consistent with the code around you, and with the\ncodebase as a whole; if there's an established tool for\nyour problem, use that tool instead.\nIn particular,\n\nlogging libraries are usually a better\nchoice than <code>std::cerr</code> or <code>std::clog</code>\nfor diagnostic output, and the libraries in\n\n<code>absl/strings</code>\nor the equivalent are usually a\nbetter choice than <code>std::stringstream</code>.</p>\n\n<p>Avoid using streams for I/O that faces external users or\nhandles untrusted data. Instead, find and use the appropriate\ntemplating libraries to handle issues like internationalization,\nlocalization, and security hardening.</p>\n\n<p>If you do use streams, avoid the stateful parts of the\nstreams API (other than error state), such as <code>imbue()</code>,\n<code>xalloc()</code>, and <code>register_callback()</code>.\nUse explicit formatting functions (such as\n<code>absl::StreamFormat()</code>) rather than\nstream manipulators or formatting flags to control formatting\ndetails such as number base, precision, or padding.</p>\n\n<p>Overload <code>&lt;&lt;</code> as a streaming operator\nfor your type only if your type represents a value, and\n<code>&lt;&lt;</code> writes out a human-readable string\nrepresentation of that value. Avoid exposing implementation\ndetails in the output of <code>&lt;&lt;</code>; if you need to print\nobject internals for debugging, use named functions instead\n(a method named <code>DebugString()</code> is the most common\nconvention).</p>\n\n<h3 id=\"Preincrement_and_Predecrement\">Preincrement and Predecrement</h3>\n\n<p>Use the prefix form (<code>++i</code>) of the increment\nand decrement operators unless you need postfix semantics.</p>\n\n<p class=\"definition\"></p>\n<p> When a variable\nis incremented (<code>++i</code> or <code>i++</code>) or\ndecremented (<code>--i</code> or <code>i--</code>) and\nthe value of the expression is not used, one must decide\nwhether to preincrement (decrement) or postincrement\n(decrement).</p>\n\n<p class=\"pros\"></p>\n\n<p>A postfix increment/decrement expression evaluates to the value\n<i>as it was before it was modified</i>. This can result in code that is more\ncompact but harder to read. The prefix form is generally more readable, is\nnever less efficient, and can be more efficient because it doesn't need to\nmake a copy of the value as it was before the operation.\n</p>\n\n<p class=\"cons\"></p>\n<p>The tradition developed, in C, of using post-increment, even\nwhen the expression value is not used, especially in\n<code>for</code> loops.</p>\n\n<p class=\"decision\"></p>\n<p>Use prefix increment/decrement, unless the code explicitly\nneeds the result of the postfix increment/decrement expression.</p>\n\n<h3 id=\"Use_of_const\">Use of const</h3>\n\n<p>In APIs, use <code>const</code> whenever it makes sense.\n<code>constexpr</code> is a better choice for some uses of\n<code>const</code>.</p>\n\n<p class=\"definition\"></p>\n<p> Declared variables and parameters can be preceded\nby the keyword <code>const</code> to indicate the variables\nare not changed (e.g., <code>const int foo</code>). Class\nfunctions can have the <code>const</code> qualifier to\nindicate the function does not change the state of the\nclass member variables (e.g., <code>class Foo { int\nBar(char c) const; };</code>).</p>\n\n<p class=\"pros\"></p>\n<p>Easier for people to understand how variables are being\nused. Allows the compiler to do better type checking,\nand, conceivably, generate better code. Helps people\nconvince themselves of program correctness because they\nknow the functions they call are limited in how they can\nmodify your variables. Helps people know what functions\nare safe to use without locks in multi-threaded\nprograms.</p>\n\n<p class=\"cons\"></p>\n<p><code>const</code> is viral: if you pass a\n<code>const</code> variable to a function, that function\nmust have <code>const</code> in its prototype (or the\nvariable will need a <code>const_cast</code>). This can\nbe a particular problem when calling library\nfunctions.</p>\n\n<p class=\"decision\"></p>\n<p>We strongly recommend using <code>const</code>\nin APIs (i.e., on function parameters, methods, and\nnon-local variables) wherever it is meaningful and accurate. This\nprovides consistent, mostly compiler-verified documentation\nof what objects an operation can mutate. Having\na consistent and reliable way to distinguish reads from writes\nis critical to writing thread-safe code, and is useful in\nmany other contexts as well. In particular:</p>\n\n<ul>\n  <li>If a function guarantees that it will not modify an argument\n  passed by reference or by pointer, the corresponding function parameter\n  should be a reference-to-const (<code>const T&amp;</code>) or\n  pointer-to-const (<code>const T*</code>), respectively.</li>\n\n  <li>For a function parameter passed by value, <code>const</code> has\n  no effect on the caller, thus is not recommended in function\n  declarations. See <a href=\"https://abseil.io/tips/109\">TotW #109</a>.</li>\n\n  <li>Declare methods to be <code>const</code> unless they\n  alter the logical state of the object (or enable the user to modify\n  that state, e.g., by returning a non-<code>const</code> reference, but that's\n  rare), or they can't safely be invoked concurrently.</li>\n</ul>\n\n<p>Using <code>const</code> on local variables is neither encouraged\nnor discouraged.</p>\n\n<p>All of a class's <code>const</code> operations should be safe\nto invoke concurrently with each other. If that's not feasible, the class must\nbe clearly documented as \"thread-unsafe\".</p>\n\n\n<h4>Where to put the const</h4>\n\n<p>Some people favor the form <code>int const* foo</code>\nto <code>const int* foo</code>. They argue that this is\nmore readable because it's more consistent: it keeps the\nrule that <code>const</code> always follows the object\nit's describing. However, this consistency argument\ndoesn't apply in codebases with few deeply-nested pointer\nexpressions since most <code>const</code> expressions\nhave only one <code>const</code>, and it applies to the\nunderlying value. In such cases, there's no consistency\nto maintain. Putting the <code>const</code> first is\narguably more readable, since it follows English in\nputting the \"adjective\" (<code>const</code>) before the\n\"noun\" (<code>int</code>).</p>\n\n<p>That said, while we encourage putting\n<code>const</code> first, we do not require it. But be\nconsistent with the code around you!</p>\n\n<h3 id=\"Use_of_constexpr\">Use of constexpr, constinit, and consteval</h3>\n\n<p>Use <code>constexpr</code> to define true\nconstants or to ensure constant initialization.\nUse <code>constinit</code> to ensure constant\ninitialization for non-constant variables.\n</p>\n\n<p class=\"definition\"></p>\n<p> Some variables can be declared <code>constexpr</code>\nto indicate the variables are true constants, i.e., fixed at\ncompilation/link time. Some functions and constructors\ncan be declared <code>constexpr</code> which enables them\nto be used in defining a <code>constexpr</code>\nvariable. Functions can be declared <code>consteval</code>\nto restrict their use to compile time.</p>\n\n<p class=\"pros\"></p>\n<p>Use of <code>constexpr</code> enables definition of\nconstants with floating-point expressions rather than\njust literals; definition of constants of user-defined\ntypes; and definition of constants with function\ncalls.</p>\n\n<p class=\"cons\"></p>\n<p>Prematurely marking something as <code>constexpr</code> may cause\nmigration problems if later on it has to be downgraded.\nCurrent restrictions on what is allowed in <code>constexpr</code>\nfunctions and constructors may invite obscure workarounds\nin these definitions.</p>\n\n<p class=\"decision\"></p>\n<p><code>constexpr</code> definitions enable a more\nrobust specification of the constant parts of an\ninterface. Use <code>constexpr</code> to specify true\nconstants and the functions that support their\ndefinitions. <code>consteval</code> may be used for\ncode that must not be invoked at runtime.\nAvoid complexifying function definitions to\nenable their use with <code>constexpr</code>. Do not use\n<code>constexpr</code> or <code>consteval</code> to force inlining.</p>\n\n<h3 id=\"Integer_Types\">Integer Types</h3>\n\n<p>Of the built-in C++ integer types, the only one used\n is\n<code>int</code>. If a program needs an integer type of a\ndifferent size, use an exact-width integer type from\n<code>&lt;stdint.h&gt;</code>, such as\n<code>int16_t</code>. If you have a\nvalue that could ever be greater than or equal to 2^31,\nuse a 64-bit type such as <code>int64_t</code>.\nKeep in mind that even if your value won't ever be too large\nfor an <code>int</code>, it may be used in intermediate\ncalculations which may require a larger type. When in doubt,\nchoose a larger type.</p>\n\n<p class=\"definition\"></p>\n<p>C++ does not specify exact sizes for the integer types\nlike <code>int</code>. Common sizes on contemporary architectures are\n16 bits for <code>short</code>, 32 bits for <code>int</code>, 32 or 64\nbits for <code>long</code>, and 64 bits for <code>long long</code>,\nbut different platforms make different choices, in particular\nfor <code>long</code>.</p>\n\n<p class=\"pros\"></p>\n<p>Uniformity of declaration.</p>\n\n<p class=\"cons\"></p>\n<p>The sizes of integral types in C++ can vary based on\ncompiler and architecture.</p>\n\n<p class=\"decision\"></p>\n\n<p>\nThe standard library header <code>&lt;stdint.h&gt;</code> defines types\nlike <code>int16_t</code>, <code>uint32_t</code>,\n<code>int64_t</code>, etc. You should always use\nthose in preference to <code>short</code>, <code>unsigned\nlong long</code>, and the like, when you need a guarantee\non the size of an integer. Prefer to omit the <code>std::</code>\nprefix for these types, as the extra 5 characters do\nnot merit the added clutter. Of the built-in integer types, only\n<code>int</code> should be used. When appropriate, you\nare welcome to use standard type aliases like\n<code>size_t</code> and <code>ptrdiff_t</code>.</p>\n\n<p>We use <code>int</code> very often, for integers we\nknow are not going to be too big, e.g., loop counters.\nUse plain old <code>int</code> for such things. You\nshould assume that an <code>int</code> is\n\nat least 32 bits, but don't\nassume that it has more than 32 bits. If you need a 64-bit\ninteger type, use <code>int64_t</code> or <code>uint64_t</code>.\n\n</p><p>For integers we know can be \"big\",\n use\n<code>int64_t</code>.\n</p>\n\n<p>You should not use the unsigned integer types such as\n<code>uint32_t</code>, unless there is a valid\nreason such as representing a bit pattern rather than a\nnumber, or you need defined overflow modulo 2^N. In\nparticular, do not use unsigned types to say a number\nwill never be negative. Instead, use\n\nassertions for this.</p>\n\n\n\n<p>If your code is a container that returns a size, be\nsure to use a type that will accommodate any possible\nusage of your container. When in doubt, use a larger type\nrather than a smaller type.</p>\n\n<p>Use care when converting integer types. Integer conversions and\npromotions can cause undefined behavior, leading to security bugs and\nother problems.</p>\n\n<h4>On Unsigned Integers</h4>\n\n<p>Unsigned integers are good for representing bitfields and modular\narithmetic. Because of historical accident, the C++ standard also uses\nunsigned integers to represent the size of containers - many members\nof the standards body believe this to be a mistake, but it is\neffectively impossible to fix at this point. The fact that unsigned\narithmetic doesn't model the behavior of a simple integer, but is\ninstead defined by the standard to model modular arithmetic (wrapping\naround on overflow/underflow), means that a significant class of bugs\ncannot be diagnosed by the compiler. In other cases, the defined\nbehavior impedes optimization.</p>\n\n<p>That said, mixing signedness of integer types is responsible for an\nequally large class of problems. The best advice we can provide: try\nto use iterators and containers rather than pointers and sizes, try\nnot to mix signedness, and try to avoid unsigned types (except for\nrepresenting bitfields or modular arithmetic). Do not use an unsigned\ntype merely to assert that a variable is non-negative.</p>\n\n<h3 id=\"Floating-Point_Types\">Floating-Point Types</h3>\n\n<p>Of the built-in C++ floating-point types, the only ones used\n are <code>float</code> and\n<code>double</code>. You may assume that these types represent IEEE-754 binary32\nand binary64, respectively.</p>\n\n<p>Do not use <code>long double</code>, as it gives non-portable\nresults.</p>\n\n<a id=\"64-bit_Portability\"></a>\n<h3 id=\"Architecture_Portability\">Architecture Portability</h3>\n\n<p>Write architecture-portable code. Do not rely on CPU features specific to a\nsingle processor.</p>\n\n<ul>\n  <li>When printing values, use type-safe numeric formatting libraries like\n  <a href=\"https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_cat.h\"><code>absl::StrCat</code></a>,\n  <a href=\"https://github.com/abseil/abseil-cpp/blob/master/absl/strings/substitute.h\"><code>absl::Substitute</code></a>,\n  <a href=\"https://github.com/abseil/abseil-cpp/blob/master/absl/strings/str_format.h\"><code>absl::StrFormat</code></a>,\n  or <a href=\"#Streams\"><code>std::ostream</code></a> instead of the\n  <code>printf</code> family of functions.</li>\n\n  <li>When moving structured data into or out of your process, encode it using a\n  serialization library like\n  <a href=\"https://protobuf.dev/\">Protocol\n  Buffers</a> rather than copying the in-memory representation around.\n  </li>\n\n  <li>If you need to work with memory addresses as integers, store them in\n  <code>uintptr_t</code>s rather than <code>uint32_t</code>s or\n  <code>uint64_t</code>s.</li>\n\n  <li>\n  Use <a href=\"#Casting\">braced-initialization</a> as needed to create\n  64-bit constants. For example:\n<pre class=\"goodcode\">int64_t my_value{0x123456789};\nuint64_t my_mask{uint64_t{3} &lt;&lt; 48};\n</pre>\n  </li>\n\n  <li>Use portable <a href=\"#Floating-Point_Types\">floating point types</a>;\n  avoid <code>long double</code>.</li>\n\n  <li>Use portable <a href=\"#Integer_Types\">integer types</a>; avoid\n  <code>short</code>, <code>long</code>, and <code>long long</code>.</li>\n</ul>\n\n<h3 id=\"Preprocessor_Macros\">Preprocessor Macros</h3>\n\n<p>Avoid defining macros, especially in headers; prefer\ninline functions, enums, and <code>const</code> variables.\nName macros with a project-specific prefix. Do not use\nmacros to define pieces of a C++ API.</p>\n\n<p>Macros mean that the code you see is not the same as\nthe code the compiler sees. This can introduce unexpected\nbehavior, especially since macros have global scope.</p>\n\n<p>The problems introduced by macros are especially severe\nwhen they are used to define pieces of a C++ API,\nand still more so for public APIs. Every error message from\nthe compiler when developers incorrectly use that interface\nnow must explain how the macros formed the interface.\nRefactoring and analysis tools have a dramatically harder\ntime updating the interface. As a consequence, we\nspecifically disallow using macros in this way.\nFor example, avoid patterns like:</p>\n\n<pre class=\"badcode\">class WOMBAT_TYPE(Foo) {\n  // ...\n\n public:\n  EXPAND_PUBLIC_WOMBAT_API(Foo)\n\n  EXPAND_WOMBAT_COMPARISONS(Foo, ==, &lt;)\n};\n</pre>\n\n<p>Luckily, macros are not nearly as necessary in C++ as\nthey are in C. Instead of using a macro to inline\nperformance-critical code, use an inline function.\nInstead of using a macro to store a constant, use a\n<code>const</code> variable. Instead of using a macro to\n\"abbreviate\" a long variable name, use a reference.\nInstead of using a macro to conditionally compile code\n... well, don't do that at all (except, of course, for\nthe <code>#define</code> guards to prevent double\ninclusion of header files). It makes testing much more\ndifficult.</p>\n\n<p>Macros can do things these other techniques cannot,\nand you do see them in the codebase, especially in the\nlower-level libraries. And some of their special features\n(like stringifying, concatenation, and so forth) are not\navailable through the language proper. But before using a\nmacro, consider carefully whether there's a non-macro way\nto achieve the same result. If you need to use a macro to\ndefine an interface, contact\nyour project leads to request\na waiver of this rule.</p>\n\n<p>The following usage pattern will avoid many problems\nwith macros; if you use macros, follow it whenever\npossible:</p>\n\n<ul>\n  <li>Don't define macros in a <code>.h</code> file.</li>\n\n  <li><code>#define</code> macros right before you use\n  them, and <code>#undef</code> them right after.</li>\n\n  <li>Do not just <code>#undef</code> an existing macro\n  before replacing it with your own; instead, pick a name\n  that's likely to be unique.</li>\n\n  <li>Try not to use macros that expand to unbalanced C++\n  constructs, or at least document that behavior\n  well.</li>\n\n  <li>Prefer not using <code>##</code> to generate\n  function/class/variable names.</li>\n\n</ul>\n\n<p>Exporting macros from headers (i.e., defining them in a header\nwithout <code>#undef</code>ing them before the end of the header)\nis extremely strongly discouraged. If you do export a macro from a\nheader, it must have a globally unique name. To achieve this, it\nmust be named with a prefix consisting of your project's namespace\nname (but upper case). </p>\n\n<h3 id=\"0_and_nullptr/NULL\">0 and nullptr/NULL</h3>\n\n<p>Use <code>nullptr</code> for pointers, and <code>'\\0'</code> for chars (and\nnot the <code>0</code> literal).</p>\n\n<p>For pointers (address values), use <code>nullptr</code>, as this\nprovides type-safety.</p>\n\n<p>Use <code>'\\0'</code> for the null character. Using the correct type makes\nthe code more readable.</p>\n\n<h3 id=\"sizeof\">sizeof</h3>\n\n<p>Prefer <code>sizeof(<var>varname</var>)</code> to\n<code>sizeof(<var>type</var>)</code>.</p>\n\n<p>Use <code>sizeof(<var>varname</var>)</code> when you\ntake the size of a particular variable.\n<code>sizeof(<var>varname</var>)</code> will update\nappropriately if someone changes the variable type either\nnow or later. You may use\n<code>sizeof(<var>type</var>)</code> for code unrelated\nto any particular variable, such as code that manages an\nexternal or internal data format where a variable of an\nappropriate C++ type is not convenient.</p>\n\n<pre class=\"goodcode\">MyStruct data;\nmemset(&amp;data, 0, sizeof(data));\n</pre>\n\n<pre class=\"badcode\">memset(&amp;data, 0, sizeof(MyStruct));\n</pre>\n\n<pre class=\"goodcode\">if (raw_size &lt; sizeof(int)) {\n  LOG(ERROR) &lt;&lt; \"compressed record not big enough for count: \" &lt;&lt; raw_size;\n  return false;\n}\n</pre>\n\n<a id=\"auto\"></a>\n<h3 id=\"Type_deduction\">Type Deduction (including auto)</h3>\n\n<p>Use type deduction only if it makes the code clearer to readers who aren't\n  familiar with the project, or if it makes the code safer. Do not use it\n  merely to avoid the inconvenience of writing an explicit type.</p>\n\n<p class=\"definition\"></p>\n\n<p>There are several contexts in which C++ allows (or even requires) types to\nbe deduced by the compiler, rather than spelled out explicitly in the code:</p>\n<dl>\n  <dt><a href=\"https://en.cppreference.com/w/cpp/language/template_argument_deduction\">Function template argument deduction</a></dt>\n  <dd>A function template can be invoked without explicit template arguments.\n    The compiler deduces those arguments from the types of the function\n    arguments:\n    <pre class=\"neutralcode\">template &lt;typename T&gt;\nvoid f(T t);\n\nf(0);  // Invokes f&lt;int&gt;(0)</pre>\n  </dd>\n  <dt><a href=\"https://en.cppreference.com/w/cpp/language/auto\"><code>auto</code> variable declarations</a></dt>\n  <dd>A variable declaration can use the <code>auto</code> keyword in place\n    of the type. The compiler deduces the type from the variable's\n    initializer, following the same rules as function template argument\n    deduction with the same initializer (so long as you don't use curly braces\n    instead of parentheses).\n    <pre class=\"neutralcode\">auto a = 42;  // a is an int\nauto&amp; b = a;  // b is an int&amp;\nauto c = b;   // c is an int\nauto d{42};   // d is an int, not a std::initializer_list&lt;int&gt;\n</pre>\n    <code>auto</code> can be qualified with <code>const</code>, and can be\n    used as part of a pointer or reference type, and (since C++17) as a\n    non-type template argument. A rare variant of this syntax uses\n    <code>decltype(auto)</code> instead of <code>auto</code>, in which case\n    the deduced type is the result of applying\n    <a href=\"https://en.cppreference.com/w/cpp/language/decltype\"><code>decltype</code></a>\n    to the initializer.\n  </dd>\n  <dt><a href=\"https://en.cppreference.com/w/cpp/language/function#Return_type_deduction\">Function return type deduction</a></dt>\n  <dd><code>auto</code> (and <code>decltype(auto)</code>) can also be used in\n    place of a function return type. The compiler deduces the return type from\n    the <code>return</code> statements in the function body, following the same\n    rules as for variable declarations:\n    <pre class=\"neutralcode\">auto f() { return 0; }  // The return type of f is int</pre>\n    <a href=\"#Lambda_expressions\">Lambda expression</a> return types can be\n    deduced in the same way, but this is triggered by omitting the return type,\n    rather than by an explicit <code>auto</code>. Confusingly,\n    <a href=\"#trailing_return\">trailing return type</a> syntax for functions\n    also uses <code>auto</code> in the return-type position, but that doesn't\n    rely on type deduction; it's just an alternative syntax for an explicit\n    return type.\n  </dd>\n  <dt><a href=\"https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas\">Generic lambdas</a></dt>\n  <dd>A lambda expression can use the <code>auto</code> keyword in place of\n    one or more of its parameter types. This causes the lambda's call operator\n    to be a function template instead of an ordinary function, with a separate\n    template parameter for each <code>auto</code> function parameter:\n    <pre class=\"neutralcode\">// Sort `vec` in decreasing order\nstd::sort(vec.begin(), vec.end(), [](auto lhs, auto rhs) { return lhs &gt; rhs; });</pre>\n  </dd>\n  <dt><a href=\"https://isocpp.org/wiki/faq/cpp14-language#lambda-captures\">Lambda init captures</a></dt>\n  <dd>Lambda captures can have explicit initializers, which can be used to\n    declare wholly new variables rather than only capturing existing ones:\n    <pre class=\"neutralcode\">[x = 42, y = \"foo\"] { ... }  // x is an int, and y is a const char*</pre>\n    This syntax doesn't allow the type to be specified; instead, it's deduced\n    using the rules for <code>auto</code> variables.\n  </dd>\n  <dt><a href=\"https://en.cppreference.com/w/cpp/language/class_template_argument_deduction\">Class template argument deduction</a></dt>\n  <dd>See <a href=\"#CTAD\">below</a>.</dd>\n  <dt><a href=\"https://en.cppreference.com/w/cpp/language/structured_binding\">Structured bindings</a></dt>\n  <dd>When declaring a tuple, struct, or array using <code>auto</code>, you can\n    specify names for the individual elements instead of a name for the whole\n    object; these names are called \"structured bindings\", and the whole\n    declaration is called a \"structured binding declaration\". This syntax\n    provides no way of specifying the type of either the enclosing object\n    or the individual names:\n    <pre class=\"neutralcode\">auto [iter, success] = my_map.insert({key, value});\nif (!success) {\n  iter-&gt;second = value;\n}</pre>\n    The <code>auto</code> can also be qualified with <code>const</code>,\n    <code>&amp;</code>, and <code>&amp;&amp;</code>, but note that these qualifiers\n    technically apply to the anonymous tuple/struct/array, rather than the\n    individual bindings. The rules that determine the types of the bindings\n    are quite complex; the results tend to be unsurprising, except that\n    the binding types typically won't be references even if the declaration\n    declares a reference (but they will usually behave like references anyway).\n  </dd>\n</dl>\n\n<p>(These summaries omit many details and caveats; see the links for further\n  information.)</p>\n\n<p class=\"pros\"></p>\n\n<ul>\n  <li>C++ type names can be long and cumbersome, especially when they\n    involve templates or namespaces.</li>\n  <li>When a C++ type name is repeated within a single declaration or a\n    small code region, the repetition may not be aiding readability.</li>\n  <li>It is sometimes safer to let the type be deduced, since that avoids\n    the possibility of unintended copies or type conversions.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<p>C++ code is usually clearer when types are explicit,\n  especially when type deduction would depend on information from\n  distant parts of the code. In expressions like:</p>\n\n<pre class=\"badcode\">auto foo = x.add_foo();\nauto i = y.Find(key);\n</pre>\n\n<p>it may not be obvious what the resulting types are if the type\n  of <code>y</code> isn't very well known, or if <code>y</code> was\n  declared many lines earlier.</p>\n\n<p>Programmers have to understand when type deduction will or won't\n  produce a reference type, or they'll get copies when they didn't\n  mean to.</p>\n\n<p>If a deduced type is used as part of an interface, then a\n  programmer might change its type while only intending to\n  change its value, leading to a more radical API change\n  than intended.</p>\n\n<p class=\"decision\"></p>\n\n<p>The fundamental rule is: use type deduction only to make the code\n  clearer or safer, and do not use it merely to avoid the\n  inconvenience of writing an explicit type. When judging whether the\n  code is clearer, keep in mind that your readers are not necessarily\n  on your team, or familiar with your project, so types that you and\n  your reviewer experience as unnecessary clutter will very often\n  provide useful information to others. For example, you can assume that\n  the return type of <code>make_unique&lt;Foo&gt;()</code> is obvious,\n  but the return type of <code>MyWidgetFactory()</code> probably isn't.</p>\n\n  <p>These principles apply to all forms of type deduction, but the\n  details vary, as described in the following sections.</p>\n\n<h4>Function template argument deduction</h4>\n\n<p>Function template argument deduction is almost always OK. Type deduction\n  is the expected default way of interacting with function templates,\n  because it allows function templates to act like infinite sets of ordinary\n  function overloads. Consequently, function templates are almost always\n  designed so that template argument deduction is clear and safe, or\n  doesn't compile.</p>\n\n<h4>Local variable type deduction</h4>\n\n<p>For local variables, you can use type deduction to make the code clearer\n  by eliminating type information that is obvious or irrelevant, so that\n  the reader can focus on the meaningful parts of the code:</p>\n  <pre class=\"neutralcode\">std::unique_ptr&lt;WidgetWithBellsAndWhistles&gt; widget =\n    std::make_unique&lt;WidgetWithBellsAndWhistles&gt;(arg1, arg2);\nabsl::flat_hash_map&lt;std::string,\n                    std::unique_ptr&lt;WidgetWithBellsAndWhistles&gt;&gt;::const_iterator\n    it = my_map_.find(key);\nstd::array&lt;int, 6&gt; numbers = {4, 8, 15, 16, 23, 42};</pre>\n\n  <pre class=\"goodcode\">auto widget = std::make_unique&lt;WidgetWithBellsAndWhistles&gt;(arg1, arg2);\nauto it = my_map_.find(key);\nstd::array numbers = {4, 8, 15, 16, 23, 42};</pre>\n\n<p>Types sometimes contain a mixture of useful information and boilerplate,\n  such as <code>it</code> in the example above: it's obvious that the\n  type is an iterator, and in many contexts the container type and even the\n  key type aren't relevant, but the type of the values is probably useful.\n  In such situations, it's often possible to define local variables with\n  explicit types that convey the relevant information:</p>\n  <pre class=\"goodcode\">if (auto it = my_map_.find(key); it != my_map_.end()) {\n  WidgetWithBellsAndWhistles&amp; widget = *it-&gt;second;\n  // Do stuff with `widget`\n}</pre>\n<p>If the type is a template instance, and the parameters are\n  boilerplate but the template itself is informative, you can use\n  class template argument deduction to suppress the boilerplate. However,\n  cases where this actually provides a meaningful benefit are quite rare.\n  Note that class template argument deduction is also subject to a\n  <a href=\"#CTAD\">separate style rule</a>.</p>\n\n<p>Do not use <code>decltype(auto)</code> if a simpler option will work;\n  because it's a fairly obscure feature, it has a high cost in code\n  clarity.</p>\n\n<h4>Return type deduction</h4>\n\n<p>Use return type deduction (for both functions and lambdas) only if the\n  function body has a very small number of <code>return</code> statements,\n  and very little other code, because otherwise the reader may not be able\n  to tell at a glance what the return type is. Furthermore, use it only\n  if the function or lambda has a very narrow scope, because functions with\n  deduced return types don't define abstraction boundaries: the implementation\n  <em>is</em> the interface. In particular, public functions in header files\n  should almost never have deduced return types.</p>\n\n<h4>Parameter type deduction</h4>\n\n<p><code>auto</code> parameter types for lambdas should be used with caution,\n  because the actual type is determined by the code that calls the lambda,\n  rather than by the definition of the lambda. Consequently, an explicit\n  type will almost always be clearer unless the lambda is explicitly called\n  very close to where it's defined (so that the reader can easily see both),\n  or the lambda is passed to an interface so well-known that it's\n  obvious what arguments it will eventually be called with (e.g.,\n  the <code>std::sort</code> example above).</p>\n\n<h4>Lambda init captures</h4>\n\n<p>Init captures are covered by a <a href=\"#Lambda_expressions\">more specific\n    style rule</a>, which largely supersedes the general rules for\n  type deduction.</p>\n\n<h4>Structured bindings</h4>\n\n<p>Unlike other forms of type deduction, structured bindings can actually\n  give the reader additional information, by giving meaningful names to the\n  elements of a larger object. This means that a structured binding declaration\n  may provide a net readability improvement over an explicit type, even in cases\n  where <code>auto</code> would not. Structured bindings are especially\n  beneficial when the object is a pair or tuple (as in the <code>insert</code>\n  example above), because they don't have meaningful field names to begin with,\n  but note that you generally <a href=\"#Structs_vs._Tuples\">shouldn't use\n    pairs or tuples</a> unless a pre-existing API like <code>insert</code>\n  forces you to.</p>\n\n<p>If the object being bound is a struct, it may sometimes be helpful to\n  provide names that are more specific to your usage, but keep in mind that\n  this may also mean the names are less recognizable to your reader than the\n  field names. We recommend using a comment to indicate the name of the\n  underlying field, if it doesn't match the name of the binding, using the\n  same syntax as for function parameter comments:</p>\n  <pre class=\"goodcode\">auto [/*field_name1=*/bound_name1, /*field_name2=*/bound_name2] = ...</pre>\n<p>As with function parameter comments, this can enable tools to detect if\n  you get the order of the fields wrong.</p>\n\n<h3 id=\"CTAD\">Class Template Argument Deduction</h3>\n\n<p>Use class template argument deduction only with templates that have\n  explicitly opted into supporting it.</p>\n\n<p class=\"definition\"></p>\n<p><a href=\"https://en.cppreference.com/w/cpp/language/class_template_argument_deduction\">Class\n    template argument deduction</a> (often abbreviated \"CTAD\") occurs when\n  a variable is declared with a type that names a template, and the template\n  argument list is not provided (not even empty angle brackets):</p>\n  <pre class=\"neutralcode\">std::array a = {1, 2, 3};  // `a` is a std::array&lt;int, 3&gt;</pre>\n<p>The compiler deduces the arguments from the initializer using the\n  template's \"deduction guides\", which can be explicit or implicit.</p>\n\n<p>Explicit deduction guides look like function declarations with trailing\n  return types, except that there's no leading <code>auto</code>, and the\n  function name is the name of the template. For example, the above example\n  relies on this deduction guide for <code>std::array</code>:</p>\n  <pre class=\"neutralcode\">namespace std {\ntemplate &lt;class T, class... U&gt;\narray(T, U...) -&gt; std::array&lt;T, 1 + sizeof...(U)&gt;;\n}</pre>\n<p>Constructors in a primary template (as opposed to a template specialization)\n  also implicitly define deduction guides.</p>\n\n<p>When you declare a variable that relies on CTAD, the compiler selects\n  a deduction guide using the rules of constructor overload resolution,\n  and that guide's return type becomes the type of the variable.</p>\n\n<p class=\"pros\"></p>\n<p>CTAD can sometimes allow you to omit boilerplate from your code.</p>\n\n<p class=\"cons\"></p>\n<p>The implicit deduction guides that are generated from constructors\n  may have undesirable behavior, or be outright incorrect. This is\n  particularly problematic for constructors written before CTAD was\n  introduced in C++17, because the authors of those constructors had no\n  way of knowing about (much less fixing) any problems that their\n  constructors would cause for CTAD. Furthermore, adding explicit deduction\n  guides to fix those problems might break any existing code that relies on\n  the implicit deduction guides.</p>\n\n<p>CTAD also suffers from many of the same drawbacks as <code>auto</code>,\n  because they are both mechanisms for deducing all or part of a variable's\n  type from its initializer. CTAD does give the reader more information\n  than <code>auto</code>, but it also doesn't give the reader an obvious\n  cue that information has been omitted.</p>\n\n<p class=\"decision\"></p>\n<p>Do not use CTAD with a given template unless the template's maintainers\n  have opted into supporting use of CTAD by providing at least one explicit\n  deduction guide (all templates in the <code>std</code> namespace are\n  also presumed to have opted in). This should be enforced with a compiler\n  warning if available.</p>\n\n<p>Uses of CTAD must also follow the general rules on\n  <a href=\"#Type_deduction\">Type deduction</a>.</p>\n\n<h3 id=\"Designated_initializers\">Designated Initializers</h3>\n\n<p>Use designated initializers only in their C++20-compliant form.</p>\n\n<p class=\"definition\"></p>\n<p><a href=\"https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers\">\n  Designated initializers</a> are a syntax that allows for initializing an\n  aggregate (\"plain old struct\") by naming its fields explicitly:</p>\n  <pre class=\"neutralcode\">  struct Point {\n    float x = 0.0;\n    float y = 0.0;\n    float z = 0.0;\n  };\n\n  Point p = {\n    .x = 1.0,\n    .y = 2.0,\n    // z will be 0.0\n  };</pre>\n<p>The explicitly listed fields will be initialized as specified, and others\n  will be initialized in the same way they would be in a traditional aggregate\n  initialization expression like <code>Point{1.0, 2.0}</code>.</p>\n\n<p class=\"pros\"></p>\n<p>Designated initializers can make for convenient and highly readable\naggregate expressions, especially for structs with less straightforward\nordering of fields than the <code>Point</code> example above.</p>\n\n<p class=\"cons\"></p>\n<p>While designated initializers have long been part of the C standard and\nsupported by C++ compilers as an extension, they were not supported by\nC++ prior to C++20.</p>\n\n<p>The rules in the C++ standard are stricter than in C and compiler extensions,\nrequiring that the designated initializers appear in the same order as the\nfields appear in the struct definition. So in the example above, it is legal\naccording to C++20 to initialize <code>x</code> and then <code>z</code>, but not\n<code>y</code> and then <code>x</code>.</p>\n\n<p class=\"decision\"></p>\n<p>Use designated initializers only in the form that is compatible with the\nC++20 standard: with initializers in the same order as the corresponding fields\nappear in the struct definition.</p>\n\n\n\n<h3 id=\"Lambda_expressions\">Lambda Expressions</h3>\n\n<p>Use lambda expressions where appropriate. Prefer explicit captures\nwhen the lambda will escape the current scope.</p>\n\n<p class=\"definition\"></p>\n<p> Lambda expressions are a concise way of creating anonymous\nfunction objects. They're often useful when passing\nfunctions as arguments. For example:</p>\n\n<pre class=\"neutralcode\">std::sort(v.begin(), v.end(), [](int x, int y) {\n  return Weight(x) &lt; Weight(y);\n});\n</pre>\n\n<p> They further allow capturing variables from the enclosing scope either\nexplicitly by name, or implicitly using a default capture. Explicit captures\nrequire each variable to be listed, as\neither a value or reference capture:</p>\n\n<pre class=\"neutralcode\">int weight = 3;\nint sum = 0;\n// Captures `weight` by value and `sum` by reference.\nstd::for_each(v.begin(), v.end(), [weight, &amp;sum](int x) {\n  sum += weight * x;\n});\n</pre>\n\n\n<p>Default captures implicitly capture any variable referenced in the\nlambda body, including <code>this</code> if any members are used:</p>\n\n<pre class=\"neutralcode\">const std::vector&lt;int&gt; lookup_table = ...;\nstd::vector&lt;int&gt; indices = ...;\n// Captures `lookup_table` by reference, sorts `indices` by the value\n// of the associated element in `lookup_table`.\nstd::sort(indices.begin(), indices.end(), [&amp;](int a, int b) {\n  return lookup_table[a] &lt; lookup_table[b];\n});\n</pre>\n\n<p>A variable capture can also have an explicit initializer, which can\n  be used for capturing move-only variables by value, or for other situations\n  not handled by ordinary reference or value captures:</p>\n  <pre class=\"neutralcode\">std::unique_ptr&lt;Foo&gt; foo = ...;\n[foo = std::move(foo)] () {\n  ...\n}</pre>\n<p>Such captures (often called \"init captures\" or \"generalized lambda captures\")\n  need not actually \"capture\" anything from the enclosing scope, or even have\n  a name from the enclosing scope; this syntax is a fully general way to define\n  members of a lambda object:</p>\n  <pre class=\"neutralcode\">[foo = std::vector&lt;int&gt;({1, 2, 3})] () {\n  ...\n}</pre>\n<p>The type of a capture with an initializer is deduced using the same rules\n  as <code>auto</code>.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Lambdas are much more concise than other ways of\n   defining function objects to be passed to STL\n   algorithms, which can be a readability\n   improvement.</li>\n\n  <li>Appropriate use of default captures can remove\n    redundancy and highlight important exceptions from\n    the default.</li>\n\n   <li>Lambdas, <code>std::function</code>, and\n   <code>std::bind</code> can be used in combination as a\n   general purpose callback mechanism; they make it easy\n   to write functions that take bound functions as\n   arguments.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>Variable capture in lambdas can be a source of dangling-pointer\n  bugs, particularly if a lambda escapes the current scope.</li>\n\n  <li>Default captures by value can be misleading because they do not prevent\n  dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep\n  copy, so it often has the same lifetime issues as capture by reference.\n  This is especially confusing when capturing <code>this</code> by value,\n  since the use of <code>this</code> is often implicit.</li>\n\n  <li>Captures actually declare new variables (whether or not the captures have\n    initializers), but they look nothing like any other variable declaration\n    syntax in C++. In particular, there's no place for the variable's type,\n    or even an <code>auto</code> placeholder (although init captures can\n    indicate it indirectly, e.g., with a cast). This can make it difficult to\n    even recognize them as declarations.</li>\n\n  <li>Init captures inherently rely on <a href=\"#Type_deduction\">type\n      deduction</a>, and suffer from many of the same drawbacks as\n    <code>auto</code>, with the additional problem that the syntax doesn't\n    even cue the reader that deduction is taking place.</li>\n\n  <li>It's possible for use of lambdas to get out of\n  hand; very long nested anonymous functions can make\n  code harder to understand.</li>\n\n</ul>\n\n<p class=\"decision\"></p>\n<ul>\n<li>Use lambda expressions where appropriate, with formatting as\ndescribed <a href=\"#Formatting_Lambda_Expressions\">below</a>.</li>\n<li>Prefer explicit captures if the lambda may escape the current scope.\nFor example, instead of:\n<pre class=\"badcode\">{\n  Foo foo;\n  ...\n  executor-&gt;Schedule([&amp;] { Frobnicate(foo); })\n  ...\n}\n// BAD! The fact that the lambda makes use of a reference to `foo` and\n// possibly `this` (if `Frobnicate` is a member function) may not be\n// apparent on a cursory inspection. If the lambda is invoked after\n// the function returns, that would be bad, because both `foo`\n// and the enclosing object could have been destroyed.\n</pre>\nprefer to write:\n<pre class=\"goodcode\">{\n  Foo foo;\n  ...\n  executor-&gt;Schedule([&amp;foo] { Frobnicate(foo); })\n  ...\n}\n// BETTER - The compile will fail if `Frobnicate` is a member\n// function, and it's clearer that `foo` is dangerously captured by\n// reference.\n</pre>\n</li>\n<li>Use default capture by reference (<code>[&amp;]</code>) only when\nthe lifetime of the lambda is obviously shorter than any potential\ncaptures.\n</li>\n<li>Use default capture by value (<code>[=]</code>) only as a means of\nbinding a few variables for a short lambda, where the set of captured\nvariables is obvious at a glance, and which does not result in\ncapturing <code>this</code> implicitly. (That means that a lambda that\nappears in a non-static class member function and refers to non-static\nclass members in its body must capture <code>this</code> explicitly or\nvia <code>[&amp;]</code>.) Prefer not to write long or complex lambdas\nwith default capture by value.\n</li>\n<li>Use captures only to actually capture variables from the enclosing scope.\n  Do not use captures with initializers to introduce new names, or\n  to substantially change the meaning of an existing name. Instead,\n  declare a new variable in the conventional way and then capture it,\n  or avoid the lambda shorthand and define a function object explicitly.</li>\n<li>See the section on <a href=\"#Type_deduction\">type deduction</a>\n  for guidance on specifying the parameter and return types.</li>\n\n</ul>\n\n<h3 id=\"Template_metaprogramming\">Template Metaprogramming</h3>\n\n<p>Avoid complicated template programming.</p>\n\n<p class=\"definition\"></p>\n<p>Template metaprogramming refers to a family of techniques that\nexploit the fact that the C++ template instantiation mechanism is\nTuring complete and can be used to perform arbitrary compile-time\ncomputation in the type domain.</p>\n\n<p class=\"pros\"></p>\n<p>Template metaprogramming allows extremely flexible interfaces that\nare type safe and high performance. Facilities like\n\n<a href=\"https://github.com/google/googletest\">GoogleTest</a>,\n<code>std::tuple</code>, <code>std::function</code>, and\nBoost.Spirit would be impossible without it.</p>\n\n<p class=\"cons\"></p>\n<p>The techniques used in template metaprogramming are often obscure\nto anyone but language experts. Code that uses templates in\ncomplicated ways is often unreadable, and is hard to debug or\nmaintain.</p>\n\n<p>Template metaprogramming often leads to extremely poor compile\ntime error messages: even if an interface is simple, the complicated\nimplementation details become visible when the user does something\nwrong.</p>\n\n<p>Template metaprogramming interferes with large scale refactoring by\nmaking the job of refactoring tools harder. First, the template code\nis expanded in multiple contexts, and it's hard to verify that the\ntransformation makes sense in all of them. Second, some refactoring\ntools work with an AST that only represents the structure of the code\nafter template expansion. It can be difficult to automatically work\nback to the original source construct that needs to be\nrewritten.</p>\n\n<p class=\"decision\"></p>\n<p>Template metaprogramming sometimes allows cleaner and easier-to-use\ninterfaces than would be possible without it, but it's also often a\ntemptation to be overly clever. It's best used in a small number of\nlow level components where the extra maintenance burden is spread out\nover a large number of uses.</p>\n\n<p>Think twice before using template metaprogramming or other\ncomplicated template techniques; think about whether the average\nmember of your team will be able to understand your code well enough\nto maintain it after you switch to another project, or whether a\nnon-C++ programmer or someone casually browsing the codebase will be\nable to understand the error messages or trace the flow of a function\nthey want to call.  If you're using recursive template instantiations\nor type lists or metafunctions or expression templates, or relying on\nSFINAE or on the <code>sizeof</code> trick for detecting function\noverload resolution, then there's a good chance you've gone too\nfar.</p>\n\n<p>If you use template metaprogramming, you should expect to put\nconsiderable effort into minimizing and isolating the complexity. You\nshould hide metaprogramming as an implementation detail whenever\npossible, so that user-facing headers are readable, and you should\nmake sure that tricky code is especially well commented. You should\ncarefully document how the code is used, and you should say something\nabout what the \"generated\" code looks like. Pay extra attention to the\nerror messages that the compiler emits when users make mistakes.  The\nerror messages are part of your user interface, and your code should\nbe tweaked as necessary so that the error messages are understandable\nand actionable from a user point of view.</p>\n\n<h3 id=\"Concepts\">Concepts and Constraints</h3>\n\n<p>Use concepts sparingly.\nIn general, concepts and constraints should only be used in cases\nwhere templates would have been used prior to C++20.\nAvoid introducing new concepts in headers,\nunless the headers are marked as internal to the library.\nDo not define concepts that are not enforced by the compiler.\nPrefer constraints over template metaprogramming, and\navoid the <code>template&lt;<i>Concept</i> T&gt;</code> syntax;\ninstead, use the <code>requires(<i>Concept&lt;T&gt;</i>)</code>\nsyntax.</p>\n\n<p class=\"definition\"></p>\n<p>The <code>concept</code> keyword is a new mechanism for defining\nrequirements (such as type traits or interface specifications)\nfor a template parameter.\nThe <code>requires</code> keyword provides mechanisms for placing\nanonymous constraints on templates and verifying that constraints\nare satisfied at compile time.\nConcepts and constraints are often used together, but can be\nalso used independently.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Concepts allow the compiler to generate much better error\n  messages when templates are involved, which can reduce confusion\n  and significantly improve the development experience.</li>\n  <li>Concepts can reduce the boilerplate necessary for defining\n  and using compile-time constraints, often increasing the clarity\n  of the resulting code.</li>\n  <li>Constraints provide some capabilities that are difficult to\n  achieve with templates and SFINAE techniques.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>As with templates, concepts can make code significantly more\n  complex and difficult to understand.</li>\n  <li>Concept syntax can be confusing to readers, as concepts\n  appear similar to class types at their usage sites.</li>\n  <li>Concepts, especially at API boundaries, increase code\n  coupling, rigidity, and ossification.</li>\n  <li>Concepts and constraints can replicate logic from a function\n  body, resulting in code duplication and increased maintenance\n  costs.</li>\n  <li>Concepts muddy the source of truth for their underlying\n  contracts, as they are standalone named entities that can be\n  utilized in multiple locations, all of which evolve separately\n  from each other.\n  This can cause the stated and implied requirements to diverge\n  over time.</li>\n  <li>Concepts and constraints affect overload resolution in novel\n  and non-obvious ways.</li>\n  <li>As with SFINAE, constraints make it harder to refactor code\n  at scale.</li>\n</ul>\n\n<p class=\"decision\"></p>\n<p>Predefined concepts in the standard library should be\npreferred to type traits, when equivalent ones exist.\n(e.g., if <code>std::is_integral_v</code> would have been used\nbefore C++20, then <code>std::integral</code> should be used in\nC++20 code.)\nSimilarly, prefer modern constraint syntax\n(via <code>requires(<i>Condition</i>)</code>).\nAvoid legacy template metaprogramming constructs\n(such as <code>std::enable_if&lt;<i>Condition</i>&gt;</code>)\nas well as the <code>template&lt;<i>Concept</i> T&gt;</code>\nsyntax.</p>\n\n<p>Do not manually re-implement any existing concepts or traits.\nFor example, use\n<code>requires(std::default_initializable&lt;T&gt;)</code>\ninstead of\n<code>requires(requires { T v; })</code>\nor the like.\n\n</p><p>New <code>concept</code> declarations should be rare, and only\ndefined internally within a library, such that they are not\nexposed at API boundaries.\nMore generally, do not use concepts or constraints in cases where\nyou wouldn't use their legacy template equivalents in C++17.\n</p>\n\n<p>Do not define concepts that duplicate the function body,\nor impose requirements that would be insignificant or obvious\nfrom reading the body of the code or the resulting error messages.\nFor example, avoid the following:\n</p><pre class=\"badcode\">template &lt;typename T&gt;     // Bad - redundant with negligible benefit\nconcept Addable = std::copyable&lt;T&gt; &amp;&amp; requires(T a, T b) { a + b; };\ntemplate &lt;Addable T&gt;\nT Add(T x, T y, T z) { return x + y + z; }\n</pre>\nInstead, prefer to leave code as an ordinary template unless\nyou can demonstrate that concepts result in significant\nimprovement for that particular case, such as in the resulting\nerror messages for a deeply nested or non-obvious\nrequirement.\n\n<p>Concepts should be statically verifiable by the compiler.\nDo not use any concept whose primary benefits would come from a\nsemantic (or otherwise unenforced) constraint.\nRequirements that are unenforced at compile time should instead\nbe imposed via other mechanisms such as comments, assertions,\nor tests.</p>\n\n<h3 id=\"modules\">C++20 modules</h3>\n\n<p>Do not use C++20 Modules.</p>\n\n<p>C++20 introduces \"modules\", a new language feature designed as an\nalternative to textual inclusion of header files. It introduces three\nnew keywords to support\nthis: <code>module</code>, <code>export</code>,\nand <code>import</code>.\n\n</p><p>Modules are a big shift in how C++ is written and compiled, and we\nare still assessing how they may fit into Google's C++ ecosystem in\nthe future. Furthermore, they are not currently well-supported by our\nbuild systems, compilers, and other tooling, and need further\nexploration as to the best practices when writing and using them.</p>\n\n\n\n<h3 id=\"coroutines\">Coroutines</h3>\n\n\n<p>Only use C++20 coroutines via libraries that have been\n  approved by your project leads.</p>\n\n<p class=\"definition\"></p>\n<p>C++20 introduced\n<a href=\"https://en.cppreference.com/w/cpp/language/coroutines.html\">coroutines</a>:\nfunctions that can suspend and resume\nexecuting later. They are especially convenient for asynchronous\nprogramming, where they can provide substantial improvements over\ntraditional callback-based frameworks.</p>\n\n<p>Unlike most other programming languages (Kotlin, Rust, TypeScript, etc.),\nC++ does not provide a concrete implementation of coroutines.\nInstead, it requires users to implement their own awaitable type (using a\n<a href=\"https://en.cppreference.com/w/cpp/language/coroutines#Promise\">\n  promise type</a>) which determines coroutine parameter types, how coroutines\nare executed, and allows running user-defined code during different stages\nof their execution.</p>\n\n<p class=\"pros\"></p>\n<ul>\n  <li>Coroutines can be used to implement safe and efficient libraries suited\n    for specific tasks, such as asynchronous programming.</li>\n  <li>Coroutines are syntactically almost identical to non-coroutine functions,\n    which can make them substantially more readable than alternatives.</li>\n  <li>The high degree of customization makes it possible to insert more\n    detailed debugging information into coroutines, compared to\n    alternatives.</li>\n</ul>\n\n<p class=\"cons\"></p>\n<ul>\n  <li>There is no standard coroutine promise type, and each user-defined\n    implementation is likely going to be unique in some aspect.</li>\n  <li>Because of load-bearing interactions between the return type, the\n    various customizable hooks in the promise type, and compiler-generated\n    code, coroutine semantics are extremely difficult to deduce from reading\n    user code.</li>\n  <li>The many customizable aspects of coroutines introduce a large number\n    of pitfalls, especially around dangling references and race\n    conditions.</li>\n</ul>\n\n<p>In summary, designing a high-quality and interoperable coroutine library\nrequires a large amount of difficult work, careful thought, and extensive\ndocumentation.</p>\n\n<p class=\"decision\"></p>\n\n\n\n<p>Use only coroutine libraries that have been approved for\n  project-wide use by your project leads. Do not roll your own promise or\n  awaitable types.</p>\n\n<h3 id=\"Boost\">Boost</h3>\n\n<p>Use only approved libraries from the Boost library\ncollection.</p>\n\n<p class=\"definition\"></p>\n<p> The\n<a href=\"https://www.boost.org/\">\nBoost library collection</a> is a popular collection of\npeer-reviewed, free, open-source C++ libraries.</p>\n\n<p class=\"pros\"></p>\n<p>Boost code is generally very high-quality, is widely\nportable, and fills many important gaps in the C++\nstandard library, such as type traits and better binders.</p>\n\n<p class=\"cons\"></p>\n<p>Some Boost libraries encourage coding practices which can\nhamper readability, such as metaprogramming and other\nadvanced template techniques, and an excessively\n\"functional\" style of programming. </p>\n\n<p class=\"decision\"></p>\n\n\n\n<div>\n<p>In order to maintain a high level of readability for\nall contributors who might read and maintain code, we\nonly allow an approved subset of Boost features.\nCurrently, the following libraries are permitted:</p>\n\n<ul>\n  <li>\n  <a href=\"https://www.boost.org/libs/utility/call_traits.htm\">\n  Call Traits</a> from <code>boost/call_traits.hpp</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/utility/compressed_pair.htm\">\n  Compressed Pair</a> from  <code>boost/compressed_pair.hpp</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/graph/\">\n  The Boost Graph Library (BGL)</a> from <code>boost/graph</code>,\n  except serialization (<code>adj_list_serialize.hpp</code>) and\n   parallel/distributed algorithms and data structures\n   (<code>boost/graph/parallel/*</code> and\n   <code>boost/graph/distributed/*</code>).</li>\n\n  <li><a href=\"https://www.boost.org/libs/property_map/\">\n  Property Map</a> from <code>boost/property_map</code>, except\n  parallel/distributed property maps (<code>boost/property_map/parallel/*</code>).</li>\n\n  <li><a href=\"https://www.boost.org/libs/iterator/\">\n  Iterator</a> from <code>boost/iterator</code></li>\n\n  <li>The part of <a href=\"https://www.boost.org/libs/polygon/\">\n  Polygon</a> that deals with Voronoi diagram\n  construction and doesn't depend on the rest of\n  Polygon:\n  <code>boost/polygon/voronoi_builder.hpp</code>,\n  <code>boost/polygon/voronoi_diagram.hpp</code>, and\n  <code>boost/polygon/voronoi_geometry_type.hpp</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/bimap/\">\n  Bimap</a> from <code>boost/bimap</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/math/doc/html/dist.html\">\n  Statistical Distributions and Functions</a> from\n  <code>boost/math/distributions</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/math/doc/html/special.html\">\n  Special Functions</a> from <code>boost/math/special_functions</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/math/doc/html/root_finding.html\">\n  Root Finding &amp; Minimization Functions</a> from <code>boost/math/tools</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/multi_index/\">\n  Multi-index</a> from <code>boost/multi_index</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/heap/\">\n  Heap</a> from <code>boost/heap</code></li>\n\n  <li>The flat containers from\n  <a href=\"https://www.boost.org/libs/container/\">Container</a>:\n  <code>boost/container/flat_map</code>, and\n  <code>boost/container/flat_set</code></li>\n\n  <li><a href=\"https://www.boost.org/libs/intrusive/\">Intrusive</a>\n  from <code>boost/intrusive</code>.</li>\n\n  <li><a href=\"https://www.boost.org/libs/sort/\">The\n  <code>boost/sort</code> library</a>.</li>\n\n  <li><a href=\"https://www.boost.org/libs/preprocessor/\">Preprocessor</a>\n  from <code>boost/preprocessor</code>.</li>\n</ul>\n\n<p>We are actively considering adding other Boost\nfeatures to the list, so this list may be expanded in\nthe future.</p>\n</div>\n\n\n\n\n<h3 id=\"Disallowed_Stdlib\">Disallowed standard library features</h3>\n\n\n<p>As with <a href=\"#Boost\">Boost</a>, some modern C++\nlibrary functionality encourages coding practices that hamper\nreadability — for example by removing\nchecked redundancy (such as type names) that may be\nhelpful to readers, or by encouraging template\nmetaprogramming. Other extensions duplicate functionality\navailable through existing mechanisms, which may lead to confusion\nand conversion costs.</p>\n\n<p class=\"decision\"></p>\n<p>The following C++ standard library features may not be used:</p>\n\n<ul>\n\n\n  <li>Compile-time rational numbers\n  (<code>&lt;ratio&gt;</code>), because of concerns that\n  it's tied to a more template-heavy interface\n  style.</li>\n\n  <li>The <code>&lt;cfenv&gt;</code> and\n  <code>&lt;fenv.h&gt;</code> headers, because many\n  compilers do not support those features reliably.</li>\n\n  <li>The <code>&lt;filesystem&gt;</code> header, which\n\n  does not have sufficient support for testing, and suffers\n  from inherent security vulnerabilities.</li>\n\n\n</ul>\n\n<h3 id=\"Nonstandard_Extensions\">Nonstandard Extensions</h3>\n\n<p>Nonstandard extensions to C++ may not be used unless otherwise specified.</p>\n\n<p class=\"definition\"></p>\n<p>Compilers support various extensions that are not part of standard C++. Such\n  extensions include GCC's <code>__attribute__</code>, intrinsic functions such\n  as <code>__builtin_prefetch</code> or SIMD, <code>#pragma</code>, inline\n  assembly, <code>__COUNTER__</code>, <code>__PRETTY_FUNCTION__</code>,\n  compound statement expressions (e.g., <code>foo = ({ int x; Bar(&amp;x); x\n    })</code>, variable-length arrays and <code>alloca()</code>, and the\n   \"<a href=\"https://en.wikipedia.org/wiki/Elvis_operator\">Elvis\n     Operator</a>\" <code>a?:b</code>.</p>\n\n<p class=\"pros\"></p>\n  <ul>\n    <li>Nonstandard extensions may provide useful features that do not exist\n      in standard C++.</li>\n    <li>Important performance guidance to the compiler can only be specified\n      using extensions.</li>\n  </ul>\n\n<p class=\"cons\"></p>\n  <ul>\n    <li>Nonstandard extensions do not work in all compilers. Use of nonstandard\n      extensions reduces portability of code.</li>\n    <li>Even if they are supported in all targeted compilers, the extensions\n      are often not well-specified, and there may be subtle behavior differences\n      between compilers.</li>\n    <li>Nonstandard extensions add features to the language that a reader must\n      know to understand the code.</li>\n    <li>Nonstandard extensions require additional work to port across architectures.</li>\n  </ul>\n\n<p class=\"decision\"></p>\n<p>Do not use nonstandard extensions. You may use portability wrappers that\n  are implemented using nonstandard extensions, so long as those wrappers\n\n  are provided by a designated project-wide portability\n    header.</p>\n\n<h3 id=\"Aliases\">Aliases</h3>\n\n<p>Public aliases are for the benefit of an API's user, and should be clearly documented.</p>\n\n<p class=\"definition\"></p>\n<p>There are several ways to create names that are aliases of other entities:</p>\n<pre class=\"neutralcode\">using Bar = Foo;\ntypedef Foo Bar;  // But prefer `using` in C++ code.\nusing ::other_namespace::Foo;\nusing enum MyEnumType;  // Creates aliases for all enumerators in MyEnumType.\n</pre>\n\n  <p>In new code, <code>using</code> is preferable to <code>typedef</code>,\n  because it provides a more consistent syntax with the rest of C++ and works\n  with templates.</p>\n\n  <p>Like other declarations, aliases declared in a header file are part of that\n  header's public API unless they're in a function definition, in the private portion of a class,\n  or in an explicitly-marked internal namespace. Aliases in such areas or in <code>.cc</code> files\n  are implementation details (because client code can't refer to them), and are not restricted by\n  this rule.</p>\n\n<p class=\"pros\"></p>\n  <ul>\n    <li>Aliases can improve readability by simplifying a long or complicated name.</li>\n    <li>Aliases can reduce duplication by naming in one place a type used repeatedly in an API,\n      which <em>might</em> make it easier to change the type later.\n    </li>\n  </ul>\n\n<p class=\"cons\"></p>\n  <ul>\n    <li>When placed in a header where client code can refer to them, aliases increase the\n      number of entities in that header's API, increasing its complexity.</li>\n    <li>Clients can easily rely on unintended details of public aliases, making\n      changes difficult.</li>\n    <li>It can be tempting to create a public alias that is only intended for use\n      in the implementation, without considering its impact on the API, or on maintainability.</li>\n    <li>Aliases can create risk of name collisions.</li>\n    <li>Aliases can reduce readability by giving a familiar construct an unfamiliar name.</li>\n    <li>Type aliases can create an unclear API contract:\n      it is unclear whether the alias is guaranteed to be identical to the type it aliases,\n      to have the same API, or only to be usable in specified narrow ways.</li>\n  </ul>\n\n<p class=\"decision\"></p>\n<p>Don't put an alias in your public API just to save typing in the implementation;\n  do so only if you intend it to be used by your clients.</p>\n<p>When defining a public alias, document the intent of\nthe new name, including whether it is guaranteed to always be the same as the type\nit's currently aliased to, or whether a more limited compatibility is\nintended. This lets the user know whether they can treat the types as\nsubstitutable or whether more specific rules must be followed, and can help the\nimplementation retain some degree of freedom to change the alias.</p>\n<p>Don't put namespace aliases in your public API. (See also <a href=\"#Namespaces\">Namespaces</a>.)\n</p>\n\n<p>For example, these aliases document how they are intended to be used in client code:</p>\n<pre class=\"goodcode\">namespace mynamespace {\n// Used to store field measurements. DataPoint may change from Bar* to some internal type.\n// Client code should treat it as an opaque pointer.\nusing DataPoint = ::foo::Bar*;\n\n// A set of measurements. Just an alias for user convenience.\nusing TimeSeries = std::unordered_set&lt;DataPoint, std::hash&lt;DataPoint&gt;, DataPointComparator&gt;;\n}  // namespace mynamespace\n</pre>\n\n<p>These aliases don't document intended use, and half of them aren't meant for client use:</p>\n\n<pre class=\"badcode\">namespace mynamespace {\n// Bad: none of these say how they should be used.\nusing DataPoint = ::foo::Bar*;\nusing ::std::unordered_set;  // Bad: just for local convenience\nusing ::std::hash;           // Bad: just for local convenience\ntypedef unordered_set&lt;DataPoint, hash&lt;DataPoint&gt;, DataPointComparator&gt; TimeSeries;\n}  // namespace mynamespace\n</pre>\n\n<p>However, local convenience aliases are fine in function definitions, <code>private</code>\n  sections of classes, explicitly-marked internal namespaces, and in <code>.cc</code> files:</p>\n\n<pre class=\"goodcode\">// In a .cc file\nusing ::foo::Bar;\n</pre>\n\n<h3 id=\"Switch_Statements\">Switch Statements</h3>\n\n<p>If not conditional on an enumerated value, switch statements should always\nhave a <code>default</code> case (in the case of an enumerated value, the\ncompiler will warn you if any values are not handled). If the default case\nshould never execute, treat this as an error. For example:\n\n</p><pre class=\"goodcode\">switch (var) {\n  case 0: {\n    ...\n    break;\n  }\n  case 1: {\n    ...\n    break;\n  }\n  default: {\n    LOG(FATAL) &lt;&lt; \"Invalid value in switch statement: \" &lt;&lt; var;\n  }\n}\n</pre>\n\n<p>Fall-through from one case label to another must be annotated using the\n<code>[[fallthrough]];</code> attribute. <code>[[fallthrough]];</code> should\nbe placed at a point of execution where a fall-through to the next case label\noccurs. A common exception is consecutive case labels without intervening code,\nin which case no annotation is needed.</p>\n\n<pre class=\"goodcode\">switch (x) {\n  case 41:  // No annotation needed here.\n  case 43:\n    if (dont_be_picky) {\n      // Use this instead of or along with annotations in comments.\n      [[fallthrough]];\n    } else {\n      CloseButNoCigar();\n      break;\n    }\n  case 42:\n    DoSomethingSpecial();\n    [[fallthrough]];\n  default:\n    DoSomethingGeneric();\n    break;\n}\n</pre>\n\n<h2 id=\"Inclusive_Language\">Inclusive Language</h2>\n\n<p>In all code, including naming and comments, use inclusive language\nand avoid terms that other programmers might find disrespectful or offensive\n(such as \"master\" and \"slave\", \"blacklist\" and \"whitelist\", or \"redline\"),\neven if the terms also have an ostensibly neutral meaning.\nSimilarly, use gender-neutral language unless you're referring\nto a specific person (and using their pronouns). For example,\nuse \"they\"/\"them\"/\"their\" for people of unspecified gender\n(<a href=\"https://apastyle.apa.org/style-grammar-guidelines/grammar/singular-they\">even\nwhen singular</a>), and \"it\"/\"its\" for software, computers, and other\nthings that aren't people.</p>\n\n\n\n<h2 id=\"Naming\">Naming</h2>\n\n<p>The most important consistency rules are those that govern\nnaming. The style of a name immediately informs us what sort of\nthing the named entity is: a type, a variable, a function, a\nconstant, a macro, etc., without requiring us to search for the\ndeclaration of that entity. The pattern-matching engine in our\nbrains relies a great deal on these naming rules.\n</p>\n\n<p>Style rules about naming are pretty arbitrary, but\n we feel that\nconsistency is more important than individual preferences in this\narea, so regardless of whether you find them sensible or not,\nthe rules are the rules.</p>\n\n<p>For the purposes of the naming rules below, a \"word\" is anything that you\nwould write in English without internal spaces. Either words are all lowercase,\nwith underscores between words\n(\"<a href=\"https://en.wikipedia.org/wiki/Snake_case\">snake_case</a>\"), or words\nare mixed case with the first letter of each word capitalized\n(\"<a href=\"https://en.wikipedia.org/wiki/Camel_case\">camelCase</a>\" or\n\"<a href=\"https://en.wiktionary.org/wiki/Pascal_case\">PascalCase</a>\").\n\n</p><h3 id=\"General_Naming_Rules\">Choosing Names</h3>\n\n<p>Give things names that make their purpose or intent understandable to a new\nreader, even someone on a different team than the owners. Do not worry about\nsaving horizontal space as it is far more important to make your code\nimmediately understandable by a new reader.</p>\n\n<p>Consider the context in which the name will be used. A name should be\ndescriptive even if it is used far from the code that makes it available for\nuse. However, a name should not distract the reader by repeating information\nthat's present in the immediate context. Generally, this means that\ndescriptiveness should be proportional to the name's scope of visibility. A free\nfunction declared in a header should probably mention the header's library,\nwhile a local variable probably shouldn't explain what function it's within.</p>\n\n<p>Minimize the use of abbreviations that would likely be unknown to someone\noutside your project (especially acronyms and initialisms). Do not abbreviate by\ndeleting letters within a word. When an abbreviation is used, prefer to\ncapitalize it as a single \"word\", e.g., <code>StartRpc()</code> rather than\n<code>StartRPC()</code>. As a rule of thumb, an abbreviation is probably OK\nif it's listed in\n\nWikipedia. Note that certain universally-known abbreviations are OK, such as\n<code>i</code> for a loop index and <code>T</code> for a template\nparameter.</p>\n\n<p>The names you see most frequently are not like most names; a small number of\n\"vocabulary\" names are reused so widely that they are always in context. These\nnames tend to be short or even abbreviated and their full meaning comes from\nexplicit long-form documentation rather than from just comments on their\ndefinition and the words within the names. For example, <code>absl::Status</code>\nhas a dedicated\n\n<a href=\"https://abseil.io/docs/cpp/guides/status\">page\nin a devguide</a>,\ndocumenting its proper use. You probably won't define new vocabulary names very\noften, but if you do, get\nadditional design review to make sure the chosen names work well when\nused widely.</p>\n\n<pre class=\"goodcode\">class MyClass {\n public:\n  int CountFooErrors(const std::vector&lt;Foo&gt;&amp; foos) {\n    int n = 0;  // Clear meaning given limited scope and context\n    for (const auto&amp; foo : foos) {\n      ...\n      ++n;\n    }\n    return n;\n  }\n  // Function comment doesn't need to explain that this returns non-OK on\n  // failure as that is implied by the `absl::Status` return type, but it\n  // might document behavior for some specific codes.\n  absl::Status DoSomethingImportant() {\n    std::string fqdn = ...;  // Well-known abbreviation for Fully Qualified Domain Name\n    return absl::OkStatus();\n  }\n private:\n  const int kMaxAllowedConnections = ...;  // Clear meaning within context\n};\n</pre>\n\n<pre class=\"badcode\">class MyClass {\n public:\n  int CountFooErrors(const std::vector&lt;Foo&gt;&amp; foos) {\n    int total_number_of_foo_errors = 0;  // Overly verbose given limited scope and context\n    for (int foo_index = 0; foo_index &lt; foos.size(); ++foo_index) {  // Use idiomatic `i`\n      ...\n      ++total_number_of_foo_errors;\n    }\n    return total_number_of_foo_errors;\n  }\n  // A return type with a generic name is unclear without widespread education.\n  Result DoSomethingImportant() {\n    int cstmr_id = ...;  // Deletes internal letters\n  }\n private:\n  const int kNum = ...;  // Unclear meaning within broad scope\n};\n</pre>\n\n<h3 id=\"File_Names\">File Names</h3>\n\n<p>Filenames should be all lowercase and can include\nunderscores (<code>_</code>) or dashes (<code>-</code>).\nFollow the convention that your\n\nproject uses. If there is no consistent\nlocal pattern to follow, prefer \"<code>_</code>\".</p>\n\n<p>Examples of acceptable file names:</p>\n\n<ul>\n  <li><code>my_useful_class.cc</code></li>\n  <li><code>my-useful-class.cc</code></li>\n  <li><code>myusefulclass.cc</code></li>\n  <li><code>myusefulclass_test.cc // _unittest and _regtest are deprecated.</code></li>\n</ul>\n\n<p>C++ files should have a <code>.cc</code> filename extension, and header files\nshould have a <code>.h</code> extension. Files that rely on being textually included at specific points\nshould end in <code>.inc</code> (see also the section on\n<a href=\"#Self_contained_Headers\">self-contained headers</a>).</p>\n\n<p>Do not use filenames that already exist in\n<code>/usr/include</code>, such as <code>db.h</code>.</p>\n\n<p>In general, make your filenames very specific. For\nexample, use <code>http_server_logs.h</code> rather than\n<code>logs.h</code>. A very common case is to have a pair\nof files called, e.g., <code>foo_bar.h</code> and\n<code>foo_bar.cc</code>, defining a class called\n<code>FooBar</code>.</p>\n\n<h3 id=\"Type_Names\">Type Names</h3>\n\n<p>Type names start with a capital letter and have a capital\nletter for each new word, with no underscores:\n<code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.</p>\n\n<p>The names of all types — classes, structs, type aliases,\nenums, and type template parameters — have the same naming convention.\nType names should start with a capital letter and have a capital letter\nfor each new word. No underscores. For example:</p>\n\n<pre class=\"goodcode\">// classes and structs\nclass UrlTable { ...\nclass UrlTableTester { ...\nstruct UrlTableProperties { ...\n\n// typedefs\ntypedef hash_map&lt;UrlTableProperties*, std::string&gt; PropertiesMap;\n\n// using aliases\nusing PropertiesMap = hash_map&lt;UrlTableProperties*, std::string&gt;;\n\n// enums\nenum class UrlTableError { ...\n</pre>\n\n<h3 id=\"Concept_Names\">Concept Names</h3>\n\nConcept names follow the same rules as <a href=\"#Type_Names\">type names</a>.\n\n<h3 id=\"Variable_Names\">Variable Names</h3>\n\n<p>The names of variables (including function parameters) and data members are\n<code>snake_case</code> (all lowercase, with underscores between words). Data members of classes\n(but not structs) additionally have trailing underscores. For instance:\n<code>a_local_variable</code>, <code>a_struct_data_member</code>,\n<code>a_class_data_member_</code>.</p>\n\n<h4>Common Variable names</h4>\n\n<p>For example:</p>\n\n<pre class=\"goodcode\">std::string table_name;  // OK - snake_case.\n</pre>\n\n<pre class=\"badcode\">std::string tableName;   // Bad - mixed case.\n</pre>\n\n<h4>Class Data Members</h4>\n\n<p>Data members of classes, both static and non-static, are\nnamed like ordinary nonmember variables, but with a\ntrailing underscore. The exception to this is static constant\nclass members, which should follow the rules for\n<a href=\"#Constant_Names\">naming constants</a>.</p>\n\n<pre class=\"goodcode\">class TableInfo {\n public:\n  ...\n  static const int kTableVersion = 3;  // OK - constant naming.\n  ...\n\n private:\n  std::string table_name_;             // OK - underscore at end.\n  static Pool&lt;TableInfo&gt;* pool_;       // OK.\n};\n</pre>\n\n<h4>Struct Data Members</h4>\n\n<p>Data members of structs, both static and non-static,\nare named like ordinary nonmember variables. They do not have\nthe trailing underscores that data members in classes have.</p>\n\n<pre class=\"goodcode\">struct UrlTableProperties {\n  std::string name;\n  int num_entries;\n  static Pool&lt;UrlTableProperties&gt;* pool;\n};\n</pre>\n\n\n<p>See <a href=\"#Structs_vs._Classes\">Structs vs.\nClasses</a> for a discussion of when to use a struct\nversus a class.</p>\n\n<h3 id=\"Constant_Names\">Constant Names</h3>\n\n<p>Variables declared <code>constexpr</code> or <code>const</code>, and whose value is fixed for\nthe duration of the program, are named with a leading \"k\" followed\nby mixed case. Underscores can be used as separators in the rare cases\nwhere capitalization cannot be used for separation. For example:</p>\n\n<pre class=\"goodcode\">const int kDaysInAWeek = 7;\nconst int kAndroid8_0_0 = 24;  // Android 8.0.0\n</pre>\n\n<p>All such variables with static storage duration (i.e., statics and globals,\nsee <a href=\"http://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration\">\nStorage Duration</a> for details) should be named this way, including those that are static constant\nclass data members and those in templates where different instantiations of the template\nmay have different values.  This convention is optional for variables of other storage classes,\ne.g., automatic variables; otherwise the usual variable naming rules apply. For example:</p>\n\n<pre class=\"goodcode\">void ComputeFoo(absl::string_view suffix) {\n  // Either of these is acceptable.\n  const absl::string_view kPrefix = \"prefix\";\n  const absl::string_view prefix = \"prefix\";\n  ...\n}\n</pre>\n\n<pre class=\"badcode\">void ComputeFoo(absl::string_view suffix) {\n  // Bad - different invocations of ComputeFoo give kCombined different values.\n  const std::string kCombined = absl::StrCat(kPrefix, suffix);\n  ...\n}\n</pre>\n\n<h3 id=\"Function_Names\">Function Names</h3>\n\n<p>Ordinarily, functions follow <a href=\"https://en.wiktionary.org/wiki/Pascal_case\">PascalCase</a>:\nstart with a capital letter and have a capital letter for each new word.</p>\n\n<pre class=\"goodcode\">AddTableEntry()\nDeleteUrl()\nOpenFileOrDie()\n</pre>\n\n<p>The same naming rule applies to class- and namespace-scope\nconstants that are exposed as part of an API and that are intended to look\nlike functions, because the fact that they're objects rather than functions\nis an unimportant implementation detail.</p>\n\n<p>Accessors and mutators (get and set functions) may be named like variables,\nin <code>snake_case</code>. These often correspond to actual member variables,\nbut this is not required. For example, <code>int count()</code> and\n<code>void set_count(int count)</code>.</p>\n\n<h3 id=\"Namespace_Names\">Namespace Names</h3>\n\n<p>Namespace names are <code>snake_case</code> (all lowercase, with underscores\nbetween words).</p>\n\n<p>When <a href=\"#General_Naming_Rules\">choosing names</a> for namespaces, note\nthat names must be fully qualified when used in a header outside the namespace,\nbecause <a href=\"#Aliases\">unqualified Aliases are generally banned</a>.</p>\n\n<p>Top-level namespaces must be globally unique and recognizable, so each one\nshould be owned by a single project or team, with a name based on the name of\nthat project or team. Usually, all code in the namespace should be under one or\nmore directories with the same name as the namespace.</p>\n\n<p>Nested namespaces should avoid the names of well-known top-level namespaces,\nespecially <code>std</code> and <code>absl</code>, because in C++, nested\nnamespaces do not protect from collisions with names in other namespaces\n(see <a href=\"https://abseil.io/tips/130\">TotW #130</a>).</p>\n\n<h3 id=\"Enumerator_Names\">Enumerator Names</h3>\n\n<p>Enumerators (for both scoped and unscoped enums) should be named like\n<a href=\"#Constant_Names\">constants</a>, not like\n<a href=\"#Macro_Names\">macros</a>. That is, use <code>kEnumName</code> not\n<code>ENUM_NAME</code>.</p>\n\n\n\n<pre class=\"goodcode\">enum class UrlTableError {\n  kOk = 0,\n  kOutOfMemory,\n  kMalformedInput,\n};\n</pre>\n<pre class=\"badcode\">enum class AlternateUrlTableError {\n  OK = 0,\n  OUT_OF_MEMORY = 1,\n  MALFORMED_INPUT = 2,\n};\n</pre>\n\n<p>Until January 2009, the style was to name enum values\nlike <a href=\"#Macro_Names\">macros</a>. This caused\nproblems with name collisions between enum values and\nmacros. Hence, the change to prefer constant-style naming\nwas put in place. New code should use constant-style\nnaming.</p>\n\n\n\n<h3 id=\"Template_Parameter_Names\">Template Parameter Names</h3>\n\n<p>Template parameters should follow the naming style for their\ncategory: type template parameters should follow the rules for naming\n<a href=\"#Type_Names\">types</a>, and non-type template\nparameters should follow the rules for naming <a href=\"#Variable_Names\">\nvariables</a> or <a href=\"#Constant_Names\">constants</a>.\n\n</p><h3 id=\"Macro_Names\">Macro Names</h3>\n\n<p>You're not really going to <a href=\"#Preprocessor_Macros\">\ndefine a macro</a>, are you? If you do, they're like this:\n<code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE</code>.\n</p>\n\n<p>Please see the <a href=\"#Preprocessor_Macros\">description\nof macros</a>; in general macros should <em>not</em> be used.\nHowever, if they are absolutely needed, then they should be\nnamed with all capitals and underscores, and with a project-specific prefix.</p>\n\n<pre class=\"neutralcode\">#define MYPROJECT_ROUND(x) ...\n</pre>\n\n<h3 id=\"Naming_Aliases\">Aliases</h3>\n\n<p>The name for an <a href=\"#Aliases\">alias</a> follows the same principles as\nany other new name, applied in the context where the alias is defined rather\nthan where the original name appears.</p>\n\n<h3 id=\"Exceptions_to_Naming_Rules\">Exceptions to Naming Rules</h3>\n\n<p>If you are naming something that is analogous to an existing C or C++\nentity (or a Rust entity via interop), then you can follow the existing\nnaming convention scheme.</p>\n\n<dl>\n  <dt><code>bigopen()</code></dt>\n  <dd>function name, follows form of <code>open()</code></dd>\n\n  <dt><code>uint</code></dt>\n  <dd><code>typedef</code></dd>\n\n  <dt><code>bigpos</code></dt>\n  <dd><code>struct</code> or <code>class</code>, follows\n  form of <code>pos</code></dd>\n\n  <dt><code>sparse_hash_map</code></dt>\n  <dd>STL-like entity; follows STL naming conventions</dd>\n\n  <dt><code>LONGLONG_MAX</code></dt>\n  <dd>a constant, as in <code>INT_MAX</code></dd>\n</dl>\n\n<h2 id=\"Comments\">Comments</h2>\n\n<p>Comments are absolutely vital to keeping our code readable. The following rules describe what you\nshould comment and where. But remember: while comments are very important, the best code is\nself-documenting. Giving sensible names to types and variables is much better than using obscure\nnames that you must then explain through comments.</p>\n\n<p>When writing your comments, write for your audience: the\nnext\ncontributor who will need to\nunderstand your code. Be generous — the next\none may be you!</p>\n\n<h3 id=\"Comment_Style\">Comment Style</h3>\n\n<p>Use either the <code>//</code> or <code>/* */</code>\nsyntax, as long as you are consistent.</p>\n\n<p>While either syntax is acceptable, <code>//</code> is\n<em>much</em> more common. Be consistent with how you\ncomment and what style you use where.</p>\n\n<h3 id=\"File_Comments\">File Comments</h3>\n\n<div>\n<p>Start each file with license boilerplate.</p>\n</div>\n\n<p>If a source file (such as a <code>.h</code> file) declares multiple user-facing abstractions\n(common functions, related classes, etc.), include a comment describing the collection of those\nabstractions. Include enough detail for future authors to know what does not fit there. However,\nthe detailed documentation about individual abstractions belongs with those abstractions, not at the\nfile level.</p>\n\n<p>For instance, if you write a file comment for <code>frobber.h</code>, you do not need\nto include a file comment in <code>frobber.cc</code> or\n<code>frobber_test.cc</code>. On the other hand, if you write a collection of classes in\n<code>registered_objects.cc</code> that has no associated header file, you must include a file\ncomment in <code>registered_objects.cc</code>.\n\n</p><h4>Legal Notice and Author Line</h4>\n\n\n\n<div>\n<p>Every file should contain license\nboilerplate. Choose the appropriate boilerplate for the\nlicense used by the project (for example, Apache 2.0,\nBSD, LGPL, GPL).</p>\n</div>\n\n<p>If you make significant changes to a file with an\nauthor line, consider deleting the author line.\nNew files should usually not contain copyright notice or\nauthor line.</p>\n\n<h3 id=\"Class_Comments\">Struct and Class Comments</h3>\n\n<p>Every non-obvious class or struct declaration should have an\naccompanying comment that describes what it is for and how it should\nbe used.</p>\n\n<pre class=\"goodcode\">// Iterates over the contents of a GargantuanTable.\n// Example:\n//    std::unique_ptr&lt;GargantuanTableIterator&gt; iter = table-&gt;NewIterator();\n//    for (iter-&gt;Seek(\"foo\"); !iter-&gt;done(); iter-&gt;Next()) {\n//      process(iter-&gt;key(), iter-&gt;value());\n//    }\nclass GargantuanTableIterator {\n  ...\n};\n</pre>\n\n<h4 id=\"Class_Comments_Details\">Class Comments</h4>\n\n<p>The class comment should provide the reader with enough information to know\nhow and when to use the class, as well as any additional considerations\nnecessary to correctly use the class. Document the synchronization assumptions\nthe class makes, if any. If an instance of the class can be accessed by\nmultiple threads, take extra care to document the rules and invariants\nsurrounding multithreaded use.</p>\n\n<p>The class comment is often a good place for a small example code snippet\ndemonstrating a simple and focused usage of the class.</p>\n\n<p>When sufficiently separated (e.g., <code>.h</code> and <code>.cc</code>\nfiles), comments describing the use of the class should go together with its\ninterface definition; comments about the class operation and implementation\nshould accompany the implementation of the class's methods.</p>\n\n<h3 id=\"Function_Comments\">Function Comments</h3>\n\n<p>Declaration comments describe use of the function (when it is\nnon-obvious); comments at the definition of a function describe\noperation.</p>\n\n<h4>Function Declarations</h4>\n\n<p>Almost every function declaration should have comments immediately\npreceding it that describe what the function does and how to use\nit. These comments may be omitted only if the function is simple and\nobvious (e.g., simple accessors for obvious properties of the class).\nPrivate methods and functions declared in <code>.cc</code> files are not exempt.\nFunction comments should be written with an implied subject of\n<i>This function</i> and should start with the verb phrase; for example,\n\"Opens the file\", rather than \"Open the file\". In general, these comments do not\ndescribe how the function performs its task. Instead, that should be\nleft to comments in the function definition.</p>\n\n<p>Types of things to mention in comments at the function\ndeclaration:</p>\n\n<ul>\n  <li>What the inputs and outputs are. If function argument names\n      are provided in `backticks`, then code-indexing\n      tools may be able to present the documentation better.</li>\n\n  <li>For class member functions: whether the object remembers\n  reference or pointer arguments beyond the duration of the method\n  call. This is quite common for pointer/reference arguments to\n  constructors.</li>\n\n  <li>For each pointer argument, whether it is allowed to be null and what happens\n  if it is.</li>\n\n  <li>For each output or input/output argument, what happens to any state that argument\n    is in (e.g., is the state appended to or overwritten?).\n\n  </li><li>If there are any performance implications of how a\n  function is used.</li>\n</ul>\n\n<p>Here is an example:</p>\n\n<pre class=\"goodcode\">// Returns an iterator for this table, positioned at the first entry\n// lexically greater than or equal to `start_word`. If there is no\n// such entry, returns a null pointer. The client must not use the\n// iterator after the underlying GargantuanTable has been destroyed.\n//\n// This method is equivalent to:\n//    std::unique_ptr&lt;Iterator&gt; iter = table-&gt;NewIterator();\n//    iter-&gt;Seek(start_word);\n//    return iter;\nstd::unique_ptr&lt;Iterator&gt; GetIterator(absl::string_view start_word) const;\n</pre>\n\n<p>However, do not be unnecessarily verbose or state the\ncompletely obvious.</p>\n\n<p>When documenting function overrides, focus on the\nspecifics of the override itself, rather than repeating\nthe comment from the overridden function.  In many of these\ncases, the override needs no additional documentation and\nthus no comment is required.</p>\n\n<p>When commenting constructors and destructors, remember\nthat the person reading your code knows what constructors\nand destructors are for, so comments that just say\nsomething like \"destroys this object\" are not useful.\nDocument what constructors do with their arguments (for\nexample, if they take ownership of pointers), and what\ncleanup the destructor does. If this is trivial, just\nskip the comment. It is quite common for destructors not\nto have a header comment.</p>\n\n<h4>Function Definitions</h4>\n\n<p>If there is anything tricky about how a function does\nits job, the function definition should have an\nexplanatory comment. For example, in the definition\ncomment you might describe any coding tricks you use,\ngive an overview of the steps you go through, or explain\nwhy you chose to implement the function in the way you\ndid rather than using a viable alternative. For instance,\nyou might mention why it must acquire a lock for the\nfirst half of the function but why it is not needed for\nthe second half.</p>\n\n<p>Note you should <em>not</em> just repeat the comments\ngiven with the function declaration, in the\n<code>.h</code> file or wherever. It's okay to\nrecapitulate briefly what the function does, but the\nfocus of the comments should be on how it does it.</p>\n\n<h3 id=\"Variable_Comments\">Variable Comments</h3>\n\n<p>In general the actual name of the variable should be\ndescriptive enough to give a good idea of what the variable\nis used for. In certain cases, more comments are required.</p>\n\n<h4>Class Data Members</h4>\n\n<p>The purpose of each class data member (also called an instance\nvariable or member variable) must be clear. If there are any\ninvariants (special values, relationships between members, lifetime\nrequirements) not clearly expressed by the type and name, they must be\ncommented. However, if the type and name suffice (<code>int\nnum_events_;</code>), no comment is needed.</p>\n\n<p>In particular, add comments to describe the existence and meaning\nof sentinel values, such as nullptr or -1, when they are not\nobvious. For example:</p>\n\n<pre class=\"goodcode\">private:\n // Used to bounds-check table accesses. -1 means\n // that we don't yet know how many entries the table has.\n int num_total_entries_;\n</pre>\n\n<h4>Global Variables</h4>\n\n<p>All global variables should have a comment describing what they\nare, what they are used for, and (if unclear) why they need to be\nglobal. For example:</p>\n\n<pre class=\"goodcode\">// The total number of test cases that we run through in this regression test.\nconst int kNumTestCases = 6;\n</pre>\n\n<h3 id=\"Implementation_Comments\">Implementation Comments</h3>\n\n<p>In your implementation you should have comments in tricky,\nnon-obvious, interesting, or important parts of your code.</p>\n\n<h4>Explanatory Comments</h4>\n\n<p>Tricky or complicated code blocks should have comments\nbefore them.</p>\n\n<h4 class=\"stylepoint_subsection\" id=\"Function_Argument_Comments\">Function Argument Comments</h4>\n\n<p>When the meaning of a function argument is nonobvious, consider\none of the following remedies:</p>\n\n<ul>\n  <li>If the argument is a literal constant, and the same constant is\n  used in multiple function calls in a way that tacitly assumes they're\n  the same, you should use a named constant to make that constraint\n  explicit, and to guarantee that it holds.</li>\n\n  <li>Consider changing the function signature to replace a <code>bool</code>\n  argument with an <code>enum</code> argument. This will make the argument\n  values self-describing.</li>\n\n  <li>For functions that have several configuration options, consider\n  defining a single class or struct to hold all the options\n  ,\n  and pass an instance of that.\n  This approach has several advantages. Options are referenced by name\n  at the call site, which clarifies their meaning. It also reduces\n  function argument count, which makes function calls easier to read and\n  write. As an added benefit, you don't have to change call sites when\n  you add another option.\n  </li>\n\n  <li>Replace large or complex nested expressions with named variables.</li>\n\n  <li>As a last resort, use comments to clarify argument meanings at the\n  call site. </li>\n</ul>\n\nConsider the following example:\n\n<pre class=\"badcode\">// What are these arguments?\nconst DecimalNumber product = CalculateProduct(values, 7, false, nullptr);\n</pre>\n\n<p>versus:</p>\n\n<pre class=\"goodcode\">ProductOptions options;\noptions.set_precision_decimals(7);\noptions.set_use_cache(ProductOptions::kDontUseCache);\nconst DecimalNumber product =\n    CalculateProduct(values, options, /*completion_callback=*/nullptr);\n</pre>\n\n<h4 id=\"Implementation_Comment_Donts\">Don'ts</h4>\n\n<p>Do not state the obvious. In particular, don't literally describe what\ncode does, unless the behavior is nonobvious to a reader who understands\nC++ well. Instead, provide higher-level comments that describe <i>why</i>\nthe code does what it does, or make the code self-describing.</p>\n\nCompare this:\n\n<pre class=\"badcode\">// Find the element in the vector.  &lt;-- Bad: obvious!\nif (std::find(v.begin(), v.end(), element) != v.end()) {\n  Process(element);\n}\n</pre>\n\nTo this:\n\n<pre class=\"goodcode\">// Process \"element\" unless it was already processed.\nif (std::find(v.begin(), v.end(), element) != v.end()) {\n  Process(element);\n}\n</pre>\n\n<p>Self-describing code doesn't need a comment. The comment from\nthe example above would be obvious:</p>\n\n<pre class=\"goodcode\">if (!IsAlreadyProcessed(element)) {\n  Process(element);\n}\n</pre>\n\n<a id=\"Punctuation,_Spelling_and_Grammar\"></a>\n<h3 id=\"Punctuation_Spelling_and_Grammar\">Punctuation, Spelling, and Grammar</h3>\n\n<p>Pay attention to punctuation, spelling, and grammar; it is\neasier to read well-written comments than badly written\nones.</p>\n\n<p>Comments should be as readable as narrative text, with\nproper capitalization and punctuation. In many cases,\ncomplete sentences are more readable than sentence\nfragments. Shorter comments, such as comments at the end\nof a line of code, can sometimes be less formal, but you\nshould be consistent with your style.</p>\n\n<p>Although it can be frustrating to have a code reviewer\npoint out that you are using a comma when you should be\nusing a semicolon, it is very important that source code\nmaintain a high level of clarity and readability. Proper\npunctuation, spelling, and grammar help with that\ngoal.</p>\n\n<h3 id=\"TODO_Comments\">TODO Comments</h3>\n\n<p>Use <code>TODO</code> comments for code that is temporary,\na short-term solution, or good-enough but not perfect.</p>\n\n<div>\n\n<p><code>TODO</code>s should include the string\n<code>TODO</code> in all caps, followed by the bug ID, name, e-mail address, or other identifier\nof the person or issue with the best context\nabout the problem referenced by the <code>TODO</code>.</p>\n<p>Recommended styles are (in order of preference):</p>\n\n<pre class=\"goodcode\">// TODO: bug 12345678 - Remove this after the 2047q4 compatibility window expires.\n// TODO: example.com/my-design-doc - Manually fix up this code the next time it's touched.\n// TODO(bug 12345678): Update this list after the Foo service is turned down.\n// TODO(John): Use a \"\\*\" here for concatenation operator.\n</pre>\n\n<p>If your <code>TODO</code> is of the form \"At a future\ndate do something\" make sure that you either include a\nvery specific date (\"Fix by November 2005\") or a very\nspecific event (\"Remove this code when all clients can\nhandle XML responses.\").</p>\n\n</div>\n\n<h2 id=\"Formatting\">Formatting</h2>\n\n<p>Coding style and formatting are pretty arbitrary, but a\n\nproject is much easier to follow\nif everyone uses the same style. Individuals may not agree with every\naspect of the formatting rules, and some of the rules may take\nsome getting used to, but it is important that all\n\nproject contributors follow the\nstyle rules so that\nthey can all read and understand\neveryone's code easily.</p>\n\n\n\n<div>\n<p>To help you format code correctly, we've created a\n<a href=\"https://raw.githubusercontent.com/google/styleguide/gh-pages/google-c-style.el\">\nsettings file for emacs</a>.</p>\n</div>\n\n<h3 id=\"Line_Length\">Line Length</h3>\n\n<p>Each line of text in your code should be at most 80\ncharacters long.</p>\n\n\n\n<div>\n<p>We recognize that this rule is\ncontroversial, but so much existing code already adheres\nto it, and we feel that consistency is important.</p>\n</div>\n\n<p class=\"pros\"></p>\n<p>Those who favor  this rule\nargue that it is rude to force them to resize\ntheir windows and there is no need for anything longer.\nSome folks are used to having several code windows\nside-by-side, and thus don't have room to widen their\nwindows in any case. People set up their work environment\nassuming a particular maximum window width, and 80\ncolumns has been the traditional standard. Why change\nit?</p>\n\n<p class=\"cons\"></p>\n<p>Proponents of change argue that a wider line can make\ncode more readable. The 80-column limit is an hidebound\nthrowback to 1960s mainframes;  modern equipment has wide screens that\ncan easily show longer lines.</p>\n\n<p class=\"decision\"></p>\n<p> 80 characters is the maximum.</p>\n\n<p>A line may exceed 80 characters if it is</p>\n\n<ul>\n  <li>a comment line which is not feasible to split without harming\n  readability, ease of cut and paste or auto-linking -- e.g., if a line\n  contains an example command or a literal URL longer than 80 characters.</li>\n\n  <li>a string literal that cannot easily be wrapped at 80 columns.\n  This may be because it contains URIs or other semantically-critical pieces,\n  or because the literal contains an embedded language, or because it is a\n  multiline literal whose newlines are significant, such as help messages.\n  In these cases, breaking up the literal would\n  reduce readability, searchability, ability to click links, etc. Except for\n  test code, such literals should appear at namespace scope near the top of a\n  file. If a tool like Clang-Format doesn't recognize the unsplittable content,\n  <a href=\"https://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code\">\n  disable the tool</a> around the content as necessary.\n  <br><br>\n  (We must balance between usability/searchability of such literals and the\n  readability of the code around them.)\n  </li>\n\n  <li>an include statement.</li>\n\n  <li>a <a href=\"#The__define_Guard\">header guard.</a></li>\n\n  <li>a using-declaration.</li>\n</ul>\n\n<h3 id=\"Non-ASCII_Characters\">Non-ASCII Characters</h3>\n\n<p>Non-ASCII characters should be rare, and must use UTF-8\nformatting.</p>\n\n<p>You shouldn't hard-code user-facing text in source,\neven English, so use of non-ASCII characters should be\nrare. However, in certain cases it is appropriate to\ninclude such words in your code. For example, if your\ncode parses data files from foreign sources, it may be\nappropriate to hard-code the non-ASCII string(s) used in\nthose data files as delimiters. More commonly, unit test\ncode (which does not  need to be localized) might\ncontain non-ASCII strings. In such cases, you should use\nUTF-8, since that is  an encoding\nunderstood by most tools able to handle more than just\nASCII.</p>\n\n<p>Hex encoding is also OK, and encouraged where it\nenhances readability — for example,\n<code>\"\\xEF\\xBB\\xBF\"</code>, or, even more simply,\n<code>\"\\uFEFF\"</code>,  is the Unicode zero-width\nno-break space character, which would be invisible\nif included in the source as straight UTF-8.</p>\n\n<p>When possible, avoid the <code>u8</code> prefix.\nIt has significantly different semantics starting in C++20\nthan in C++17, producing arrays of <code>char8_t</code>\nrather than <code>char</code>, and will change again in C++23.\n\n\n</p><p>You shouldn't use <code>char16_t</code> and\n<code>char32_t</code> character types, since they're for\nnon-UTF-8 text. For similar reasons you also shouldn't\nuse <code>wchar_t</code> (unless you're writing code that\ninteracts with the Windows API, which uses\n<code>wchar_t</code> extensively).</p>\n\n<h3 id=\"Spaces_vs._Tabs\">Spaces vs. Tabs</h3>\n\n<p>Use only spaces, and indent 2 spaces at a time.</p>\n\n<p>We use spaces for indentation. Do not use tabs in your\ncode. You should set your editor to emit spaces when you\nhit the tab key.</p>\n\n<h3 id=\"Function_Declarations_and_Definitions\">Function Declarations and Definitions</h3>\n\n<p>Return type on the same line as function name, parameters\non the same line if they fit. Wrap parameter lists which do\nnot fit on a single line as you would wrap arguments in a\n<a href=\"#Function_Calls\">function call</a>.</p>\n\n<p>Functions look like this:</p>\n\n\n<pre class=\"goodcode\">ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {\n  DoSomething();\n  ...\n}\n</pre>\n\n<p>If you have too much text to fit on one line:</p>\n\n<pre class=\"goodcode\">ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,\n                                             Type par_name3) {\n  DoSomething();\n  ...\n}\n</pre>\n\n<p>or if you cannot fit even the first parameter:</p>\n\n<pre class=\"goodcode\">ReturnType LongClassName::ReallyReallyReallyLongFunctionName(\n    Type par_name1,  // 4 space indent\n    Type par_name2,\n    Type par_name3) {\n  DoSomething();  // 2 space indent\n  ...\n}\n</pre>\n\n<p>Some points to note:</p>\n\n<ul>\n  <li>Choose good parameter names.</li>\n\n  <li>A parameter name may be omitted only if the parameter is not used in the\n  function's definition.</li>\n\n  <li>If you cannot fit the return type and the function\n  name on a single line, break between them.</li>\n\n  <li>If you break after the return type of a function\n  declaration or definition, do not indent.</li>\n\n  <li>The open parenthesis is always on the same line as\n  the function name.</li>\n\n  <li>There is never a space between the function name\n  and the open parenthesis.</li>\n\n  <li>There is never a space between the parentheses and\n  the parameters.</li>\n\n  <li>The open curly brace is always on the end of the last line of the function\n  declaration, not the start of the next line.</li>\n\n  <li>The close curly brace is either on the last line by\n  itself or on the same line as the open curly brace.</li>\n\n  <li>There should be a space between the close\n  parenthesis and the open curly brace.</li>\n\n  <li>All parameters should be aligned if possible.</li>\n\n  <li>Default indentation is 2 spaces.</li>\n\n  <li>Wrapped parameters have a 4 space indent.</li>\n</ul>\n\n<p>Unused parameters that are obvious from context may omit the name:</p>\n\n<pre class=\"goodcode\">class Foo {\n public:\n  Foo(const Foo&amp;) = delete;\n  Foo&amp; operator=(const Foo&amp;) = delete;\n};\n</pre>\n\n<p>Unused parameters that might not be obvious should comment out the variable\nname in the function definition:</p>\n\n<pre class=\"goodcode\">class Shape {\n public:\n  virtual void Rotate(double radians) = 0;\n};\n\nclass Circle : public Shape {\n public:\n  void Rotate(double radians) override;\n};\n\nvoid Circle::Rotate(double /*radians*/) {}\n</pre>\n\n<pre class=\"badcode\">// Bad - if someone wants to implement later, it's not clear what the\n// variable means.\nvoid Circle::Rotate(double) {}\n</pre>\n\n<p>Attributes, and macros that expand to attributes, appear at the very\nbeginning of the function declaration or definition, before the\nreturn type:</p>\n<pre class=\"goodcode\">  ABSL_ATTRIBUTE_NOINLINE void ExpensiveFunction();\n  [[nodiscard]] bool IsOk();\n</pre>\n\n<h3 id=\"Formatting_Lambda_Expressions\">Lambda Expressions</h3>\n\n<p>Format parameters and bodies as for any other function, and capture\nlists like other comma-separated lists.</p>\n\n<p>For by-reference captures, do not leave a space between the\nampersand (<code>&amp;</code>) and the variable name.</p>\n<pre class=\"goodcode\">int x = 0;\nauto x_plus_n = [&amp;x](int n) -&gt; int { return x + n; }\n</pre>\n<p>Short lambdas may be written inline as function arguments.</p>\n<pre class=\"goodcode\">absl::flat_hash_set&lt;int&gt; to_remove = {7, 8, 9};\nstd::vector&lt;int&gt; digits = {3, 9, 1, 8, 4, 7, 1};\ndigits.erase(std::remove_if(digits.begin(), digits.end(), [&amp;to_remove](int i) {\n               return to_remove.contains(i);\n             }),\n             digits.end());\n</pre>\n\n<h3 id=\"Floating_Literals\">Floating-point Literals</h3>\n\n<p>Floating-point literals should always have a radix point, with digits on both\nsides, even if they use exponential notation. Readability is improved if all\nfloating-point literals take this familiar form, as this helps ensure that they\nare not mistaken for integer literals, and that the\n<code>E</code>/<code>e</code> of the exponential notation is not mistaken for a\nhexadecimal digit. It is fine to initialize a floating-point variable with an\ninteger literal (assuming the variable type can exactly represent that integer),\nbut note that a number in exponential notation is never an integer literal.\n</p>\n\n<pre class=\"badcode\">float f = 1.f;\nlong double ld = -.5L;\ndouble d = 1248e6;\n</pre>\n\n<pre class=\"goodcode\">float f = 1.0f;\nfloat f2 = 1.0;  // Also OK\nfloat f3 = 1;    // Also OK\nlong double ld = -0.5L;\ndouble d = 1248.0e6;\n</pre>\n\n\n<h3 id=\"Function_Calls\">Function Calls</h3>\n\n<p>Either write the call all on a single line, wrap the\narguments at the parenthesis, or start the arguments on a new\nline indented by four spaces and continue at that 4 space\nindent. In the absence of other considerations, use the\nminimum number of lines, including placing multiple arguments\non each line where appropriate.</p>\n\n<p>Function calls have the following format:</p>\n<pre class=\"goodcode\">bool result = DoSomething(argument1, argument2, argument3);\n</pre>\n\n<p>If the arguments do not all fit on one line, they\nshould be broken up onto multiple lines, with each\nsubsequent line aligned with the first argument. Do not\nadd spaces after the open paren or before the close\nparen:</p>\n<pre class=\"goodcode\">bool result = DoSomething(averyveryveryverylongargument1,\n                          argument2, argument3);\n</pre>\n\n<p>Arguments may optionally all be placed on subsequent\nlines with a four space indent:</p>\n<pre class=\"goodcode\">if (...) {\n  ...\n  ...\n  if (...) {\n    bool result = DoSomething(\n        argument1, argument2,  // 4 space indent\n        argument3, argument4);\n    ...\n  }\n</pre>\n\n<p>Put multiple arguments on a single line to reduce the\nnumber of lines necessary for calling a function unless\nthere is a specific readability problem. Some find that\nformatting with strictly one argument on each line is\nmore readable and simplifies editing of the arguments.\nHowever, we prioritize for the reader over the ease of\nediting arguments, and most readability problems are\nbetter addressed with the following techniques.</p>\n\n<p>If having multiple arguments in a single line decreases\nreadability due to the complexity or confusing nature of the\nexpressions that make up some arguments, try creating\nvariables that capture those arguments in a descriptive name:</p>\n<pre class=\"goodcode\">int my_heuristic = scores[x] * y + bases[x];\nbool result = DoSomething(my_heuristic, x, y, z);\n</pre>\n\n<p>Or put the confusing argument on its own line with\nan explanatory comment:</p>\n<pre class=\"goodcode\">bool result = DoSomething(scores[x] * y + bases[x],  // Score heuristic.\n                          x, y, z);\n</pre>\n\n<p>If there is still a case where one argument is\nsignificantly more readable on its own line, then put it on\nits own line. The decision should be specific to the argument\nwhich is made more readable rather than a general policy.</p>\n\n<p>Sometimes arguments form a structure that is important\nfor readability. In those cases, feel free to format the\narguments according to that structure:</p>\n<pre class=\"goodcode\">// Transform the widget by a 3x3 matrix.\nmy_widget.Transform(x1, x2, x3,\n                    y1, y2, y3,\n                    z1, z2, z3);\n</pre>\n\n<h3 id=\"Braced_Initializer_List_Format\">Braced Initializer List Format</h3>\n\n<p>Format a braced initializer list exactly like you would format a function\ncall in its place.</p>\n\n<p>If the braced list follows a name (e.g., a type or\nvariable name), format as if the <code>{}</code> were the\nparentheses of a function call with that name. If there\nis no name, assume a zero-length name.</p>\n\n<pre class=\"goodcode\">// Examples of braced init list on a single line.\nreturn {foo, bar};\nfunctioncall({foo, bar});\nstd::pair&lt;int, int&gt; p{foo, bar};\n\n// When you have to wrap.\nSomeFunction(\n    {\"assume a zero-length name before {\"},\n    some_other_function_parameter);\nSomeType variable{\n    some, other, values,\n    {\"assume a zero-length name before {\"},\n    SomeOtherType{\n        \"Very long string requiring the surrounding breaks.\",\n        some, other, values},\n    SomeOtherType{\"Slightly shorter string\",\n                  some, other, values}};\nSomeType variable{\n    \"This is too long to fit all in one line\"};\nMyType m = {  // Here, you could also break before {.\n    superlongvariablename1,\n    superlongvariablename2,\n    {short, interior, list},\n    {interiorwrappinglist,\n     interiorwrappinglist2}};\n</pre>\n\n<a id=\"Conditionals\"></a>\n<h3 id=\"Formatting_Looping_Branching\">Looping and branching statements</h3>\n\n<p>At a high level, looping or branching statements consist of the following\n<strong>components</strong>:\n</p><ul>\n  <li>One or more <strong>statement keywords</strong> (e.g., <code>if</code>,\n  <code>else</code>, <code>switch</code>, <code>while</code>, <code>do</code>,\n  or <code>for</code>).</li>\n  <li>One <strong>condition or iteration specifier</strong>, inside\n  parentheses.</li>\n  <li>One or more <strong>controlled statements</strong>, or blocks of\n  controlled statements.</li>\n</ul>\nFor these statements:\n\n<ul>\n  <li>The components of the statement should be separated by single spaces (not\n  line breaks).</li>\n  <li>Inside the condition or iteration specifier, put one space (or a line\n  break) between each semicolon and the next token, except if the token is a\n  closing parenthesis or another semicolon.</li>\n  <li>Inside the condition or iteration specifier, do not put a space after the\n  opening parenthesis or before the closing parenthesis.</li>\n  <li>Put any controlled statements inside blocks (i.e., use curly braces).</li>\n  <li>Inside the controlled blocks, put one line break immediately after the\n  opening brace, and one line break immediately before the closing brace.</li>\n</ul>\n\n<pre class=\"goodcode\">if (condition) {                   // Good - no spaces inside parentheses, space before brace.\n  DoOneThing();                    // Good - two-space indent.\n  DoAnotherThing();\n} else if (int a = f(); a != 3) {  // Good - closing brace on new line, else on same line.\n  DoAThirdThing(a);\n} else {\n  DoNothing();\n}\n\n// Good - the same rules apply to loops.\nwhile (condition) {\n  RepeatAThing();\n}\n\n// Good - the same rules apply to loops.\ndo {\n  RepeatAThing();\n} while (condition);\n\n// Good - the same rules apply to loops.\nfor (int i = 0; i &lt; 10; ++i) {\n  RepeatAThing();\n}\n</pre>\n\n<pre class=\"badcode\">if(condition) {}                   // Bad - space missing after `if`.\nelse if ( condition ) {}           // Bad - space between the parentheses and the condition.\nelse if (condition){}              // Bad - space missing before `{`.\nelse if(condition){}               // Bad - multiple spaces missing.\n\nfor (int a = f();a == 10) {}       // Bad - space missing after the semicolon.\n\n// Bad - `if ... else` statement does not have braces everywhere.\nif (condition)\n  foo;\nelse {\n  bar;\n}\n\n// Bad - `if` statement too long to omit braces.\nif (condition)\n  // Comment\n  DoSomething();\n\n// Bad - `if` statement too long to omit braces.\nif (condition1 &amp;&amp;\n    condition2)\n  DoSomething();\n</pre>\n\n<p>For historical reasons, we allow one exception to the above rules: the curly\nbraces for the controlled statement or the line breaks inside the curly braces\nmay be omitted if as a result the entire statement appears on either a single\nline (in which case there is a space between the closing parenthesis and the\ncontrolled statement) or on two lines (in which case there is a line break\nafter the closing parenthesis and there are no braces).</p>\n\n<pre class=\"neutralcode\">// OK - fits on one line.\nif (x == kFoo) { return new Foo(); }\n\n// OK - braces are optional in this case.\nif (x == kFoo) return new Foo();\n\n// OK - condition fits on one line, body fits on another.\nif (x == kBar)\n  Bar(arg1, arg2, arg3);\n</pre>\n\n<p>This exception does not apply to multi-keyword statements like\n<code>if ... else</code> or <code>do ... while</code>.</p>\n\n<pre class=\"badcode\">// Bad - `if ... else` statement is missing braces.\nif (x) DoThis();\nelse DoThat();\n\n// Bad - `do ... while` statement is missing braces.\ndo DoThis();\nwhile (x);\n</pre>\n\n<p>Use this style only when the statement is brief, and consider that loops and\nbranching statements with complex conditions or controlled statements may be\nmore readable with curly braces. Some\nprojects require curly braces always.</p>\n\n<p><code>case</code> blocks in <code>switch</code> statements can have curly\nbraces or not, depending on your preference. If you do include curly braces,\nthey should be placed as shown below.</p>\n\n<pre class=\"goodcode\">switch (var) {\n  case 0: {  // 2 space indent\n    Foo();   // 4 space indent\n    break;\n  }\n  default: {\n    Bar();\n  }\n}\n</pre>\n\n<p>Empty loop bodies should use either an empty pair of braces or\n<code>continue</code> with no braces, rather than a single semicolon.</p>\n\n<pre class=\"goodcode\">while (condition) {}  // Good - `{}` indicates no logic.\nwhile (condition) {\n  // Comments are okay, too\n}\nwhile (condition) continue;  // Good - `continue` indicates no logic.\n</pre>\n\n<pre class=\"badcode\">while (condition);  // Bad - looks like part of `do-while` loop.\n</pre>\n\n<h3 id=\"Pointer_and_Reference_Expressions\">Pointer and Reference Expressions and Types</h3>\n\n<p>No spaces around period or arrow. Pointer operators do not\nhave trailing spaces.</p>\n\n<p>The following are examples of correctly-formatted\npointer and reference expressions:</p>\n\n<pre class=\"goodcode\">x = *p;\np = &amp;x;\nx = r.y;\nx = r-&gt;y;\n</pre>\n\n<p>Note that:</p>\n\n<ul>\n  <li>There are no spaces around the period or arrow when\n  accessing a member.</li>\n\n   <li>Pointer operators have no space after the\n   <code>*</code> or <code>&amp;</code>.</li>\n</ul>\n\n<p>When referring to a pointer or reference (variable declarations or definitions, arguments, return\ntypes, template parameters, etc.), you must not place a space before the asterisk/ampersand. Use a\nspace to separate the type from the declared name (if present).</p>\n\n<pre class=\"goodcode\">// These are fine.\nchar* c;\nconst std::string&amp; str;\nint* GetPointer();\nstd::vector&lt;char*&gt;  // Note no space between '*' and '&gt;'\n</pre>\n\n<p>It is allowed (if unusual) to declare multiple variables in the same\ndeclaration, but it is disallowed if any of those have pointer or\nreference decorations. Such declarations are easily misread.</p>\n<pre class=\"neutralcode\">// Fine if helpful for readability.\nint x, y;\n</pre>\n<pre class=\"badcode\">int x, *y;  // Disallowed - no &amp; or * in multiple declaration\nint *x, *y;  // Disallowed - no &amp; or * in multiple declaration\nint *x;  // Disallowed - &amp; or * must be left of the space\nchar * c;  // Bad - spaces on both sides of *\nconst std::string &amp; str;  // Bad - spaces on both sides of &amp;\n</pre>\n\n<h3 id=\"Boolean_Expressions\">Boolean Expressions</h3>\n\n<p>When you have a boolean expression that is longer than the\n<a href=\"#Line_Length\">standard line length</a>, be\nconsistent in how you break up the lines.</p>\n\n<p>In this example, the logical AND operator is always at\nthe end of the lines:</p>\n\n<pre class=\"goodcode\">if (this_one_thing &gt; this_other_thing &amp;&amp;\n    a_third_thing == a_fourth_thing &amp;&amp;\n    yet_another &amp;&amp; last_one) {\n  ...\n}\n</pre>\n\n<p>Note that when the code wraps in this example, both of\nthe <code>&amp;&amp;</code> logical AND operators are at\nthe end of the line. This is more common in Google code,\nthough wrapping all operators at the beginning of the\nline is also allowed. Feel free to insert extra\nparentheses judiciously because they can be very helpful\nin increasing readability when used\nappropriately, but be careful about overuse. Also note that you\nshould always use the punctuation operators, such as\n<code>&amp;&amp;</code> and <code>~</code>, rather than\nthe word operators, such as <code>and</code> and\n<code>compl</code>.</p>\n\n<h3 id=\"Return_Values\">Return Values</h3>\n\n<p>Do not needlessly surround the <code>return</code>\nexpression with parentheses.</p>\n\n<p>Use parentheses in <code>return expr;</code> only\nwhere you would use them in <code>x = expr;</code>.</p>\n\n<pre class=\"goodcode\">return result;                  // No parentheses in the simple case.\n// Parentheses OK to make a complex expression more readable.\nreturn (some_long_condition &amp;&amp;\n        another_condition);\n</pre>\n\n<pre class=\"badcode\">return (value);                // You wouldn't write var = (value);\nreturn(result);                // return is not a function!\n</pre>\n\n\n\n<h3 id=\"Variable_and_Array_Initialization\">Variable and Array Initialization</h3>\n\n<p>You may choose between <code>=</code>,\n<code>()</code>, and <code>{}</code>; the following are\nall correct:</p>\n\n<pre class=\"goodcode\">int x = 3;\nint x(3);\nint x{3};\nstd::string name = \"Some Name\";\nstd::string name(\"Some Name\");\nstd::string name{\"Some Name\"};\n</pre>\n\n<p>Be careful when using a braced initialization list <code>{...}</code>\non a type with an <code>std::initializer_list</code> constructor.\nA nonempty <i>braced-init-list</i> prefers the\n<code>std::initializer_list</code> constructor whenever\npossible. Note that empty braces <code>{}</code> are special, and\nwill call a default constructor if available. To force the\nnon-<code>std::initializer_list</code> constructor, use parentheses\ninstead of braces.</p>\n\n<pre class=\"goodcode\">std::vector&lt;int&gt; v(100, 1);  // A vector containing 100 items: All 1s.\nstd::vector&lt;int&gt; v{100, 1};  // A vector containing 2 items: 100 and 1.\n</pre>\n\n<p>Also, the brace form prevents narrowing of integral\ntypes. This can prevent some types of programming\nerrors.</p>\n\n<pre class=\"goodcode\">int pi(3.14);  // OK -- pi == 3.\nint pi{3.14};  // Compile error: narrowing conversion.\n</pre>\n\n<h3 id=\"Preprocessor_Directives\">Preprocessor Directives</h3>\n\n<p>The hash mark that starts a preprocessor directive should\nalways be at the beginning of the line.</p>\n\n<p>Even when preprocessor directives are within the body\nof indented code, the directives should start at the\nbeginning of the line.</p>\n\n<pre class=\"goodcode\">// Good - directives at beginning of line\n  if (lopsided_score) {\n#if DISASTER_PENDING      // Correct -- Starts at beginning of line\n    DropEverything();\n# if NOTIFY               // OK but not required -- Spaces after #\n    NotifyClient();\n# endif\n#endif\n    BackToNormal();\n  }\n</pre>\n\n<pre class=\"badcode\">// Bad - indented directives\n  if (lopsided_score) {\n    #if DISASTER_PENDING  // Wrong!  The \"#if\" should be at beginning of line\n    DropEverything();\n    #endif                // Wrong!  Do not indent \"#endif\"\n    BackToNormal();\n  }\n</pre>\n\n<h3 id=\"Class_Format\">Class Format</h3>\n\n<p>Sections in <code>public</code>, <code>protected</code>, and\n<code>private</code> order, each indented one space.</p>\n\n<p>The basic format for a class definition (lacking the\ncomments, see <a href=\"#Class_Comments\">Class\nComments</a> for a discussion of what comments are\nneeded) is:</p>\n\n<pre class=\"goodcode\">class MyClass : public OtherClass {\n public:      // Note the 1 space indent!\n  MyClass();  // Regular 2 space indent.\n  explicit MyClass(int var);\n  ~MyClass() {}\n\n  void SomeFunction();\n  void SomeFunctionThatDoesNothing() {\n  }\n\n  void set_some_var(int var) { some_var_ = var; }\n  int some_var() const { return some_var_; }\n\n private:\n  bool SomeInternalFunction();\n\n  int some_var_;\n  int some_other_var_;\n};\n</pre>\n\n<p>Things to note:</p>\n\n<ul>\n  <li>Any base class name should be on the same line as\n  the subclass name, subject to the 80-column limit.</li>\n\n  <li>The <code>public:</code>, <code>protected:</code>,\n  and <code>private:</code> keywords should be indented\n  one space.</li>\n\n  <li>Except for the first instance, these keywords\n  should be preceded by a blank line. This rule is\n  optional in small classes.</li>\n\n  <li>Do not leave a blank line after these\n  keywords.</li>\n\n  <li>The <code>public</code> section should be first,\n  followed by the <code>protected</code> and finally the\n  <code>private</code> section.</li>\n\n  <li>See <a href=\"#Declaration_Order\">Declaration\n  Order</a> for rules on ordering declarations within\n  each of these sections.</li>\n</ul>\n\n<h3 id=\"Constructor_Initializer_Lists\">Constructor Initializer Lists</h3>\n\n<p>Constructor initializer lists can be all on one line or\nwith subsequent lines indented four spaces.</p>\n\n<p>The acceptable formats for initializer lists are:</p>\n\n<pre class=\"goodcode\">// When everything fits on one line:\nMyClass::MyClass(int var) : some_var_(var) {\n  DoSomething();\n}\n\n// If the signature and initializer list are not all on one line,\n// you must wrap before the colon and indent 4 spaces:\nMyClass::MyClass(int var)\n    : some_var_(var), some_other_var_(var + 1) {\n  DoSomething();\n}\n\n// When the list spans multiple lines, put each member on its own line\n// and align them:\nMyClass::MyClass(int var)\n    : some_var_(var),             // 4 space indent\n      some_other_var_(var + 1) {  // lined up\n  DoSomething();\n}\n\n// As with any other code block, the close curly can be on the same\n// line as the open curly, if it fits.\nMyClass::MyClass(int var)\n    : some_var_(var) {}\n</pre>\n\n<h3 id=\"Namespace_Formatting\">Namespace Formatting</h3>\n\n<p>The contents of namespaces are not indented.</p>\n\n<p><a href=\"#Namespaces\">Namespaces</a> do not add an\nextra level of indentation. For example, use:</p>\n\n<pre class=\"goodcode\">namespace {\n\nvoid foo() {  // Correct.  No extra indentation within namespace.\n  ...\n}\n\n}  // namespace\n</pre>\n\n<p>Do not indent within a namespace:</p>\n\n<pre class=\"badcode\">namespace {\n\n  // Wrong!  Indented when it should not be.\n  void foo() {\n    ...\n  }\n\n}  // namespace\n</pre>\n\n<h3 id=\"Horizontal_Whitespace\">Horizontal Whitespace</h3>\n\n<p>Use of horizontal whitespace depends on location. Never put\ntrailing whitespace at the end of a line.</p>\n\n<h4>General</h4>\n\n<pre class=\"goodcode\">int i = 0;  // Two spaces before end-of-line comments.\n\nvoid f(bool b) {  // Open braces should always have a space before them.\n  ...\nint i = 0;  // Semicolons usually have no space before them.\n// Spaces inside braces for braced-init-list are optional.  If you use them,\n// put them on both sides!\nint x[] = { 0 };\nint x[] = {0};\n\n// Spaces around the colon in inheritance and initializer lists.\nclass Foo : public Bar {\n public:\n  // For inline function implementations, put spaces between the braces\n  // and the implementation itself.\n  Foo(int b) : Bar(), baz_(b) {}  // No spaces inside empty braces.\n  void Reset() { baz_ = 0; }  // Spaces separating braces from implementation.\n  ...\n</pre>\n\n<p>Adding trailing whitespace can cause extra work for\nothers editing the same file when they merge, as can\nremoving existing trailing whitespace. So, don't\nintroduce trailing whitespace. Remove it if you're\nalready changing that line, or do it in a separate\nclean-up\noperation (preferably when no one\nelse is working on the file).</p>\n\n<h4>Loops and Conditionals</h4>\n\n<pre class=\"goodcode\">if (b) {          // Space after the keyword in conditions and loops.\n} else {          // Spaces around else.\n}\nwhile (test) {}   // There is usually no space inside parentheses.\nswitch (i) {\nfor (int i = 0; i &lt; 5; ++i) {\n// Loops and conditions may have spaces inside parentheses, but this\n// is rare.  Be consistent.\nswitch ( i ) {\nif ( test ) {\nfor ( int i = 0; i &lt; 5; ++i ) {\n// For loops always have a space after the semicolon.  They may have a space\n// before the semicolon, but this is rare.\nfor ( ; i &lt; 5 ; ++i) {\n  ...\n\n// Range-based for loops always have a space before and after the colon.\nfor (auto x : counts) {\n  ...\n}\nswitch (i) {\n  case 1:         // No space before colon in a switch case.\n    ...\n  case 2: break;  // Use a space after a colon if there's code after it.\n</pre>\n\n<h4>Operators</h4>\n\n<pre class=\"goodcode\">// Assignment operators always have spaces around them.\nx = 0;\n\n// Other binary operators usually have spaces around them, but it's\n// OK to remove spaces around factors.  Parentheses should have no\n// internal padding.\nv = w * x + y / z;\nv = w*x + y/z;\nv = w * (x + z);\n\n// No spaces separating unary operators and their arguments.\nx = -5;\n++x;\nif (x &amp;&amp; !y)\n  ...\n</pre>\n\n<h4>Templates and Casts</h4>\n\n<pre class=\"goodcode\">// No spaces inside the angle brackets (&lt; and &gt;), before\n// &lt;, or between &gt;( in a cast\nstd::vector&lt;std::string&gt; x;\ny = static_cast&lt;char*&gt;(x);\n\n// No spaces between type and pointer.\nstd::vector&lt;char*&gt; x;\n</pre>\n\n<h3 id=\"Vertical_Whitespace\">Vertical Whitespace</h3>\n\n<p>Use vertical whitespace sparingly; unnecessary blank lines make it harder to\nsee overall code structure. Use blank lines only where they aid the reader in\nunderstanding the structure.</p>\n\n<p>Do not add blank lines where indentation already provides clear delineation,\nsuch as at the start or end of a code block. Do use blank lines to separate code\ninto closely related chunks, analogous to paragraph breaks in prose. Within a\nstatement or declaration, usually only insert line breaks to stay within\nthe <a href=\"#Line_Length\">line length limit</a>, or to attach a comment to only\npart of the contents.</p>\n\n<h2 id=\"Exceptions_to_the_Rules\">Exceptions to the Rules</h2>\n\n<p>The coding conventions described above are mandatory.\nHowever, like all good rules, these sometimes have exceptions,\nwhich we discuss here.</p>\n\n\n\n<div>\n<h3 id=\"Existing_Non-conformant_Code\" class=\"no-toc\">Existing Non-conformant Code</h3>\n\n<p>You may diverge from the rules when dealing with code that\ndoes not conform to this style guide.</p>\n\n<p>If you find yourself modifying code that was written\nto specifications other than those presented by this\nguide, you may have to diverge from these rules in order\nto stay consistent with the local conventions in that\ncode. If you are in doubt about how to do this, ask the\noriginal author or the person currently responsible for\nthe code. Remember that <em>consistency</em> includes\nlocal consistency, too.</p>\n\n</div>\n\n\n\n<h3 id=\"Windows_Code\">Windows Code</h3>\n\n<p> Windows\nprogrammers have developed their own set of coding\nconventions, mainly derived from the conventions in Windows\nheaders and other Microsoft code. We want to make it easy\nfor anyone to understand your code, so we have a single set\nof guidelines for everyone writing C++ on any platform.</p>\n\n<p>It is worth reiterating a few of the guidelines that\nyou might forget if you are used to the prevalent Windows\nstyle:</p>\n\n<ul>\n  <li>Do not use Hungarian notation (for example, naming\n  an integer <code>iNum</code>). Use the Google naming\n  conventions, including the <code>.cc</code> extension\n  for source files.</li>\n\n  <li>Windows defines many of its own synonyms for\n  primitive types, such as <code>DWORD</code>,\n  <code>HANDLE</code>, etc. It is perfectly acceptable,\n  and encouraged, that you use these types when calling\n  Windows API functions. Even so, keep as close as you\n  can to the underlying C++ types. For example, use\n  <code>const TCHAR*</code> instead of\n  <code>LPCTSTR</code>.</li>\n\n  <li>When compiling with Microsoft Visual C++, set the\n  compiler to warning level 3 or higher, and treat all\n  warnings as errors.</li>\n\n  <li>Do not use <code>#pragma once</code>; instead use\n  the standard Google include guards. The path in the\n  include guards should be relative to the top of your\n  project tree.</li>\n\n  <li>In fact, do not use any nonstandard extensions,\n  like <code>#pragma</code> and <code>__declspec</code>,\n  unless you absolutely must. Using\n  <code>__declspec(dllimport)</code> and\n  <code>__declspec(dllexport)</code> is allowed; however,\n  you must use them through macros such as\n  <code>DLLIMPORT</code> and <code>DLLEXPORT</code>, so\n  that someone can easily disable the extensions if they\n  share the code.</li>\n</ul>\n\n<p>However, there are just a few rules that we\noccasionally need to break on Windows:</p>\n\n<ul>\n  <li>Normally we <a href=\"#Multiple_Inheritance\">strongly discourage\n  the use of multiple implementation inheritance</a>;\n  however, it is required when using COM and some ATL/WTL\n  classes. You may use multiple implementation\n  inheritance to implement COM or ATL/WTL classes and\n  interfaces.</li>\n\n  <li>Although you should not use exceptions in your own\n  code, they are used extensively in the ATL and some\n  STLs, including the one that comes with Visual C++.\n  When using the ATL, you should define\n  <code>_ATL_NO_EXCEPTIONS</code> to disable exceptions.\n  You should investigate whether you can also disable\n  exceptions in your STL, but if not, it is OK to turn on\n  exceptions in the compiler. (Note that this is only to\n  get the STL to compile. You should still not write\n  exception handling code yourself.)</li>\n\n  <li>The usual way of working with precompiled headers\n  is to include a header file at the top of each source\n  file, typically with a name like <code>StdAfx.h</code>\n  or <code>precompile.h</code>. To make your code easier\n  to share with other projects, avoid including this file\n  explicitly (except in <code>precompile.cc</code>), and\n  use the <code>/FI</code> compiler option to include the\n  file automatically.</li>\n\n  <li>Resource headers, which are usually named\n  <code>resource.h</code> and contain only macros, do not\n  need to conform to these style guidelines.</li>\n</ul>\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "cppguide.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n  <meta http-equiv=\"refresh\" content=\"1; url=cppguide.html\"/>\n  <title>Redirecting</title>\n</head>\n<!-- The BODY onLoad redirect is the best: it preserves #fragments and\n     ?queries.  But it requires javascript.  If that fails, the\n     meta-refresh kicks in; it works more generally, but loses fragments\n     and queries, takes a second, and pollutes the browser history.\n     If they both fail, we let the user manually click on the new link.\n-->\n <body onload=\"location.replace(location.href.replace('.xml', '.html'))\">\n  Redirecting you to <a href=\"cppguide.html\">cppguide.html</a>.\n</body>\n</html>\n"
  },
  {
    "path": "csharp-style.md",
    "content": "# C# at Google Style Guide\n\nThis style guide is for C# code developed internally at Google, and is the\ndefault style for C# code at Google. It makes stylistic choices that conform to\nother languages at Google, such as Google C++ style and Google Java style.\n\n## Formatting guidelines\n\n### Naming rules\n\nNaming rules follow\n[Microsoft's C# naming guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines).\nWhere Microsoft's naming guidelines are unspecified (e.g. private and local\nvariables), rules are taken from the\n[CoreFX C# coding guidelines](https://github.com/dotnet/runtime/blob/HEAD/docs/coding-guidelines/coding-style.md)\n\nRule summary:\n\n#### Code\n\n*   Names of classes, methods, enumerations, public fields, public properties,\n    namespaces: `PascalCase`.\n*   Names of local variables, parameters: `camelCase`.\n*   Names of private, protected, internal and protected internal fields and\n    properties: `_camelCase`.\n*   Naming convention is unaffected by modifiers such as const, static,\n    readonly, etc.\n*   For casing, a \"word\" is anything written without internal spaces, including\n    acronyms. For example, `MyRpc` instead of ~~`MyRPC`~~.\n*   Names of interfaces start with `I`, e.g. `IInterface`.\n\n#### Files\n\n*   Filenames and directory names are `PascalCase`, e.g. `MyFile.cs`.\n*   Where possible the file name should be the same as the name of the main\n    class in the file, e.g. `MyClass.cs`.\n*   In general, prefer one core class per file.\n\n### Organization\n\n*   Modifiers occur in the following order: `public protected internal private\n    new abstract virtual override sealed static readonly extern unsafe volatile\n    async`.\n*   Namespace `using` declarations go at the top, before any namespaces. `using`\n    import order is alphabetical, apart from `System` imports which always go\n    first.\n*   Class member ordering:\n    *   Group class members in the following order:\n        *   Nested classes, enums, delegates and events.\n        *   Static, const and readonly fields.\n        *   Fields and properties.\n        *   Constructors and finalizers.\n        *   Methods.\n    *   Within each group, elements should be in the following order:\n        *   Public.\n        *   Internal.\n        *   Protected internal.\n        *   Protected.\n        *   Private.\n    *   Where possible, group interface implementations together.\n\n### Whitespace rules\n\nDeveloped from Google Java style.\n\n*   A maximum of one statement per line.\n*   A maximum of one assignment per statement.\n*   Indentation of 2 spaces, no tabs.\n*   Column limit: 100.\n*   No line break before opening brace.\n*   No line break between closing brace and `else`.\n*   Braces used even when optional.\n*   Space after `if`/`for`/`while` etc., and after commas.\n*   No space after an opening parenthesis or before a closing parenthesis.\n*   No space between a unary operator and its operand. One space between the\n    operator and each operand of all other operators.\n*   Line wrapping developed from Google C++ style guidelines, with minor\n    modifications for compatibility with Microsoft's C# formatting tools:\n    *   In general, line continuations are indented 4 spaces.\n    *   Line breaks with braces (e.g. list initializers, lambdas, object\n        initializers, etc) do not count as continuations.\n    *   For function definitions and calls, if the arguments do not all fit on\n        one line they should be broken up onto multiple lines, with each\n        subsequent line aligned with the first argument. If there is not enough\n        room for this, arguments may instead be placed on subsequent lines with\n        a four space indent. The code example below illustrates this.\n\n### Example\n\n```c#\nusing System;                                       // `using` goes at the top, outside the\n                                                    // namespace.\n\nnamespace MyNamespace {                             // Namespaces are PascalCase.\n                                                    // Indent after namespace.\n  public interface IMyInterface {                   // Interfaces start with 'I'\n    public int Calculate(float value, float exp);   // Methods are PascalCase\n                                                    // ...and space after comma.\n  }\n\n  public enum MyEnum {                              // Enumerations are PascalCase.\n    Yes,                                            // Enumerators are PascalCase.\n    No,\n  }\n\n  public class MyClass {                            // Classes are PascalCase.\n    public int Foo = 0;                             // Public member variables are\n                                                    // PascalCase.\n    public bool NoCounting = false;                 // Field initializers are encouraged.\n    private class Results {\n      public int NumNegativeResults = 0;\n      public int NumPositiveResults = 0;\n    }\n    private Results _results;                       // Private member variables are\n                                                    // _camelCase.\n    public static int NumTimesCalled = 0;\n    private const int _bar = 100;                   // const does not affect naming\n                                                    // convention.\n    private int[] _someTable = {                    // Container initializers use a 2\n      2, 3, 4,                                      // space indent.\n    }\n\n    public MyClass() {\n      _results = new Results {\n        NumNegativeResults = 1,                     // Object initializers use a 2 space\n        NumPositiveResults = 1,                     // indent.\n      };\n    }\n\n    public int CalculateValue(int mulNumber) {      // No line break before opening brace.\n      var resultValue = Foo * mulNumber;            // Local variables are camelCase.\n      NumTimesCalled++;\n      Foo += _bar;\n\n      if (!NoCounting) {                            // No space after unary operator and\n                                                    // space after 'if'.\n        if (resultValue < 0) {                      // Braces used even when optional and\n                                                    // spaces around comparison operator.\n          _results.NumNegativeResults++;\n        } else if (resultValue > 0) {               // No newline between brace and else.\n          _results.NumPositiveResults++;\n        }\n      }\n\n      return resultValue;\n    }\n\n    public void ExpressionBodies() {\n      // For simple lambdas, fit on one line if possible, no brackets or braces required.\n      Func<int, int> increment = x => x + 1;\n\n      // Closing brace aligns with first character on line that includes the opening brace.\n      Func<int, int, long> difference1 = (x, y) => {\n        long diff = (long)x - y;\n        return diff >= 0 ? diff : -diff;\n      };\n\n      // If defining after a continuation line break, indent the whole body.\n      Func<int, int, long> difference2 =\n          (x, y) => {\n            long diff = (long)x - y;\n            return diff >= 0 ? diff : -diff;\n          };\n\n      // Inline lambda arguments also follow these rules. Prefer a leading newline before\n      // groups of arguments if they include lambdas.\n      CallWithDelegate(\n          (x, y) => {\n            long diff = (long)x - y;\n            return diff >= 0 ? diff : -diff;\n          });\n    }\n\n    void DoNothing() {}                             // Empty blocks may be concise.\n\n    // If possible, wrap arguments by aligning newlines with the first argument.\n    void AVeryLongFunctionNameThatCausesLineWrappingProblems(int longArgumentName,\n                                                             int p1, int p2) {}\n\n    // If aligning argument lines with the first argument doesn't fit, or is difficult to\n    // read, wrap all arguments on new lines with a 4 space indent.\n    void AnotherLongFunctionNameThatCausesLineWrappingProblems(\n        int longArgumentName, int longArgumentName2, int longArgumentName3) {}\n\n    void CallingLongFunctionName() {\n      int veryLongArgumentName = 1234;\n      int shortArg = 1;\n      // If possible, wrap arguments by aligning newlines with the first argument.\n      AnotherLongFunctionNameThatCausesLineWrappingProblems(shortArg, shortArg,\n                                                            veryLongArgumentName);\n      // If aligning argument lines with the first argument doesn't fit, or is difficult to\n      // read, wrap all arguments on new lines with a 4 space indent.\n      AnotherLongFunctionNameThatCausesLineWrappingProblems(\n          veryLongArgumentName, veryLongArgumentName, veryLongArgumentName);\n    }\n  }\n}\n```\n\n## C# coding guidelines\n\n### Constants\n\n*   Variables and fields that can be made `const` should always be made `const`.\n*   If `const` isn’t possible, `readonly` can be a suitable alternative.\n*   Prefer named constants to magic numbers.\n\n### IEnumerable vs IList vs IReadOnlyList\n\n*   For inputs use the most restrictive collection type possible, for example\n    `IReadOnlyCollection` / `IReadOnlyList` / `IEnumerable` as inputs to methods\n    when the inputs should be immutable.\n*   For outputs, if passing ownership of the returned container to the owner,\n    prefer `IList` over `IEnumerable`. If not transferring ownership, prefer the\n    most restrictive option.\n\n### Generators vs containers\n\n*   Use your best judgement, bearing in mind:\n    *   Generator code is often less readable than filling in a container.\n    *   Generator code can be more performant if the results are going to be\n        processed lazily, e.g. when not all the results are needed.\n    *   Generator code that is directly turned into a container via `ToList()`\n        will be less performant than filling in a container directly.\n    *   Generator code that is called multiple times will be considerably slower\n        than iterating over a container multiple times.\n\n### Property styles\n\n*   For single line read-only properties, prefer expression body properties\n    (`=>`) when possible.\n*   For everything else, use the older `{ get; set; }` syntax.\n\n### Expression body syntax\n\nFor example:\n\n```c#\nint SomeProperty => _someProperty\n```\n\n*   Judiciously use expression body syntax in lambdas and properties.\n*   Don’t use on method definitions. This will be reviewed when C# 7 is live,\n    which uses this syntax heavily.\n*   As with methods and other scoped blocks of code, align the closing with the\n    first character of the line that includes the opening brace. See sample code\n    for examples.\n\n### Structs and classes:\n\n*   Structs are very different from classes:\n\n    *   Structs are always passed and returned by value.\n    *   Assigning a value to a member of a returned struct doesn’t modify the\n        original - e.g. `transform.position.x = 10` doesn’t set the transform’s\n        position.x to 10; `position` here is a property that returns a `Vector3`\n        by value, so this just sets the x parameter of a copy of the original.\n\n*   Almost always use a class.\n\n*   Consider struct when the type can be treated like other value types - for\n    example, if instances of the type are small and commonly short-lived or are\n    commonly embedded in other objects. Good examples include Vector3,\n    Quaternion and Bounds.\n\n*   Note that this guidance may vary from team to team where, for example,\n    performance issues might force the use of structs.\n\n### Lambdas vs named methods\n\n*   If a lambda is non-trivial (e.g. more than a couple of statements, excluding\n    declarations), or is reused in multiple places, it should probably be a\n    named method.\n\n### Field initializers\n\n*   Field initializers are generally encouraged.\n\n### Extension methods\n\n*   Only use an extension method when the source of the original class is not\n    available, or else when changing the source is not feasible.\n*   Only use an extension method if the functionality being added is a ‘core’\n    general feature that would be appropriate to add to the source of the\n    original class.\n    *   Note - if we have the source to the class being extended, and the\n        maintainer of the original class does not want to add the function,\n        prefer not using an extension method.\n*   Only put extension methods into core libraries that are available\n    everywhere - extensions that are only available in some code will become a\n    readability issue.\n*   Be aware that using extension methods always obfuscates the code, so err on\n    the side of not adding them.\n\n### ref and out\n\n*   Use `out` for returns that are not also inputs.\n*   Place `out` parameters after all other parameters in the method definition.\n*   `ref` should be used rarely, when mutating an input is necessary.\n*   Do not use `ref` as an optimisation for passing structs.\n*   Do not use `ref` to pass a modifiable container into a method. `ref` is only\n    required when the supplied container needs be replaced with an entirely\n    different container instance.\n\n### LINQ\n\n*   In general, prefer single line LINQ calls and imperative code, rather than\n    long chains of LINQ. Mixing imperative code and heavily chained LINQ is\n    often hard to read.\n*   Prefer member extension methods over SQL-style LINQ keywords - e.g. prefer\n    `myList.Where(x)` to `myList where x`.\n*   Avoid `Container.ForEach(...)` for anything longer than a single statement.\n\n### Array vs List\n\n*   In general, prefer `List<>` over arrays for public variables, properties,\n    and return types (keeping in mind the guidance on `IList` / `IEnumerable` /\n    `IReadOnlyList` above).\n*   Prefer `List<>` when the size of the container can change.\n*   Prefer arrays when the size of the container is fixed and known at\n    construction time.\n*   Prefer array for multidimensional arrays.\n*   Note:\n    *   array and `List<>` both represent linear, contiguous containers.\n    *   Similar to C++ arrays vs `std::vector`, arrays are of fixed capacity,\n        whereas `List<>` can be added to.\n    *   In some cases arrays are more performant, but in general `List<>` is\n        more flexible.\n\n### Folders and file locations\n\n*   Be consistent with the project.\n*   Prefer a flat structure where possible.\n\n### Use of tuple as a return type\n\n*   In general, prefer a named class type over `Tuple<>`, particularly when\n    returning complex types.\n\n### String interpolation vs `String.Format()` vs `String.Concat` vs `operator+`\n\n*   In general, use whatever is easiest to read, particularly for logging and\n    assert messages.\n*   Be aware that chained `operator+` concatenations will be slower and cause\n    significant memory churn.\n*   If performance is a concern, `StringBuilder` will be faster for multiple\n    string concatenations.\n\n### `using`\n\n*   Generally, don’t alias long typenames with `using`. Often this is a sign\n    that a `Tuple<>` needs to be turned into a class.\n    *   e.g. `using RecordList = List<Tuple<int, float>>` should probably be a\n        named class instead.\n*   Be aware that `using` statements are only file scoped and so of limited use.\n    Type aliases will not be available for external users.\n\n### Object Initializer syntax\n\nFor example:\n\n```c#\nvar x = new SomeClass {\n  Property1 = value1,\n  Property2 = value2,\n};\n```\n\n*   Object Initializer Syntax is fine for ‘plain old data’ types.\n*   Avoid using this syntax for classes or structs with constructors.\n*   If splitting across multiple lines, indent one block level.\n\n### Namespace naming\n\n*   In general, namespaces should be no more than 2 levels deep.\n*   Don't force file/folder layout to match namespaces.\n*   For shared library/module code, use namespaces. For leaf 'application' code,\n    such as `unity_app`, namespaces are not necessary.\n*   New top-level namespace names must be globally unique and recognizable.\n\n### Default values/null returns for structs\n\n*   Prefer returning a ‘success’ boolean value and a struct `out` value.\n*   Where performance isn't a concern and the resulting code significantly more\n    readable (e.g. chained null conditional operators vs deeply nested if\n    statements) nullable structs are acceptable.\n*   Notes:\n\n    *   Nullable structs are convenient, but reinforce the general ‘null is\n        failure’ pattern Google prefers to avoid. We will investigate a\n        `StatusOr` equivalent in the future, if there is enough demand.\n\n### Removing from containers while iterating\n\nC# (like many other languages) does not provide an obvious mechanism for\nremoving items from containers while iterating. There are a couple of options:\n\n*   If all that is required is to remove items that satisfy some condition,\n    `someList.RemoveAll(somePredicate)` is recommended.\n*   If other work needs to be done in the iteration, `RemoveAll` may not be\n    sufficient. A common alternative pattern is to create a new container\n    outside of the loop, insert items to keep in the new container, and swap the\n    original container with the new one at the end of iteration.\n\n### Calling delegates\n\n*   When calling a delegate, use `Invoke()` and use the null conditional\n    operator - e.g. `SomeDelegate?.Invoke()`. This clearly marks the call at the\n    callsite as ‘a delegate that is being called’. The null check is concise and\n    robust against threading race conditions.\n\n### The `var` keyword\n\n*   Use of `var` is encouraged if it aids readability by avoiding type names\n    that are noisy, obvious, or unimportant.\n*   Encouraged:\n\n    *   When the type is obvious - e.g. `var apple = new Apple();`, or `var\n        request = Factory.Create<HttpRequest>();`\n    *   For transient variables that are only passed directly to other methods -\n        e.g. `var item = GetItem(); ProcessItem(item);`\n\n*   Discouraged:\n\n    *   When working with basic types - e.g. `var success = true;`\n    *   When working with compiler-resolved built-in numeric types - e.g. `var\n        number = 12 * ReturnsFloat();`\n    *   When users would clearly benefit from knowing the type - e.g. `var\n        listOfItems = GetList();`\n\n### Attributes\n\n*   Attributes should appear on the line above the field, property, or method\n    they are associated with, separated from the member by a newline.\n*   Multiple attributes should be separated by newlines. This allows for easier\n    adding and removing of attributes, and ensures each attribute is easy to\n    search for.\n\n### Argument Naming\n\nDerived from the Google C++ style guide.\n\nWhen the meaning of a function argument is nonobvious, consider one of the\nfollowing remedies:\n\n*   If the argument is a literal constant, and the same constant is used in\n    multiple function calls in a way that tacitly assumes they're the same, use\n    a named constant to make that constraint explicit, and to guarantee that it\n    holds.\n*   Consider changing the function signature to replace a `bool` argument with\n    an `enum` argument. This will make the argument values self-describing.\n*   Replace large or complex nested expressions with named variables.\n*   Consider using\n    [Named Arguments](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments)\n    to clarify argument meanings at the call site.\n*   For functions that have several configuration options, consider defining a\n    single class or struct to hold all the options and pass an instance of that.\n    This approach has several advantages. Options are referenced by name at the\n    call site, which clarifies their meaning. It also reduces function argument\n    count, which makes function calls easier to read and write. As an added\n    benefit, call sites don't need to be changed when another option is added.\n\nConsider the following example:\n\n```c#\n// Bad - what are these arguments?\nDecimalNumber product = CalculateProduct(values, 7, false, null);\n```\n\nversus:\n\n```c#\n// Good\nProductOptions options = new ProductOptions();\noptions.PrecisionDecimals = 7;\noptions.UseCache = CacheUsage.DontUseCache;\nDecimalNumber product = CalculateProduct(values, options, completionDelegate: null);\n```\n"
  },
  {
    "path": "docguide/README.md",
    "content": "# Google documentation guide\n\n* [Markdown styleguide](style.md)\n* [Best practices](best_practices.md)\n* [README files](READMEs.md)\n* [Philosophy](philosophy.md)\n\n## See also\n\n* [How to update this guide](https://goto.google.com/doc-guide), for Googlers.\n"
  },
  {
    "path": "docguide/READMEs.md",
    "content": "# READMEs\n\nAbout README.md files.\n\n1.  [Overview](#overview)\n1.  [Readable README files](#readable-readme-files)\n1.  [Where to put your README](#where-to-put-your-readme)\n1.  [What to put in your README](#what-to-put-in-your-readme)\n\n## Overview\n\nA README is a short summary of the contents of a directory. The contents of the\nfile are displayed in GitHub and Gitiles when you view the contents of the\ncontaining directory. README files provide critical information for people\nbrowsing your code, especially first-time users.\n\nThis document covers how to create README files that are readable with GitHub\nand Gitiles.\n\n## Readable README files\n\n**README files must be named `README.md`.** The file name *must* end with the\n`.md` extension and is case sensitive.\n\nFor example, the file /README.md is rendered when you view the contents of the\ncontaining directory:\n\nhttps://github.com/google/styleguide/tree/gh-pages\n\nAlso `README.md` at `HEAD` ref is rendered by Gitiles when displaying repository\nindex:\n\nhttps://gerrit.googlesource.com/gitiles/\n\n## Where to put your README\n\nUnlike all other Markdown files, `README.md` files should not be located inside\nyour product or library's documentation directory. `README.md` files should be\nlocated in the top-level directory for your product or library's actual\ncodebase.\n\nAll top-level directories for a code package should have an up-to-date\n`README.md` file. This is especially important for package directories that\nprovide interfaces for other teams.\n\n## What to put in your README\n\nAt a minimum, your `README.md` file should contain a link to your user- and/or\nteam-facing documentation.\n\nEvery package-level `README.md` should include or point to the following\ninformation:\n\n1.  What is in this package or library and what's it used for.\n1.  Points of contact.\n1.  Status of whether this package or library is deprecated, or not for general\n    release, etc.\n1.  How to use the package or library. Examples include sample code, copyable\n    `bazel run` or `bazel test` commands, etc.\n1.  Links to relevant documentation.\n"
  },
  {
    "path": "docguide/VERSION",
    "content": "2.0\n"
  },
  {
    "path": "docguide/best_practices.md",
    "content": "# Documentation Best Practices\n\n\"Say what you mean, simply and directly.\" -\n[Brian Kernighan](https://en.wikipedia.org/wiki/The_Elements_of_Programming_Style)\n\nContents:\n\n1.  [Minimum Viable Documentation](#minimum-viable-documentation)\n1.  [Update Docs with Code](#update-docs-with-code)\n1.  [Delete Dead Documentation](#delete-dead-documentation)\n1.  [Prefer the Good Over the Perfect](#prefer-the-good-over-the-perfect)\n1.  [Documentation is the Story of Your Code](#documentation-is-the-story-of-your-code)\n1.  [Duplication is Evil](#duplication-is-evil)\n\n## Minimum Viable Documentation\n\nA small set of fresh and accurate docs is better than a large assembly of\n\"documentation\" in various states of disrepair.\n\nWrite short and useful documents. Cut out everything unnecessary, including\nout-of-date, incorrect, or redundant information. Also make a habit of\ncontinually massaging and improving every doc to suit your changing needs.\n**Docs work best when they are alive but frequently trimmed, like a bonsai\ntree**.\n\nSee also\n[these Agile Documentation best practices](https://www.agilemodeling.com/essays/agileDocumentationBestPractices.htm).\n\n## Update Docs with Code\n\n**Change your documentation in the same CL as the code change**. This keeps your\ndocs fresh, and is also a good place to explain to your reviewer what you're\ndoing.\n\nA good reviewer can at least insist that docstrings, header files, README.md\nfiles, and any other docs get updated alongside the CL.\n\n## Delete Dead Documentation\n\nDead docs are bad. They misinform, they slow down, they incite despair in\nengineers and laziness in team leads. They set a precedent for leaving behind\nmesses in a code base. If your home is clean, most guests will be clean without\nbeing asked.\n\nJust like any big cleaning project, **it's easy to be overwhelmed**. If your\ndocs are in bad shape:\n\n*   Take it slow, doc health is a gradual accumulation.\n*   First delete what you're certain is wrong, ignore what's unclear.\n*   Get your whole team involved. Devote time to quickly scan every doc and make\n    a simple decision: Keep or delete?\n*   Default to delete or leave behind if migrating. Stragglers can always be\n    recovered.\n*   Iterate.\n\n## Prefer the Good Over the Perfect\n\nDocumentation is an art. There is no perfect document, there are only proven\nmethods and prudent guidelines. See [Better is better than best](./style.md).\n\n## Documentation is the Story of Your Code\n\nWriting excellent code doesn't end when your code compiles or even if your test\ncoverage reaches 100%. It's easy to write something a computer understands, it's\nmuch harder to write something both a human and a computer understand. Your\nmission as a Code Health-conscious engineer is to **write for humans first,\ncomputers second.** Documentation is an important part of this skill.\n\nThere's a spectrum of engineering documentation that ranges from terse comments\nto detailed prose:\n\n1.  **Meaningful names**: Good naming allows the code to convey information that\n    would otherwise be relegated to comments or documentation. This includes\n    nameable entities at all levels, from local variables to classes, files, and\n    directories.\n\n2.  **Inline comments**: The primary purpose of inline comments is to provide\n    information that the code itself cannot contain, such as why the code is\n    there.\n\n3.  **Method and class comments**:\n\n    *   **Method API documentation**: The header / Javadoc / docstring comments\n        that say what methods do and how to use them. This documentation is\n        **the contract of how your code must behave**. The intended audience is\n        future programmers who will use and modify your code.\n\n        It is often reasonable to say that any behavior documented here should\n        have a test verifying it. This documentation details what arguments the\n        method takes, what it returns, any \"gotchas\" or restrictions, and what\n        exceptions it can throw or errors it can return. It does not usually\n        explain why code behaves a particular way unless that's relevant to a\n        developer's understanding of how to use the method. \"Why\" explanations\n        are for inline comments. Think in practical terms when writing method\n        documentation: \"This is a hammer. You use it to pound nails.\"\n\n    *   **Class / Module API documentation**: The header / Javadoc / docstring\n        comments for a class or a whole file. This documentation gives a brief\n        overview of what the class / file does and often gives a few short\n        examples of how you might use the class / file.\n\n        Examples are particularly relevant when there's several distinct ways to\n        use the class (some advanced, some simple). Always list the simplest use\n        case first.\n\n4.  **README.md**: A good README.md orients the new user to the directory and\n    points to more detailed explanation and user guides:\n\n    *   What is this directory intended to hold?\n    *   Which files should the developer look at first? Are some files an API?\n    *   Who maintains this directory and where I can learn more?\n\n    See the [README.md guidelines](READMEs.md).\n\n5.  **docs**: The contents of a good docs directory explain how to:\n\n    *   Get started using the relevant API, library, or tool.\n    *   Run its tests.\n    *   Debug its output.\n    *   Release the binary.\n\n6.  **Design docs, PRDs**: A good design doc or PRD discusses the proposed\n    implementation at length for the purpose of collecting feedback on that\n    design. However, once the code is implemented, design docs should serve as\n    archives of these decisions, not as half-correct docs (they are often\n    misused).\n\n7.  **Other external docs**: Some teams maintain documentation in other\n    locations, separate from the code, such as Google Sites, Drive, or wiki.\n    If you do maintain documentation in\n    other locations, you should clearly point to those locations from your\n    project directory (for example, by adding an obvious link to the location\n    from your project's `README.md`).\n\n## Duplication is Evil\n\nDo not write your own guide to a common Google technology or process. Link to it\ninstead. If the guide doesn't exist or it's badly out of date, submit your\nupdates to the appropriate directory or create a package-level\nREADME.md. **Take ownership and don't be shy**: Other teams will usually welcome\nyour contributions.\n"
  },
  {
    "path": "docguide/philosophy.md",
    "content": "# Philosophy\n\n埏埴以為器，當其無，有器之用.\n\n*Clay becomes pottery through craft, but it's the emptiness that makes a pot\nuseful.*\n\n\\- [Laozi](https://ctext.org/dictionary.pl?if=en&id=11602)\n\nContents:\n\n1.  [Radical simplicity](#radical-simplicity)\n1.  [Readable source text](#readable-source-text)\n1.  [Minimum viable documentation](#minimum-viable-documentation)\n1.  [Better is better than best](#better-is-better-than-best)\n\n## Radical simplicity\n\n*   **Scalability and interoperability** are more important than a menagerie of\n    unessential features. Scale comes from simplicity, speed, and ease.\n    Interoperability comes from unadorned, digestible content.\n\n*   **Fewer distractions** make for better writing and more productive reading.\n\n*   **New features should never interfere with the simplest use case** and\n    should remain invisible to users who don't need them.\n\n*   **Markdown is designed for the average engineer** -- the busy,\n    just-want-to-go-back-to-coding engineer. Large and complex documentation is\n    possible but not the primary focus.\n\n*   **Minimizing context switching makes people happier.** Engineers should be\n    able to interact with documentation using the same tools they use to read\n    and write code.\n\n## Readable source text\n\n* **Plain text not only suffices, it is superior**. Markdown itself is not\n  essential to this formula, but it is the best and most widely supported\n  solution right now. HTML is generally not encouraged.\n\n* **Content and presentation should not mingle**. It should always be possible\n  to ditch the renderer and read the essential information at source. Users\n  should never have to touch the presentation layer if they don't want to.\n\n* **Portability and future-proofing leave room for the unimagined integrations\n  to come**, and are best achieved by keeping the source as human-readable as\n  possible.\n\n* **Static content is better than dynamic**, because content should not depend\n  on the features of any one server. However, **fresh is better than stale**. We\n  strive to balance these needs.\n\n## Minimum viable documentation\n\n* **Docs thrive when they're treated like tests**: a necessary chore one learns\n  to savor because it rewards over time.\n  See [Best Practices](best_practices.md).\n\n* **Brief and utilitarian is better than long and exhaustive**. The vast\n  majority of users need only a small fraction of the author's total knowledge,\n  but they need it quickly and often.\n\n## Better is better than best\n\n*   **Incremental improvement is better than prolonged debate**. Patience and\n    tolerance of imperfection allow projects to evolve organically.\n\n*   **Don't\n    [lick the cookie](https://community.redhat.com/blog/2018/09/dont-lick-the-cookie/),\n    pass the plate**. Ideas are cheap. We're drowning in potentially impactful\n    projects. Choose only those you can really handle and release those you\n    can't.\n"
  },
  {
    "path": "docguide/style.md",
    "content": "# Markdown style guide\n\nMuch of what makes Markdown refreshing is the ability to write plain text and get\ngreat formatted output as a result. To keep the slate clean for the next author,\nyour Markdown should be simple and consistent with the whole corpus wherever\npossible.\n\nWe seek to balance three goals:\n\n1.  *Source text is readable and portable.*\n2.  *The Markdown corpus is maintainable over time and across teams.*\n3.  *The syntax is simple and easy to remember.*\n\nContents:\n\n1.  [Minimum viable documentation](#minimum-viable-documentation)\n1.  [Better is better than best](#better-is-better-than-best)\n1.  [Capitalization](#capitalization)\n1.  [Document layout](#document-layout)\n1.  [Table of contents](#table-of-contents)\n1.  [Character line limit](#character-line-limit)\n1.  [Trailing whitespace](#trailing-whitespace)\n1.  [Headings](#headings)\n    1.  [ATX-style headings](#atx-style-headings)\n    1.  [Use unique, complete names for headings](#use-unique-complete-names-for-headings)\n    1.  [Add spacing to headings](#add-spacing-to-headings)\n    1.  [Use a single H1 heading](#use-a-single-h1-heading)\n    1.  [Capitalization of titles and headers](#capitalization-of-titles-and-headers)\n1.  [Lists](#lists)\n    1.  [Use lazy numbering for long lists](#use-lazy-numbering-for-long-lists)\n    1.  [Nested list spacing](#nested-list-spacing)\n1.  [Code](#code)\n    1.  [Inline](#inline)\n    1.  [Use code span for escaping](#use-code-span-for-escaping)\n    1.  [Codeblocks](#codeblocks)\n        1.  [Declare the language](#declare-the-language)\n        1.  [Escape newlines](#escape-newlines)\n        1.  [Use fenced code blocks instead of indented code blocks](#use-fenced-code-blocks-instead-of-indented-code-blocks)\n        1.  [Nest codeblocks within lists](#nest-codeblocks-within-lists)\n1.  [Links](#links)\n    1.  [Use explicit paths for links within Markdown](#use-explicit-paths-for-links-within-markdown)\n    1.  [Avoid relative paths unless within the same directory](#avoid-relative-paths-unless-within-the-same-directory)\n    1.  [Use informative Markdown link titles](#use-informative-markdown-link-titles)\n    1.  [Reference links](#reference-links)\n        1.  [Use reference links for long links](#use-reference-links-for-long-links)\n        1.  [Use reference links to reduce duplication](#use-reference-links-to-reduce-duplication)\n        1.  [Define reference links after their first use](#define-reference-links-after-their-first-use)\n1.  [Images](#images)\n1.  [Tables](#tables)\n1.  [Strongly prefer Markdown to HTML](#strongly-prefer-markdown-to-html)\n\n## Minimum viable documentation\n\nA small set of fresh and accurate docs is better than a sprawling, loose\nassembly of \"documentation\" in various states of disrepair.\n\nThe **Markdown way** encourages engineers to take ownership of their docs and\nkeep them up to date with the same zeal we keep our tests in good order. Strive\nfor this.\n\n*   Identify what you really need: release docs, API docs, testing guidelines.\n*   Delete cruft frequently and in small batches.\n\n## Better is better than best\n\nThe standards for an internal documentation review are different from the\nstandards for code reviews. Reviewers should ask for improvements, but in\ngeneral, the author should always be able to invoke the \"Better/Best Rule.\"\n\nFast iteration is your friend. To get long-term improvement, **authors must stay\nproductive** when making short-term improvements. Set lower standards for each\nCL, so that **more such CLs** can happen.\n\nAs a reviewer of a documentation CL:\n\n1.  When reasonable, LGTM immediately and trust that comments will be fixed\n    appropriately.\n2.  Prefer to suggest an alternative rather than leaving a vague comment.\n3.  For substantial changes, start your own follow-up CL instead. Especially try\n    to avoid comments of the form \"You should *also*...\".\n4.  On rare occasions, hold up submission if the CL actually makes the docs\n    worse. It's okay to ask the author to revert.\n\nAs an author:\n\n1.  Avoid wasting cycles with trivial argument. Capitulate early and move on.\n2.  Cite the Better/Best Rule as often as needed.\n\n## Capitalization\n\nUse the original names of products, tools and binaries, preserving the\ncapitalization. E.g.:\n\n```markdown\n# Markdown style guide\n\n`Markdown` is a dead-simple platform for internal engineering documentation.\n```\n\nand not\n\n```markdown\n# markdown bad style guide example\n\n`markdown` is a dead-simple platform for internal engineering documentation.\n```\n\n## Document layout\n\nIn general, documents benefit from some variation of the following layout:\n\n```markdown\n# Document Title\n\nShort introduction.\n\n[TOC]\n\n## Topic\n\nContent.\n\n## See also\n\n* https://link-to-more-info\n```\n\n1.  `# Document title`: The first heading should be a level-one heading, ideally\n    the same or nearly the same as the filename. The first level-one heading is\n    used as the page `<title>`.\n\n1.  `author`: *Optional*. If you'd like to claim ownership of the document or\n    if you are very proud of it, add yourself under the title. However,\n    revision history generally suffices.\n\n1.  `Short introduction.` 1–3 sentences providing a high-level overview of the\n    topic. Imagine yourself as a complete newbie who landed on your \"Extending Foo\" doc\n    and doesn't know the most basic information you take for granted. \"What is\n    Foo? Why would I extend it?\"\n\n1.  `[TOC]`: if you use hosting that supports table of contents, such as Gitiles,\n    put `[TOC]` after the short introduction. See [`[TOC]` documentation][TOC-docs].\n\n1.  `## Topic`: The rest of your headings should start from level 2.\n\n1.  `## See also`: Put miscellaneous links at the bottom for the user who wants\n    to know more or didn't find what they needed.\n\n[TOC-docs]: https://gerrit.googlesource.com/gitiles/+/HEAD/Documentation/markdown.md#Table-of-contents\n\n## Table of contents\n\n### Use a `[TOC]` directive\n\nUse a [`[TOC]` directive][TOC-docs] unless all\nof your content is above the fold[^above] on a laptop.\n\n[^above]: Content is \"above the fold\" if it is visible when the page is first\n    displayed. Content is \"below the fold\" if it is hidden until the user\n    scrolls down the page on a computer or literally unfolds a document\n    such as a newspaper.\n\n### Place the `[TOC]` directive after the introduction\n\nPlace the `[TOC]` directive after your page's introduction and before the first\nH2 heading. For example:\n\n```markdown\n# My Page\n\nThis is my introduction **before** the TOC.\n\n[TOC]\n\n## My first H2\n```\n\n```markdown\n# My Page\n\n[TOC]\n\nThis is my introduction **after** the TOC where it should not be.\n\n## My first H2\n```\n\nFor users who read your documentation visually, it doesn't matter where your\n`[TOC]` directive is placed, as Markdown always displays the TOC toward the top and\nto the right of the page. However, `[TOC]` placement matters a lot when screen\nreaders or keyboard controls are involved.\n\nThat's because `[TOC]` inserts the HTML for the table of contents into the DOM\nwherever you've included the directive in your Markdown file. If, for example,\nyou place the directive at the very bottom of your file, screen readers won't\nread it until they get to the end of the document.\n\n## Character line limit\n\nMarkdown content follows the residual convention of an 80-character line limit.\nWhy? Because it's what most of us do for code.\n\n*   **Tooling integration**: All our tooling is designed around code, so the\n    more our documents are formatted according to similar rules, the better\n    these tools will work. For example, Code Search doesn't soft wrap.\n\n*   **Quality**. The more engineers use their well-worn coding habits when\n    creating and editing Markdown content, the better the quality. Markdown takes\n    advantage of the excellent review culture we already have.\n\n### Exceptions\n\nExceptions to the 80-character rule include:\n\n*   Links\n*   Tables\n*   Headings\n*   Code blocks\n\nThis means that lines with links are allowed to extend past column 80, along\nwith any relevant punctuation:\n\n```markdown\n*   See the\n    [foo docs](https://gerrit.googlesource.com/gitiles/+/HEAD/Documentation/markdown.md).\n    and find the logfile.\n```\n\nHowever, note that text before and after the link gets wrapped.\n\nTables may also run long. However, there are\n[best practices for creating short, readable tables](#tables).\n\n```markdown\nFoo                                                                           | Bar | Baz\n----------------------------------------------------------------------------- | --- | ---\nSomehow-unavoidable-long-cell-filled-with-content-that-simply-refuses-to-wrap | Foo | Bar\n```\n\n## Trailing whitespace\n\nDon't use trailing whitespace. Use a trailing backslash to break lines.\n\nThe [CommonMark spec](http://spec.commonmark.org/0.20/#hard-line-breaks) decrees\nthat two spaces at the end of a line should insert a `<br />` tag. However, many\ndirectories have a presubmit check for trailing whitespace, and many IDEs will\nclean it up anyway.\n\nUse a trailing backslash, sparingly:\n\n```markdown\nFor some reason I just really want a break here,\\\nthough it's probably not necessary.\n```\n\nBest practice is to avoid the need for a `<br />` altogether. A pair of newlines\nwill create a paragraph tag; get used to that.\n\n## Headings\n\n### ATX-style headings\n\n```markdown\n# Heading 1\n\n## Heading 2\n```\n\nHeadings with `=` or `-` underlines can be annoying to maintain and don't fit\nwith the rest of the heading syntax. An editor has to ask: Does `---` mean H1 or\nH2?\n\n```markdown\nHeading - do you remember what level? DO NOT DO THIS.\n---------\n```\n\n### Use unique, complete names for headings\n\nUse unique and fully descriptive names for each heading, even for sub-sections.\nSince link anchors are constructed from headings, this helps ensure that the\nautomatically-constructed anchor links are intuitive and clear.\n\nFor example, instead of:\n\n```markdown\n## Foo\n### Summary\n### Example\n## Bar\n### Summary\n### Example\n```\n\nprefer:\n\n```markdown\n## Foo\n### Foo summary\n### Foo example\n## Bar\n### Bar summary\n### Bar example\n```\n\n### Add spacing to headings\n\nPrefer spacing after `#` and newlines before and after:\n\n```markdown\n...text before.\n\n## Heading 2\n\nText after...\n```\n\nLack of spacing makes it a little harder to read in source:\n\n```markdown\n...text before.\n\n##Heading 2\nText after... DO NOT DO THIS.\n```\n\n### Use a single H1 heading\n\nUse one H1 heading as the title of your document. Subsequent headings should be\nH2 or deeper. See [Document layout](#document-layout) for more information.\n\n### Capitalization of titles and headers\n\nFollow the guidance for\n[capitalization](https://developers.google.com/style/capitalization#capitalization-in-titles-and-headings)\nin the\n[Google Developer Documentation Style Guide](https://developers.google.com/style/).\n\n## Lists\n\n### Use lazy numbering for long lists\n\nMarkdown is smart enough to let the resulting HTML render your numbered lists\ncorrectly. For longer lists that may change, especially long nested lists, use\n\"lazy\" numbering:\n\n```markdown\n1.  Foo.\n1.  Bar.\n    1.  Foofoo.\n    1.  Barbar.\n1.  Baz.\n```\n\nHowever, if the list is small and you don't anticipate changing it, prefer fully\nnumbered lists, because it's nicer to read in source:\n\n```markdown\n1.  Foo.\n2.  Bar.\n3.  Baz.\n```\n\n### Nested list spacing\n\nWhen nesting lists, use a 4-space indent for both numbered and bulleted lists:\n\n```markdown\n1.  Use 2 spaces after the item number, so the text itself is indented 4 spaces.\n    Use a 4-space indent for wrapped text.\n2.  Use 2 spaces again for the next item.\n\n*   Use 3 spaces after a bullet, so the text itself is indented 4 spaces.\n    Use a 4-space indent for wrapped text.\n    1.  Use 2 spaces with numbered lists, as before.\n        Wrapped text in a nested list needs an 8-space indent.\n    2.  Looks nice, doesn't it?\n*   Back to the bulleted list, indented 3 spaces.\n```\n\nThe following works, but it's very messy:\n\n```markdown\n* One space,\nwith no indent for wrapped text.\n     1. Irregular nesting... DO NOT DO THIS.\n```\n\nEven when there's no nesting, using the 4 space indent makes layout consistent\nfor wrapped text:\n\n```markdown\n*   Foo,\n    wrapped with a 4-space indent.\n\n1.  Two spaces for the list item\n    and 4 spaces before wrapped text.\n2.  Back to 2 spaces.\n```\n\nHowever, when lists are small, not nested, and a single line, one space can\nsuffice for both kinds of lists:\n\n```markdown\n* Foo\n* Bar\n* Baz.\n\n1. Foo.\n2. Bar.\n```\n\n## Code\n\n### Inline\n\n&#96;Backticks&#96; designate `inline code` that will be rendered literally. Use\nthem for short code quotations, field names, and more:\n\n```markdown\nYou'll want to run `really_cool_script.sh arg`.\n\nPay attention to the `foo_bar_whammy` field in that table.\n```\n\nUse inline code when referring to file types in a generic sense, rather than a\nspecific existing file:\n\n```markdown\nBe sure to update your `README.md`!\n```\n\n### Use code span for escaping\n\nWhen you don't want text to be processed as normal Markdown, like a fake path or\nexample URL that would lead to a bad autolink, wrap it in backticks:\n\n```markdown\nAn example Markdown shortlink would be: `Markdown/foo/Markdown/bar.md`\n\nAn example query might be: `https://www.google.com/search?q=$TERM`\n```\n\n### Codeblocks\n\nFor code quotations longer than a single line, use a fenced code block:\n\n<pre>\n```python\ndef Foo(self, bar):\n  self.bar = bar\n```\n</pre>\n\n#### Declare the language\n\nIt is best practice to explicitly declare the language, so that neither the\nsyntax highlighter nor the next editor must guess.\n\n#### Use fenced code blocks instead of indented code blocks\n\nFour-space indenting is also interpreted as a code block. However, we strongly\nrecommend fencing for all code blocks.\n\nIndented code blocks can sometimes look cleaner in the source, but they have\nseveral drawbacks:\n\n*   You cannot specify the language. Some Markdown features are tied to language\n    specifiers.\n*   The beginning and end of the code block are ambiguous.\n*   Indented code blocks are harder to search for in Code Search.\n\n```markdown\nYou'll need to run:\n\n    bazel run :thing -- --foo\n\nAnd then:\n\n    bazel run :another_thing -- --bar\n\nAnd again:\n\n    bazel run :yet_again -- --baz\n```\n\n#### Escape newlines\n\nBecause most command-line snippets are intended to be copied and pasted directly\ninto a terminal, it's best practice to escape any newlines. Use a single\nbackslash at the end of the line:\n\n<pre>\n```shell\n$ bazel run :target -- --flag --foo=longlonglonglonglongvalue \\\n  --bar=anotherlonglonglonglonglonglonglonglonglonglongvalue\n```\n</pre>\n\n#### Nest codeblocks within lists\n\nIf you need a code block within a list, make sure to indent it so as to not\nbreak the list:\n\n```markdown\n*   Bullet.\n\n    ```c++\n    int foo;\n    ```\n\n*   Next bullet.\n```\n\nYou can also create a nested code block with 4 spaces. Simply indent 4\nadditional spaces from the list indentation:\n\n```markdown\n*   Bullet.\n\n        int foo;\n\n*   Next bullet.\n```\n\n## Links\n\nLong links make source Markdown difficult to read and break the 80 character\nwrapping. **Wherever possible, shorten your links**.\n\n### Use explicit paths for links within Markdown\n\nUse the explicit path for Markdown links. For example:\n\n```markdown\n[...](/path/to/other/markdown/page.md)\n```\n\nYou don't need to use the entire qualified URL:\n\n```markdown\n[...](https://bad-full-url.example.com/path/to/other/markdown/page.md)\n```\n\n### Avoid relative paths unless within the same directory\n\nRelative paths are fairly safe within the same directory. For example:\n\n```markdown\n[...](other-page-in-same-dir.md)\n[...](/path/to/another/dir/other-page.md)\n```\n\nAvoid relative links if you need to specify other directories with `../`:\n\n```markdown\n[...](../../bad/path/to/another/dir/other-page.md)\n```\n\n### Use informative Markdown link titles\n\nMarkdown link syntax allows you to set a link title. Use it wisely. Users often\ndo not read documents; they scan them.\n\nLinks catch the eye. But titling your links \"here,\" \"link,\" or simply\nduplicating the target URL tells the hasty reader precisely nothing and is a\nwaste of space:\n\n```markdown\nDO NOT DO THIS.\n\nSee the Markdown guide for more info: [link](markdown.md), or check out the\nstyle guide [here](style.md).\n\nCheck out a typical test result:\n[https://example.com/foo/bar](https://example.com/foo/bar).\n```\n\nInstead, write the sentence naturally, then go back and wrap the most\nappropriate phrase with the link:\n\n```markdown\nSee the [Markdown guide](markdown.md) for more info, or check out the\n[style guide](style.md).\n\nCheck out a\n[typical test result](https://example.com/foo/bar).\n```\n\n### Reference\n\nFor long links or image URLs, you may want to split the link use from the link\ndefinition, like this:\n\n<!-- Known bug: We use a zero-width non-breaking space (U+FEFF) here to prevent -->\n<!-- reference links from rendering within code blocks. -->\n\n```markdown\nSee the [Markdown style guide][style], which has suggestions for making docs more\nreadable.\n\n﻿[style]: http://Markdown/corp/Markdown/docs/reference/style.md\n```\n\n#### Use reference links for long links\n\nUse reference links where the length of the link would detract from the\nreadability of the surrounding text if it were inlined. Reference links make it\nharder to see the destination of a link in source text, and add additional\nsyntax.\n\nIn this example, reference link usage is not appropriate, because the link is\nnot long enough to disrupt the flow of the text:\n\n```markdown\nDO NOT DO THIS.\n\nThe [style guide][style_guide] says not to use reference links unless you have\nto.\n\n﻿[style_guide]: https://google.com/Markdown-style\n```\n\nJust inline it instead:\n\n```markdown\nhttps://google.com/Markdown-style says not to use reference links unless you have to.\n```\n\nIn this example, the link destination is long enough that it makes sense to use\na reference link:\n\n```markdown\nThe [style guide] says not to use reference links unless you have to.\n\n﻿[style guide]: https://docs.google.com/document/d/13HQBxfhCwx8lVRuN2Wf6poqvAfVeEXmFVcawP5I6B3c/edit\n```\n\nUse reference links more often in tables. It is particularly important to keep\ntable content short, since Markdown does not provide a facility to break text in\ncell tables across multiple lines, and smaller tables are more readable.\n\nFor example, this table's readability is worsened by inline links:\n\n```markdown\nDO NOT DO THIS.\n\nSite                                                             | Description\n---------------------------------------------------------------- | -----------------------\n[site 1](http://google.com/excessively/long/path/example_site_1) | This is example site 1.\n[site 2](http://google.com/excessively/long/path/example_site_2) | This is example site 2.\n```\n\nInstead, use reference links to keep the line length manageable:\n\n```markdown\nSite     | Description\n-------- | -----------------------\n[site 1] | This is example site 1.\n[site 2] | This is example site 2.\n\n﻿[site 1]: http://google.com/excessively/long/path/example_site_1\n﻿[site 2]: http://google.com/excessively/long/path/example_site_2\n```\n\n#### Use reference links to reduce duplication\n\nConsider using reference links when referencing the same link destination\nmultiple times in a document, to reduce duplication.\n\n#### Define reference links after their first use\n\nWe recommend putting reference link definitions just before the next heading, at\nthe end of the section in which they're first used. If your editor has its own\nopinion about where they should go, don't fight it; the tools always win.\n\nWe define a \"section\" as all text between two headings. Think of reference links\nlike footnotes, and the current section like the current page.\n\nThis arrangement makes it easy to find the link destination in source view,\nwhile keeping the flow of text free from clutter. In long documents with lots of\nreference links, it also prevents \"footnote overload\" at the bottom of the file,\nwhich makes it difficult to pick out the relevant link destination.\n\nThere is one exception to this rule: reference link definitions that are used in\nmultiple sections should go at the end of the document. This avoids dangling\nlinks when a section is updated or moved.\n\nIn the following example, the reference definition is far from its initial use,\nwhich makes the document harder to read:\n\n```markdown\n# Header FOR A BAD DOCUMENT\n\nSome text with a [link][link_def].\n\nSome more text with the same [link][link_def].\n\n## Header 2\n\n... lots of text ...\n\n## Header 3\n\nSome more text using a [different_link][different_link_def].\n\n﻿[link_def]: http://reallyreallyreallylonglink.com\n﻿[different_link_def]: http://differentreallyreallylonglink.com\n```\n\nInstead, put it just before the header following its first use:\n\n```markdown\n# Header\n\nSome text with a [link][link_def].\n\nSome more text with the same [link][link_def].\n\n﻿[link_def]: http://reallyreallyreallylonglink.com\n\n## Header 2\n\n... lots of text ...\n\n## Header 3\n\nSome more text using a [different_link][different_link_def].\n\n﻿[different_link_def]: http://differentreallyreallylonglink.com\n```\n\n## Images\n\nSee [image syntax](https://gerrit.googlesource.com/gitiles/+/HEAD/Documentation/markdown.md#Images).\n\nUse images sparingly, and prefer simple screenshots. This guide is designed\naround the idea that plain text gets users down to the business of communication\nfaster with less reader distraction and author procrastination. However, it's\nsometimes very helpful to show what you mean.\n\n*   Use images when it's easier to *show* a reader something than to *describe\n    it*. For example, explaining how to navigate a UI is often easier with an\n    image than text.\n*   Make sure to provide appropriate text to describe your image. Readers who\n    are not sighted cannot see your image and still need to understand the\n    content! See the alt text best practices below.\n\n## Tables\n\nUse tables when they make sense: for the presentation of tabular data that needs\nto be scanned quickly.\n\nAvoid using tables when your data could easily be presented in a list. Lists are\nmuch easier to write and read in Markdown.\n\nFor example:\n\n```markdown\nDO NOT DO THIS\n\nFruit  | Metrics      | Grows on | Acute curvature    | Attributes                                                                                                  | Notes\n------ | ------------ | -------- | ------------------ | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------\nApple  | Very popular | Trees    |                    | [Juicy](http://cs/SomeReallyReallyReallyReallyReallyReallyReallyReallyLongQuery), Firm, Sweet               | Apples keep doctors away.\nBanana | Very popular | Trees    | 16 degrees average | [Convenient](http://cs/SomeDifferentReallyReallyReallyReallyReallyReallyReallyReallyLongQuery), Soft, Sweet | Contrary to popular belief, most apes prefer mangoes. Don't you? See the [design doc][banana_v2] for the newest hotness in bananiels.\n```\n\nThis table illustrates a few typical problems:\n\n*   **Poor distribution**: Several columns don't differ across rows, and some\n    cells are empty. This is usually a sign that your data may not benefit from\n    tabular display.\n\n*   **Unbalanced dimensions**: There are a small number of rows relative to\n    columns. When this ratio is unbalanced in either direction, a table becomes\n    little more than an inflexible format for text.\n\n*   **Rambling prose** in some cells. Tables should tell a succinct story at a\n    glance.\n\n[Lists](#lists) and subheadings sometimes suffice to present the same\ninformation. Let's see this data in list form:\n\n```markdown\n## Fruits\n\nBoth types are highly popular, sweet, and grow on trees.\n\n### Apple\n\n*   [Juicy](http://SomeReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongURL)\n*   Firm\n\nApples keep doctors away.\n\n### Banana\n\n*   [Convenient](http://cs/SomeDifferentReallyReallyReallyReallyReallyReallyReallyReallyLongQuery)\n*   Soft\n*   16 degrees average acute curvature.\n\nContrary to popular belief, most apes prefer mangoes. Don't you?\n\nSee the [design doc][banana_v2] for the newest hotness in bananiels.\n```\n\nThe list form is more spacious, and arguably therefore much easier for the\nreader to find what interests her in this case.\n\nHowever, there are times a table is the best choice. When you have:\n\n*   Relatively uniform data distribution across two dimensions.\n*   Many parallel items with distinct attributes.\n\nIn those cases, a table format is just the thing. In fact, a compact table can\nimprove readability:\n\n```markdown\nTransport        | Favored by     | Advantages\n---------------- | -------------- | -----------------------------------------------\nSwallow          | Coconuts       | [Fast when unladen][airspeed]\nBicycle          | Miss Gulch     | [Weatherproof][tornado_proofing]\nX-34 landspeeder | Whiny farmboys | [Cheap][tosche_station] since the XP-38 came out\n\n﻿[airspeed]: http://google3/airspeed.h\n﻿[tornado_proofing]: http://google3/kansas/\n﻿[tosche_station]: http://google3/power_converter.h\n```\n\nNote that [reference links](#reference-links) are used to keep the table cells\nmanageable.\n\n## Strongly prefer Markdown to HTML\n\nPlease prefer standard Markdown syntax wherever possible and avoid HTML hacks.\nIf you can't seem to accomplish what you want, reconsider whether you really\nneed it. Except for [big tables](#tables), Markdown meets almost all needs\nalready.\n\nEvery bit of HTML hacking reduces the readability and portability of our\nMarkdown corpus. This in turn limits the usefulness of integrations with other\ntools, which may either present the source as plain text or render it. See\n[Philosophy](philosophy.md).\n\nGitiles does not render HTML.\n"
  },
  {
    "path": "eclipse-cpp-google-style.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<profiles version=\"1\">\n<profile kind=\"CodeFormatterProfile\" name=\"Google C++\" version=\"1\">\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_for\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_in_empty_block\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.lineSplit\" value=\"80\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_member_access\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_base_types\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.keep_else_statement_on_same_line\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_switch\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_constructor_initializer_list\" value=\"83\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_brace_in_array_initializer\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_if\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_exception_specification\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_base_types\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_access_specifier\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_exception_specification\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_block\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.use_tabs_only_for_leading_indentations\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_colon_in_labeled_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_colon_in_case\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.comment.min_distance_between_code_and_line_comment\" value=\"2\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_array_initializer\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_enum_declarations\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_expressions_in_array_initializer\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_declarator_list\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_bracket\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_for\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_prefix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.tabulation.size\" value=\"2\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_before_else_in_if_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_enumerator_list\" value=\"51\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_switch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_declarator_list\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_empty_lines\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_switchstatements_compare_to_cases\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.keep_empty_array_initializer_on_one_line\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_method_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.put_empty_statement_on_new_line\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_switch\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_cast\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_between_empty_braces_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_method_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_while\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_question_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_semicolon\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_colon_in_base_clause\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_breaks_compare_to_cases\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_unary_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.join_wrapped_lines\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_declarator_list\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_arguments_in_method_invocation\" value=\"18\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.comment.never_indent_line_comments_on_first_column\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_while\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_between_empty_brackets\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_bracket\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_parameters_in_method_declaration\" value=\"18\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.number_of_empty_lines_to_preserve\" value=\"1\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_brace_in_array_initializer\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_semicolon_in_for\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_colon_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_block\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_type_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_assignment_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_expression_list\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.continuation_indentation\" value=\"2\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_expression_list\" value=\"0\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_colon_in_default\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_binary_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_conditional_expression\" value=\"34\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_if\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.format_guardian_clause_on_one_line\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_access_specifier_extra_spaces\" value=\"1\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_cast\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_access_specifier_compare_to_type_header\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_type_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.continuation_indentation_for_array_initializer\" value=\"2\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_colon_in_labeled_statement\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_semicolon_in_for\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_body_declarations_compare_to_namespace_header\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_compact_if\" value=\"0\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_assignment_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_closing_brace_in_block\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_array_initializer\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_at_end_of_file_if_missing\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_assignment\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_conditional_expression_chain\" value=\"18\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_template_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_expression_list\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_question_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_exception_specification\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_binary_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_before_identifier_in_function_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_base_clause_in_type_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_declaration_throws\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_between_empty_parens_in_exception_specification\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_declaration_compare_to_template_header\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_unary_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_switch\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_statements_compare_to_body\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_declaration_throws\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_binary_expression\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indent_statements_compare_to_block\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_template_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_before_catch_in_try_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_throws_clause_in_method_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_closing_paren_in_cast\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_paren_in_catch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_angle_bracket_in_template_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.tabulation.char\" value=\"space\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_before_colon_in_constructor_initializer_list\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_while\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_block_in_case\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.compact_else_if\" value=\"true\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_postfix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_after_template_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_colon_in_base_clause\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_catch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.keep_then_statement_on_same_line\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_switch\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.alignment_for_overloaded_left_shift_chain\" value=\"18\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_if\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_paren_in_switch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.keep_imple_if_on_one_line\" value=\"false\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.indentation.size\" value=\"2\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_namespace_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_colon_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_comma_in_enum_declarations\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_prefix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_angle_bracket_in_template_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.brace_position_for_array_initializer\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_colon_in_case\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_catch\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_brace_in_namespace_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_postfix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_closing_bracket\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_new_line_before_while_in_do_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_before_opening_paren_in_for\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_closing_angle_bracket_in_template_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.cdt.core.formatter.insert_space_after_opening_angle_bracket_in_template_arguments\" value=\"do not insert\"/>\n</profile>\n</profiles>\n"
  },
  {
    "path": "eclipse-java-google-style.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<profiles version=\"13\">\n<profile kind=\"CodeFormatterProfile\" name=\"GoogleStyle\" version=\"13\">\n<setting id=\"org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.disabling_tag\" value=\"@formatter:off\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments.count_dependent\" value=\"16|-1|16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_field\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.use_on_off_tags\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_prefer_two_fragments\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_ellipsis\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_comment_inline_tags\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_local_variable_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_multiple_fields\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter\" value=\"1040\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type.count_dependent\" value=\"1585|-1|1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_conditional_expression\" value=\"80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_multiple_fields.count_dependent\" value=\"16|-1|16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_binary_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_array_initializer\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_after_package\" value=\"1\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression.count_dependent\" value=\"16|4|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration.count_dependent\" value=\"16|4|48\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.continuation_indentation\" value=\"2\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration.count_dependent\" value=\"16|4|49\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk\" value=\"1\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_binary_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_package\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_cascading_method_invocation_with_arguments\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.compiler.source\" value=\"1.7\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration.count_dependent\" value=\"16|4|48\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.format_line_comments\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.join_wrapped_lines\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_non_simple_local_variable_annotation\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.align_type_members_on_columns\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_member_type\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_enum_constants.count_dependent\" value=\"16|5|48\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_unary_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.indent_parameter_description\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.lineSplit\" value=\"100\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation.count_dependent\" value=\"16|4|48\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indentation.size\" value=\"4\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.enabling_tag\" value=\"@formatter:on\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package\" value=\"1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_assignment\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.compiler.problem.assertIdentifier\" value=\"error\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.tabulation.char\" value=\"space\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_statements_compare_to_body\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_method\" value=\"1\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_non_simple_type_annotation\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_field_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_method_declaration\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_switch\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.compiler.problem.enumIdentifier\" value=\"error\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment_new_line_at_start_of_html_paragraph\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_ellipsis\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_block\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comment_prefix\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_method_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.compact_else_if\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_non_simple_parameter_annotation\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method\" value=\"1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.indent_root_tags\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_enum_constant\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.tabulation.size\" value=\"2\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation.count_dependent\" value=\"16|5|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter.count_dependent\" value=\"1040|-1|1040\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package.count_dependent\" value=\"1585|-1|1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_empty_lines\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.force_if_else_statement_brace\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_block_in_case\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve\" value=\"3\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_non_simple_package_annotation\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation.count_dependent\" value=\"16|-1|16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type\" value=\"1585\"/>\n<setting id=\"org.eclipse.jdt.core.compiler.compliance\" value=\"1.7\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer\" value=\"2\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_unary_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_new_anonymous_class\" value=\"20\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable.count_dependent\" value=\"1585|-1|1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field.count_dependent\" value=\"1585|-1|1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration.count_dependent\" value=\"16|5|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_binary_expression\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode\" value=\"enabled\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_label\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.format_javadoc_comments\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant.count_dependent\" value=\"16|-1|16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.line_length\" value=\"100\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_between_import_groups\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_semicolon\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_binary_operator\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations\" value=\"2\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_statements_compare_to_block\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.join_lines_in_comments\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_compact_if\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_imports\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field\" value=\"1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.format_html\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer.count_dependent\" value=\"16|5|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.format_source_code\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.compiler.codegen.targetPlatform\" value=\"1.7\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_resources_in_try\" value=\"80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.format_header\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.format_block_comments\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_enum_constants\" value=\"0\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration.count_dependent\" value=\"16|4|48\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method.count_dependent\" value=\"1585|-1|1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_type_declaration\" value=\"end_of_line\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_binary_expression.count_dependent\" value=\"16|-1|16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.wrap_non_simple_member_annotation\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable\" value=\"1585\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call.count_dependent\" value=\"16|5|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_generic_type_arguments.count_dependent\" value=\"16|-1|16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression.count_dependent\" value=\"16|5|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration.count_dependent\" value=\"16|5|80\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_after_imports\" value=\"1\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header\" value=\"true\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for\" value=\"insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_for_statement\" value=\"16\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column\" value=\"false\"/>\n<setting id=\"org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line\" value=\"false\"/>\n</profile>\n</profiles>\n"
  },
  {
    "path": "go/best-practices.md",
    "content": "<!--* toc_depth: 3 *-->\n\n# Go Style Best Practices\n\nhttps://google.github.io/styleguide/go/best-practices\n\n[Overview](index) | [Guide](guide) | [Decisions](decisions) |\n[Best practices](best-practices)\n\n<!--\n\n-->\n\n{% raw %}\n\n**Note:** This is part of a series of documents that outline [Go Style](index)\nat Google. This document is **neither [normative](index#normative) nor\n[canonical](index#canonical)**, and is an auxiliary document to the\n[core style guide](guide). See [the overview](index#about) for more information.\n\n<a id=\"about\"></a>\n\n## About\n\nThis file documents **guidance about how to best apply the Go Style Guide**.\nThis guidance is intended for common situations that arise frequently, but may\nnot apply in every circumstance. Where possible, multiple alternative approaches\nare discussed along with the considerations that go into the decision about when\nand when not to apply them.\n\nSee [the overview](index#about) for the full set of Style Guide documents.\n\n<a id=\"naming\"></a>\n\n## Naming\n\n<a id=\"function-names\"></a>\n\n### Function and method names\n\n<a id=\"function-name-repetition\"></a>\n\n#### Avoid repetition\n\nWhen choosing the name for a function or method, consider the context in which\nthe name will be read. Consider the following recommendations to avoid excess\n[repetition](decisions#repetition) at the call site:\n\n*   The following can generally be omitted from function and method names:\n\n    *   The types of the inputs and outputs (when there is no collision)\n    *   The type of a method's receiver\n    *   Whether an input or output is a pointer\n\n*   For functions, do not\n    [repeat the name of the package](decisions#repetitive-with-package).\n\n    ```go\n    // Bad:\n    package yamlconfig\n\n    func ParseYAMLConfig(input string) (*Config, error)\n    ```\n\n    ```go\n    // Good:\n    package yamlconfig\n\n    func Parse(input string) (*Config, error)\n    ```\n\n*   For methods, do not repeat the name of the method receiver.\n\n    ```go\n    // Bad:\n    func (c *Config) WriteConfigTo(w io.Writer) (int64, error)\n    ```\n\n    ```go\n    // Good:\n    func (c *Config) WriteTo(w io.Writer) (int64, error)\n    ```\n\n*   Do not repeat the names of variables passed as parameters.\n\n    ```go\n    // Bad:\n    func OverrideFirstWithSecond(dest, source *Config) error\n    ```\n\n    ```go\n    // Good:\n    func Override(dest, source *Config) error\n    ```\n\n*   Do not repeat the names and types of the return values.\n\n    ```go\n    // Bad:\n    func TransformToJSON(input *Config) *jsonconfig.Config\n    ```\n\n    ```go\n    // Good:\n    func Transform(input *Config) *jsonconfig.Config\n    ```\n\nWhen it is necessary to disambiguate functions of a similar name, it is\nacceptable to include extra information.\n\n```go\n// Good:\nfunc (c *Config) WriteTextTo(w io.Writer) (int64, error)\nfunc (c *Config) WriteBinaryTo(w io.Writer) (int64, error)\n```\n\n<a id=\"function-name-conventions\"></a>\n\n#### Naming conventions\n\nThere are some other common conventions when choosing names for functions and\nmethods:\n\n*   Functions that return something are given noun-like names.\n\n    ```go\n    // Good:\n    func (c *Config) JobName(key string) (value string, ok bool)\n    ```\n\n    A corollary of this is that function and method names should\n    [avoid the prefix `Get`](decisions#getters).\n\n    ```go\n    // Bad:\n    func (c *Config) GetJobName(key string) (value string, ok bool)\n    ```\n\n*   Functions that do something are given verb-like names.\n\n    ```go\n    // Good:\n    func (c *Config) WriteDetail(w io.Writer) (int64, error)\n    ```\n\n*   Identical functions that differ only by the types involved include the name\n    of the type at the end of the name.\n\n    ```go\n    // Good:\n    func ParseInt(input string) (int, error)\n    func ParseInt64(input string) (int64, error)\n    func AppendInt(buf []byte, value int) []byte\n    func AppendInt64(buf []byte, value int64) []byte\n    ```\n\n    If there is a clear \"primary\" version, the type can be omitted from the name\n    for that version:\n\n    ```go\n    // Good:\n    func (c *Config) Marshal() ([]byte, error)\n    func (c *Config) MarshalText() (string, error)\n    ```\n\n<a id=\"naming-doubles\"></a>\n\n### Test double and helper packages\n\nThere are several disciplines you can apply to [naming] packages and types that\nprovide test helpers and especially [test doubles]. A test double could be a\nstub, fake, mock, or spy.\n\nThese examples mostly use stubs. Update your names accordingly if your code uses\nfakes or another kind of test double.\n\n[naming]: guide#naming\n[test doubles]: https://abseil.io/resources/swe-book/html/ch13.html#basic_concepts\n\nSuppose you have a well-focused package providing production code similar to\nthis:\n\n```go\npackage creditcard\n\nimport (\n    \"errors\"\n\n    \"path/to/money\"\n)\n\n// ErrDeclined indicates that the issuer declines the charge.\nvar ErrDeclined = errors.New(\"creditcard: declined\")\n\n// Card contains information about a credit card, such as its issuer,\n// expiration, and limit.\ntype Card struct {\n    // omitted\n}\n\n// Service allows you to perform operations with credit cards against external\n// payment processor vendors like charge, authorize, reimburse, and subscribe.\ntype Service struct {\n    // omitted\n}\n\nfunc (s *Service) Charge(c *Card, amount money.Money) error { /* omitted */ }\n```\n\n<a id=\"naming-doubles-helper-package\"></a>\n\n#### Creating test helper packages\n\nSuppose you want to create a package that contains test doubles for another.\nWe'll use `package creditcard` (from above) for this example:\n\nOne approach is to introduce a new Go package based on the production one for\ntesting. A safe choice is to append the word `test` to the original package name\n(\"creditcard\" + \"test\"):\n\n```go\n// Good:\npackage creditcardtest\n```\n\nUnless stated explicitly otherwise, all examples in the sections below are in\n`package creditcardtest`.\n\n<a id=\"naming-doubles-simple\"></a>\n\n#### Simple case\n\nYou want to add a set of test doubles for `Service`. Because `Card` is\neffectively a dumb data type, similar to a Protocol Buffer message, it needs no\nspecial treatment in tests, so no double is required. If you anticipate only\ntest doubles for one type (like `Service`), you can take a concise approach to\nnaming the doubles:\n\n```go\n// Good:\nimport (\n    \"path/to/creditcard\"\n    \"path/to/money\"\n)\n\n// Stub stubs creditcard.Service and provides no behavior of its own.\ntype Stub struct{}\n\nfunc (Stub) Charge(*creditcard.Card, money.Money) error { return nil }\n```\n\nThis is strictly preferable to a naming choice like `StubService` or the very\npoor `StubCreditCardService`, because the base package name and its domain types\nimply what `creditcardtest.Stub` is.\n\nFinally, if the package is built with Bazel, make sure the new `go_library` rule\nfor the package is marked as `testonly`:\n\n```build\n# Good:\ngo_library(\n    name = \"creditcardtest\",\n    srcs = [\"creditcardtest.go\"],\n    deps = [\n        \":creditcard\",\n        \":money\",\n    ],\n    testonly = True,\n)\n```\n\nThe approach above is conventional and will be reasonably well understood by\nother engineers.\n\nSee also:\n\n*   [Go Tip #42: Authoring a Stub for Testing](https://google.github.io/styleguide/go/index.html#gotip)\n\n<a id=\"naming-doubles-multiple-behaviors\"></a>\n\n#### Multiple test double behaviors\n\nWhen one kind of stub is not enough (for example, you also need one that always\nfails), we recommend naming the stubs according to the behavior they emulate.\nHere we rename `Stub` to `AlwaysCharges` and introduce a new stub called\n`AlwaysDeclines`:\n\n```go\n// Good:\n// AlwaysCharges stubs creditcard.Service and simulates success.\ntype AlwaysCharges struct{}\n\nfunc (AlwaysCharges) Charge(*creditcard.Card, money.Money) error { return nil }\n\n// AlwaysDeclines stubs creditcard.Service and simulates declined charges.\ntype AlwaysDeclines struct{}\n\nfunc (AlwaysDeclines) Charge(*creditcard.Card, money.Money) error {\n    return creditcard.ErrDeclined\n}\n```\n\n<a id=\"naming-doubles-multiple-types\"></a>\n\n#### Multiple doubles for multiple types\n\nBut now suppose that `package creditcard` contains multiple types worth creating\ndoubles for, as seen below with `Service` and `StoredValue`:\n\n```go\npackage creditcard\n\ntype Service struct {\n    // omitted\n}\n\ntype Card struct {\n    // omitted\n}\n\n// StoredValue manages customer credit balances.  This applies when returned\n// merchandise is credited to a customer's local account instead of processed\n// by the credit issuer.  For this reason, it is implemented as a separate\n// service.\ntype StoredValue struct {\n    // omitted\n}\n\nfunc (s *StoredValue) Credit(c *Card, amount money.Money) error { /* omitted */ }\n```\n\nIn this case, more explicit test double naming is sensible:\n\n```go\n// Good:\ntype StubService struct{}\n\nfunc (StubService) Charge(*creditcard.Card, money.Money) error { return nil }\n\ntype StubStoredValue struct{}\n\nfunc (StubStoredValue) Credit(*creditcard.Card, money.Money) error { return nil }\n```\n\n<a id=\"naming-doubles-local-variables\"></a>\n\n#### Local variables in tests\n\nWhen variables in your tests refer to doubles, choose a name that most clearly\ndifferentiates the double from other production types based on context. Consider\nsome production code you want to test:\n\n```go\npackage payment\n\nimport (\n    \"path/to/creditcard\"\n    \"path/to/money\"\n)\n\ntype CreditCard interface {\n    Charge(*creditcard.Card, money.Money) error\n}\n\ntype Processor struct {\n    CC CreditCard\n}\n\nvar ErrBadInstrument = errors.New(\"payment: instrument is invalid or expired\")\n\nfunc (p *Processor) Process(c *creditcard.Card, amount money.Money) error {\n    if c.Expired() {\n        return ErrBadInstrument\n    }\n    return p.CC.Charge(c, amount)\n}\n```\n\nIn the tests, a test double called a \"spy\" for `CreditCard` is juxtaposed\nagainst production types, so prefixing the name may improve clarity.\n\n```go\n// Good:\npackage payment\n\nimport \"path/to/creditcardtest\"\n\nfunc TestProcessor(t *testing.T) {\n    var spyCC creditcardtest.Spy\n    proc := &Processor{CC: spyCC}\n\n    // declarations omitted: card and amount\n    if err := proc.Process(card, amount); err != nil {\n        t.Errorf(\"proc.Process(card, amount) = %v, want nil\", err)\n    }\n\n    charges := []creditcardtest.Charge{\n        {Card: card, Amount: amount},\n    }\n\n    if got, want := spyCC.Charges, charges; !cmp.Equal(got, want) {\n        t.Errorf(\"spyCC.Charges = %v, want %v\", got, want)\n    }\n}\n```\n\nThis is clearer than when the name is not prefixed.\n\n```go\n// Bad:\npackage payment\n\nimport \"path/to/creditcardtest\"\n\nfunc TestProcessor(t *testing.T) {\n    var cc creditcardtest.Spy\n\n    proc := &Processor{CC: cc}\n\n    // declarations omitted: card and amount\n    if err := proc.Process(card, amount); err != nil {\n        t.Errorf(\"proc.Process(card, amount) = %v, want nil\", err)\n    }\n\n    charges := []creditcardtest.Charge{\n        {Card: card, Amount: amount},\n    }\n\n    if got, want := cc.Charges, charges; !cmp.Equal(got, want) {\n        t.Errorf(\"cc.Charges = %v, want %v\", got, want)\n    }\n}\n```\n\n<a id=\"shadowing\"></a>\n\n### Shadowing\n\n**Note:** This explanation uses two informal terms, *stomping* and *shadowing*.\nThey are not official concepts in the Go language spec.\n\nLike many programming languages, Go has mutable variables: assigning to a\nvariable changes its value.\n\n```go\n// Good:\nfunc abs(i int) int {\n    if i < 0 {\n        i *= -1\n    }\n    return i\n}\n```\n\nWhen using [short variable declarations] with the `:=` operator, in some cases a\nnew variable is not created. We can call this *stomping*. It's OK to do this\nwhen the original value is no longer needed.\n\n```go\n// Good:\n// innerHandler is a helper for some request handler, which itself issues\n// requests to other backends.\nfunc (s *Server) innerHandler(ctx context.Context, req *pb.MyRequest) *pb.MyResponse {\n    // Unconditionally cap the deadline for this part of request handling.\n    ctx, cancel := context.WithTimeout(ctx, 3*time.Second)\n    defer cancel()\n    ctxlog.Info(ctx, \"Capped deadline in inner request\")\n\n    // Code here no longer has access to the original context.\n    // This is good style if when first writing this, you anticipate\n    // that even as the code grows, no operation legitimately should\n    // use the (possibly unbounded) original context that the caller provided.\n\n    // ...\n}\n```\n\nBe careful using short variable declarations in a new scope, though: that\nintroduces a new variable. We can call this *shadowing* the original variable.\nCode after the end of the block refers to the original. Here is a buggy attempt\nto shorten the deadline conditionally:\n\n```go\n// Bad:\nfunc (s *Server) innerHandler(ctx context.Context, req *pb.MyRequest) *pb.MyResponse {\n    // Attempt to conditionally cap the deadline.\n    if *shortenDeadlines {\n        ctx, cancel := context.WithTimeout(ctx, 3*time.Second)\n        defer cancel()\n        ctxlog.Info(ctx, \"Capped deadline in inner request\")\n    }\n\n    // BUG: \"ctx\" here again means the context that the caller provided.\n    // The above buggy code compiled because both ctx and cancel\n    // were used inside the if statement.\n\n    // ...\n}\n```\n\nA correct version of the code might be:\n\n```go\n// Good:\nfunc (s *Server) innerHandler(ctx context.Context, req *pb.MyRequest) *pb.MyResponse {\n    if *shortenDeadlines {\n        var cancel func()\n        // Note the use of simple assignment, = and not :=.\n        ctx, cancel = context.WithTimeout(ctx, 3*time.Second)\n        defer cancel()\n        ctxlog.Info(ctx, \"Capped deadline in inner request\")\n    }\n    // ...\n}\n```\n\nIn the case we called stomping, because there's no new variable, the type being\nassigned must match that of the original variable. With shadowing, an entirely\nnew entity is introduced so it can have a different type. Intentional shadowing\ncan be a useful practice, but you can always use a new name if it improves\n[clarity](guide#clarity).\n\nIt is not a good idea to use variables with the same name as standard packages\nother than very small scopes, because that renders free functions and values\nfrom that package inaccessible. Conversely, when picking a name for your\npackage, avoid names that are likely to require\n[import renaming](decisions#import-renaming) or cause shadowing of otherwise\ngood variable names at the client side.\n\n```go\n// Bad:\nfunc LongFunction() {\n    url := \"https://example.com/\"\n    // Oops, now we can't use net/url in code below.\n}\n```\n\n[short variable declarations]: https://go.dev/ref/spec#Short_variable_declarations\n\n<a id=\"util-packages\"></a>\n\n### Util packages\n\nGo packages have a name specified on the `package` declaration, separate from\nthe import path. The package name matters more for readability than the path.\n\nGo package names should be\n[related to what the package provides](decisions#package-names). Naming a\npackage just `util`, `helper`, `common` or similar is usually a poor choice (it\ncan be used as *part* of the name though). Uninformative names make the code\nharder to read, and if used too broadly they are liable to cause needless\n[import conflicts](decisions#import-renaming).\n\nInstead, consider what the callsite will look like.\n\n```go\n// Good:\ndb := spannertest.NewDatabaseFromFile(...)\n\n_, err := f.Seek(0, io.SeekStart)\n\nb := elliptic.Marshal(curve, x, y)\n```\n\nYou can tell roughly what each of these do even without knowing the imports list\n(`cloud.google.com/go/spanner/spannertest`, `io`, and `crypto/elliptic`). With\nless focused names, these might read:\n\n```go\n// Bad:\ndb := test.NewDatabaseFromFile(...)\n\n_, err := f.Seek(0, common.SeekStart)\n\nb := helper.Marshal(curve, x, y)\n```\n\n<a id=\"package-size\"></a>\n\n## Package size\n\nIf you're asking yourself how big your Go packages should be and whether to\nplace related types in the same package or split them into different ones, a\ngood place to start is the [Go blog post about package names][blog-pkg-names].\nDespite the post title, it's not solely about naming. It contains some helpful\nhints and cites several useful articles and talks.\n\nHere are some other considerations and notes.\n\nUsers see [godoc] for the package in one page, and any methods exported by types\nsupplied by the package are grouped by their type. Godoc also group constructors\nalong with the types they return. If *client code* is likely to need two values\nof different type to interact with each other, it may be convenient for the user\nto have them in the same package.\n\nCode within a package can access unexported identifiers in the package. If you\nhave a few related types whose *implementation* is tightly coupled, placing them\nin the same package lets you achieve this coupling without polluting the public\nAPI with these details. A good test for this coupling is to imagine a\nhypothetical user of two packages, where the packages cover closely related\ntopics: if the user must import both packages in order to use either in any\nmeaningful way, combining them together is usually the right thing to do. The\nstandard library generally demonstrates this kind of scoping and layering well.\n\nAll of that being said, putting your entire project in a single package would\nlikely make that package too large. When something is conceptually distinct,\ngiving it its own small package can make it easier to use. The short name of the\npackage as known to clients together with the exported type name work together\nto make a meaningful identifier: e.g. `bytes.Buffer`, `ring.New`. The\n[Package Names blog post][blog-pkg-names] has more examples.\n\nGo style is flexible about file size, because maintainers can move code within a\npackage from one file to another without affecting callers. But as a general\nguideline: it is usually not a good idea to have a single file with many\nthousands of lines in it, or having many tiny files. There is no \"one type, one\nfile\" convention as in some other languages. As a rule of thumb, files should be\nfocused enough that a maintainer can tell which file contains something, and the\nfiles should be small enough that it will be easy to find once there. The\nstandard library often splits large packages to several source files, grouping\nrelated code by file. The source for [package `bytes`] is a good example.\nPackages with long package documentation may choose to dedicate one file called\n`doc.go` that has the [package documentation](decisions#package-comments), a\npackage declaration, and nothing else, but this is not required.\n\nWithin the Google codebase and in projects using Bazel, directory layout for Go\ncode is different than it is in open source Go projects: you can have multiple\n`go_library` targets in a single directory. A good reason to give each package\nits own directory is if you expect to open source your project in the future.\n\nA few non-canonical reference examples to help demonstrate these ideas in\naction:\n\n*   small packages that contain one cohesive idea that warrant nothing more\n    being added nor nothing being removed:\n\n    *   [package `csv`][package `csv`]: CSV data encoding and decoding with\n        responsibility split respectively between [reader.go] and [writer.go].\n    *   [package `expvar`][package `expvar`]: whitebox program telemetry all\n        contained in [expvar.go].\n\n*   moderately sized packages that contain one large domain and its multiple\n    responsibilities together:\n\n    *   [package `flag`][package `flag`]: command line flag management all\n        contained in [flag.go].\n\n*   large packages that divide several closely related domains across several\n    files:\n\n    *   [package `http`][package `http`]: the core of HTTP:\n        [client.go][http-client], support for HTTP clients;\n        [server.go][http-client], support for HTTP servers; [cookie.go], cookie\n        management.\n    *   [package `os`][package `os`]: cross-platform operating system\n        abstractions: [exec.go], subprocess management; [file.go], file\n        management; [tempfile.go], temporary files.\n\nSee also:\n\n*   [Test double packages](#naming-doubles)\n*   [Organizing Go Code (Blog Post)]\n*   [Organizing Go Code (Presentation)]\n\n[blog-pkg-names]: https://go.dev/blog/package-names\n[package `bytes`]: https://go.dev/src/bytes/\n[Organizing Go Code (Blog Post)]: https://go.dev/blog/organizing-go-code\n[Organizing Go Code (Presentation)]: https://go.dev/talks/2014/organizeio.slide\n[package `csv`]: https://pkg.go.dev/encoding/csv\n[reader.go]: https://go.googlesource.com/go/+/refs/heads/master/src/encoding/csv/reader.go\n[writer.go]: https://go.googlesource.com/go/+/refs/heads/master/src/encoding/csv/writer.go\n[package `expvar`]: https://pkg.go.dev/expvar\n[expvar.go]: https://go.googlesource.com/go/+/refs/heads/master/src/expvar/expvar.go\n[package `flag`]: https://pkg.go.dev/flag\n[flag.go]: https://go.googlesource.com/go/+/refs/heads/master/src/flag/flag.go\n[godoc]: https://pkg.go.dev/\n[package `http`]: https://pkg.go.dev/net/http\n[http-client]: https://go.googlesource.com/go/+/refs/heads/master/src/net/http/client.go\n[http-server]: https://go.googlesource.com/go/+/refs/heads/master/src/net/http/server.go\n[cookie.go]: https://go.googlesource.com/go/+/refs/heads/master/src/net/http/cookie.go\n[package `os`]: https://pkg.go.dev/os\n[exec.go]: https://go.googlesource.com/go/+/refs/heads/master/src/os/exec.go\n[file.go]: https://go.googlesource.com/go/+/refs/heads/master/src/os/file.go\n[tempfile.go]: https://go.googlesource.com/go/+/refs/heads/master/src/os/tempfile.go\n\n<a id=\"imports\"></a>\n\n## Imports\n\n<a id=\"import-protos\"></a>\n\n### Protocol Buffer Messages and Stubs\n\nProto library imports are treated differently than standard Go imports due to\ntheir cross-language nature. The convention for renamed proto imports are based\non the rule that generated the package:\n\n*   The `pb` suffix is generally used for `go_proto_library` rules.\n*   The `grpc` suffix is generally used for `go_grpc_library` rules.\n\nOften a single word describing the package is used:\n\n```go\n// Good:\nimport (\n    foopb \"path/to/package/foo_service_go_proto\"\n    foogrpc \"path/to/package/foo_service_go_grpc\"\n)\n```\n\nFollow the style guidance for\n[package names](https://google.github.io/styleguide/go/decisions#package-names).\nPrefer whole words. Short names are good, but avoid ambiguity. When in doubt,\nuse the proto package name up to _go with a pb suffix:\n\n```go\n// Good:\nimport (\n    pushqueueservicepb \"path/to/package/push_queue_service_go_proto\"\n)\n```\n\n**Note:** Previous guidance encouraged very short names such as \"xpb\" or even\njust \"pb\". New code should prefer more descriptive names. Existing code which\nuses short names should not be used as an example, but does not need to be\nchanged.\n\n<a id=\"import-order\"></a>\n\n### Import ordering\n\nSee the [Go Style Decisions: Import grouping](decisions.md#import-grouping).\n\n<a id=\"error-handling\"></a>\n\n## Error handling\n\nIn Go, [errors are values]; they are created by code and consumed by code.\nErrors can be:\n\n*   Converted into diagnostic information for display to humans\n*   Used by the maintainer\n*   Interpreted by an end user\n\nError messages also show up across a variety of different surfaces including log\nmessages, error dumps, and rendered UIs.\n\nCode that processes (produces or consumes) errors should do so deliberately. It\ncan be tempting to ignore or blindly propagate an error return value. However,\nit is always worth considering whether the current function in the call frame is\npositioned to handle the error most effectively. This is a large topic and it is\nhard to give categorical advice. Use your judgment, but keep the following\nconsiderations in mind:\n\n*   When creating an error value, decide whether to give it any\n    [structure](#error-structure).\n*   When handling an error, consider [adding information](#error-extra-info)\n    that you have but that the caller and/or callee might not.\n*   See also guidance on [error logging](#error-logging).\n\nWhile it is usually not appropriate to ignore an error, a reasonable exception\nto this is when orchestrating related operations, where often only the first\nerror is useful. Package [`errgroup`] provides a convenient abstraction for a\ngroup of operations that can all fail or be canceled as a group.\n\n[errors are values]: https://go.dev/blog/errors-are-values\n[`errgroup`]: https://pkg.go.dev/golang.org/x/sync/errgroup\n\nSee also:\n\n*   [Effective Go on errors](https://go.dev/doc/effective_go#errors)\n*   [A post by the Go Blog on errors](https://go.dev/blog/go1.13-errors)\n*   [Package `errors`](https://pkg.go.dev/errors)\n*   [Package `upspin.io/errors`](https://commandcenter.blogspot.com/2017/12/error-handling-in-upspin.html)\n*   [GoTip #89: When to Use Canonical Status Codes as Errors](https://google.github.io/styleguide/go/index.html#gotip)\n*   [GoTip #48: Error Sentinel Values](https://google.github.io/styleguide/go/index.html#gotip)\n*   [GoTip #13: Designing Errors for Checking](https://google.github.io/styleguide/go/index.html#gotip)\n\n<a id=\"error-structure\"></a>\n\n### Error structure\n\nIf callers need to interrogate the error (e.g., distinguish different error\nconditions), give the error value structure so that this can be done\nprogrammatically rather than having the caller perform string matching. This\nadvice applies to production code as well as to tests that care about different\nerror conditions.\n\nThe simplest structured errors are unparameterized global values.\n\n```go\ntype Animal string\n\nvar (\n    // ErrDuplicate occurs if this animal has already been seen.\n    ErrDuplicate = errors.New(\"duplicate\")\n\n    // ErrMarsupial occurs because we're allergic to marsupials outside Australia.\n    // Sorry.\n    ErrMarsupial = errors.New(\"marsupials are not supported\")\n)\n\nfunc process(animal Animal) error {\n    switch {\n    case seen[animal]:\n        return ErrDuplicate\n    case marsupial(animal):\n        return ErrMarsupial\n    }\n    seen[animal] = true\n    // ...\n    return nil\n}\n```\n\nThe caller can simply compare the returned error value of the function with one\nof the known error values:\n\n```go\n// Good:\nfunc handlePet(...) {\n    switch err := process(an); err {\n    case ErrDuplicate:\n        return fmt.Errorf(\"feed %q: %v\", an, err)\n    case ErrMarsupial:\n        // Try to recover with a friend instead.\n        alternate = an.BackupAnimal()\n        return handlePet(..., alternate, ...)\n    }\n}\n```\n\nThe above uses sentinel values, where the error must be equal (in the sense of\n`==`) to the expected value. That is perfectly adequate in many cases. If\n`process` returns wrapped errors (discussed below), you can use [`errors.Is`].\n\n```go\n// Good:\nfunc handlePet(...) {\n    switch err := process(an); {\n    case errors.Is(err, ErrDuplicate):\n        return fmt.Errorf(\"feed %q: %v\", an, err)\n    case errors.Is(err, ErrMarsupial):\n        // ...\n    }\n}\n```\n\nDo not attempt to distinguish errors based on their string form. (See\n[Go Tip #13: Designing Errors for Checking](https://google.github.io/styleguide/go/index.html#gotip)\nfor more.)\n\n```go\n// Bad:\nfunc handlePet(...) {\n    err := process(an)\n    if regexp.MatchString(`duplicate`, err.Error()) {...}\n    if regexp.MatchString(`marsupial`, err.Error()) {...}\n}\n```\n\nIf there is extra information in the error that the caller needs\nprogrammatically, it should ideally be presented structurally. For example, the\n[`os.PathError`] type is documented to place the pathname of the failing\noperation in a struct field which the caller can easily access.\n\nOther error structures can be used as appropriate, for example a project struct\ncontaining an error code and detail string. [Package `status`][status] is a\ncommon encapsulation; if you choose this approach (which you are not obligated\nto do), use [canonical codes]. See\n[Go Tip #89: When to Use Canonical Status Codes as Errors](https://google.github.io/styleguide/go/index.html#gotip)\nto know if using status codes is the right choice.\n\n[`os.PathError`]: https://pkg.go.dev/os#PathError\n[`errors.Is`]: https://pkg.go.dev/errors#Is\n[`errors.As`]: https://pkg.go.dev/errors#As\n[`package cmp`]: https://pkg.go.dev/github.com/google/go-cmp/cmp\n[status]: https://pkg.go.dev/google.golang.org/grpc/status\n[canonical codes]: https://pkg.go.dev/google.golang.org/grpc/codes\n\n<a id=\"error-extra-info\"></a>\n\n### Adding information to errors\n\nWhen adding information to errors, avoid redundant information that the\nunderlying error already provides. The `os` package, for instance, already\nincludes path information in its errors.\n\n```go\n// Good:\nif err := os.Open(\"settings.txt\"); err != nil {\n  return fmt.Errorf(\"launch codes unavailable: %v\", err)\n}\n\n// Output:\n//\n// launch codes unavailable: open settings.txt: no such file or directory\n```\n\nHere, \"launch codes unavailable\" adds specific meaning to the `os.Open` error\nthat's relevant to the current function's context, without duplicating the\nunderlying file path information.\n\n```go\n// Bad:\nif err := os.Open(\"settings.txt\"); err != nil {\n  return fmt.Errorf(\"could not open settings.txt: %v\", err)\n}\n\n// Output:\n//\n// could not open settings.txt: open settings.txt: no such file or directory\n```\n\nDon't add an annotation if its sole purpose is to indicate a failure without\nadding new information. The presence of an error sufficiently conveys the\nfailure to the caller.\n\n```go\n// Bad:\nreturn fmt.Errorf(\"failed: %v\", err) // just return err instead\n```\n\nThe\n[choice between `%v` and `%w` when wrapping errors](https://go.dev/blog/go1.13-errors#whether-to-wrap)\nwith `fmt.Errorf` is a nuanced decision that significantly impacts how errors\nare propagated handled, inspected, and documented within your application. The\ncore principle is to make error values useful to their observers, whether those\nobservers are humans or code.\n\n1.  **`%v` for simple annotation or new error**\n\n    The `%v` verb is your general-purpose tool for string formatting of any Go\n    value, including errors. When used with `fmt.Errorf`, it embeds the string\n    representation of an error (what its `Error()` method returns) into a new\n    error value, dropping any structured information from the original error.\n    Examples to use `%v`:\n\n    *   Adding interesting, non-redundant context: as in the example above.\n\n    *   Logging or displaying errors: When the primary goal is to present a\n        human-readable error message in logs or to a user, and you don't intend\n        for the caller to programmatically `errors.Is` or `errors.As` the error\n        (Note: `errors.Unwrap` is generally not recommended here as it doesn't\n        handle multi-errors).\n\n    *   Creating fresh, independent errors: Sometimes it is necessary to\n        transform an error into a new error message, thereby hiding the\n        specifics of the original error. This practice is particularly\n        beneficial at system boundaries, including but not limited to RPC, IPC,\n        and storage, where we translate domain-specific errors into a canonical\n        error space.\n\n        ```go\n        // Good:\n        func (*FortuneTeller) SuggestFortune(context.Context, *pb.SuggestionRequest) (*pb.SuggestionResponse, error) {\n          // ...\n          if err != nil {\n            return nil, fmt.Errorf(\"couldn't find fortune database: %v\", err)\n          }\n        }\n        ```\n\n        We could also explicitly annotate RPC code `Internal` to the example\n        above.\n\n        ```go\n        // Good:\n        import (\n          \"google.golang.org/grpc/codes\"\n          \"google.golang.org/grpc/status\"\n        )\n\n        func (*FortuneTeller) SuggestFortune(context.Context, *pb.SuggestionRequest) (*pb.SuggestionResponse, error) {\n          // ...\n          if err != nil {\n            // Or use fmt.Errorf with the %w verb if deliberately wrapping an\n            // error which the caller is meant to unwrap.\n            return nil, status.Errorf(codes.Internal, \"couldn't find fortune database\", status.ErrInternal)\n          }\n        }\n        ```\n\n1.  **`%w` (wrap) for programmatic inspection and error chaining**\n\n    The `%w` verb is specifically designed for error wrapping. It creates a new\n    error that provides an `Unwrap()` method, allowing callers to\n    programmatically inspect the error chain using `errors.Is` and `errors.As`.\n    Examples to use `%w`:\n\n    *   Adding context while preserving the original error for programmatic\n        inspection: This is the primary use case within helpers of your\n        application. You want to enrich an error with additional context (e.g.,\n        what operation was being performed when it failed) but still allow the\n        caller to check if the underlying error is a specific sentinel error or\n        type.\n\n        ```go\n        // Good:\n        func (s *Server) internalFunction(ctx context.Context) error {\n          // ...\n          if err != nil {\n            return fmt.Errorf(\"couldn't find remote file: %w\", err)\n          }\n        }\n        ```\n\n        This allows a higher-level function to do `errors.Is(err,\n        fs.ErrNotExist)` if the underlying error was `fs.ErrNotExist`, even\n        though it's wrapped.\n\n        At points where your system interacts with external systems like RPC,\n        IPC, or storage, it's often better to translate domain-specific errors\n        into a standardized error space (e.g., gRPC status codes) rather than\n        simply wrapping the raw underlying error with `%w`. The client typically\n        doesn't care about the exact internal file system error; they care about\n        the canonical result (e.g., `Internal`, `NotFound`, `PermissionDenied`).\n\n    *   When you explicitly document and test the underlying errors you expose:\n        If your package's API guarantees that certain underlying errors can be\n        unwrapped and checked by callers (e.g., \"this function might return\n        `ErrInvalidConfig` wrapped within a more general error\"), then `%w` is\n        appropriate. This forms part of your package's contract.\n\nSee also:\n\n*   [Error Documentation Conventions](#documentation-conventions-errors)\n*   [Blog post on error wrapping](https://blog.golang.org/go1.13-errors)\n\n<a id=\"error-percent-w\"></a>\n\n### Placement of %w in errors\n\nPrefer to place `%w` at the end of an error string *if* you are to use\n[error wrapping](https://go.dev/blog/go1.13-errors) with the `%w` formatting\nverb.\n\nErrors can be wrapped with the `%w` verb, or by placing them in a\n[structured error](https://google.github.io/styleguide/go/index.html#gotip) that\nimplements `Unwrap() error` (ex:\n[`fs.PathError`](https://pkg.go.dev/io/fs#PathError)).\n\nWrapped errors form error chains: each new layer of wrapping adds a new entry to\nthe front of the error chain. The error chain can be traversed with the\n`Unwrap() error` method. For example:\n\n```go\nerr1 := fmt.Errorf(\"err1\")\nerr2 := fmt.Errorf(\"err2: %w\", err1)\nerr3 := fmt.Errorf(\"err3: %w\", err2)\n```\n\nThis forms an error chain of the form,\n\n```mermaid\nflowchart LR\n  err3 == err3 wraps err2 ==> err2;\n  err2 == err2 wraps err1 ==> err1;\n```\n\nRegardless of where the `%w` verb is placed, the error returned always\nrepresents the front of the error chain, and the `%w` is the next child.\nSimilarly, `Unwrap() error` always traverses the error chain from newest to\noldest error.\n\nPlacement of the `%w` verb does, however, affect whether the error chain is\nprinted newest to oldest, oldest to newest, or neither:\n\n```go\n// Good:\nerr1 := fmt.Errorf(\"err1\")\nerr2 := fmt.Errorf(\"err2: %w\", err1)\nerr3 := fmt.Errorf(\"err3: %w\", err2)\nfmt.Println(err3) // err3: err2: err1\n// err3 is a newest-to-oldest error chain, that prints newest-to-oldest.\n```\n\n```go\n// Bad:\nerr1 := fmt.Errorf(\"err1\")\nerr2 := fmt.Errorf(\"%w: err2\", err1)\nerr3 := fmt.Errorf(\"%w: err3\", err2)\nfmt.Println(err3) // err1: err2: err3\n// err3 is a newest-to-oldest error chain, that prints oldest-to-newest.\n```\n\n```go\n// Bad:\nerr1 := fmt.Errorf(\"err1\")\nerr2 := fmt.Errorf(\"err2-1 %w err2-2\", err1)\nerr3 := fmt.Errorf(\"err3-1 %w err3-2\", err2)\nfmt.Println(err3) // err3-1 err2-1 err1 err2-2 err3-2\n// err3 is a newest-to-oldest error chain, that neither prints newest-to-oldest\n// nor oldest-to-newest.\n```\n\nTherefore, in order for error text to mirror error chain structure, prefer\nplacing the `%w` verb at the end with the form `[...]: %w`.\n\n<a id=\"error-percent-w-sentinel-placement\"></a>\n\n#### Sentinel error placement\n\nAn exception to this rule is when wrapping sentinel errors. A sentinel error is\nan error that serves as a primary categorization of a failure. This helps\nobservers quickly understand the nature of a failure (such as \"not found\" or\n\"invalid argument\") without having to parse the entire error message.\nIdentifying that error type as early as possible in the error string is\nbeneficial.\n\nExamples of sentinel errors include os errors (e.g., [`os.ErrInvalid`]) and\npackage-level errors.\n\nIn these cases, placing the `%w` verb at the beginning of the error string can\nimprove readability by immediately identifying the category of the error.\n\n```go\n// Good:\npackage parser\n\nvar ErrParse = fmt.Errorf(\"parse error\")\n\n// This is another package error that could be returned.\nvar ErrParseInvalidHeader = fmt.Errorf(\"%w: invalid header\", ErrParse)\n\nfunc parseHeader() error {\n  err := checkHeader()\n  return fmt.Errorf(\"%w: invalid character in header: %v\", ErrParseInvalidHeader, err)\n}\n\nerr := fmt.Errorf(\"%w: couldn't find fortune database: %v\", ErrInternal, err)\n```\n\nPlacing the status at the beginning ensures that the most relevant categorical\ninformation is most prominent.\n\n```go\n// Bad:\npackage parser\n\nvar ErrParse = fmt.Errorf(\"parse error\")\n\n// This is another package error that could be returned.\nvar ErrParseInvalidHeader = fmt.Errorf(\"%w: invalid header\", ErrParse)\n\nfunc parseHeader() error {\n  err := checkHeader()\n  return fmt.Errorf(\"invalid character in header: %v: %w\", err, ErrParseInvalidHeader)\n}\n\nvar ErrInternal = status.Error(codes.Internal, \"internal\")\nerr2 := fmt.Errorf(\"couldn't find fortune database: %v: %w\", err, ErrInternal)\n```\n\nWhen you place it at the end, it makes it harder to identify the error category\nwhen reading the error text, as it's buried in the specific error details.\n\n[`os.ErrInvalid`]: https://pkg.go.dev/os#ErrInvalid\n\nSee also:\n\n*   [Go Tip #48: Error Sentinel Values]\n*   [Go Tip #106: Error Naming Conventions]\n\n[commentary]: decisions#commentary\n[Go Tip #48: Error Sentinel Values]: https://google.github.io/styleguide/go/index.html#gotip\n[Go Tip #106: Error Naming Conventions]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"error-logging\"></a>\n\n### Logging errors\n\nFunctions sometimes need to tell an external system about an error without\npropagating it to their callers. Logging is an obvious choice here; but be\nconscious of what and how you log errors.\n\n*   Like [good test failure messages], log messages should clearly express what\n    went wrong and help the maintainer by including relevant information to\n    diagnose the problem.\n\n*   Avoid duplication. If you return an error, it's usually better not to log it\n    yourself but rather let the caller handle it. The caller can choose to log\n    the error, or perhaps rate-limit logging using [`rate.Sometimes`]. Other\n    options include attempting recovery or even [stopping the program]. In any\n    case, giving the caller control helps avoid logspam.\n\n    The downside to this approach, however, is that any logging is written using\n    the caller's line coordinates.\n\n*   Be careful with [PII]. Many log sinks are not appropriate destinations for\n    sensitive end-user information.\n\n*   Use `log.Error` sparingly. ERROR level logging causes a flush and is more\n    expensive than lower logging levels. This can have serious performance\n    impact on your code. When deciding between error and warning levels,\n    consider the best practice that messages at the error level should be\n    actionable rather than \"more serious\" than a warning.\n\n*   Inside Google, we have monitoring systems that can be set up for more\n    effective alerting than writing to a log file and hoping someone notices it.\n    This is similar but not identical to the standard library\n    [package `expvar`].\n\n[good test failure messages]: https://google.github.io/styleguide/go/decisions#useful-test-failures\n[stopping the program]: #checks-and-panics\n[`rate.Sometimes`]: https://pkg.go.dev/golang.org/x/time/rate#Sometimes\n[PII]: https://en.wikipedia.org/wiki/Personal_data\n[package `expvar`]: https://pkg.go.dev/expvar\n\n<a id=\"vlog\"></a>\n\n#### Custom verbosity levels\n\nUse verbose logging ([`log.V`]) to your advantage. Verbose logging can be useful\nfor development and tracing. Establishing a convention around verbosity levels\ncan be helpful. For example:\n\n*   Write a small amount of extra information at `V(1)`\n*   Trace more information in `V(2)`\n*   Dump large internal states in `V(3)`\n\nTo minimize the cost of verbose logging, you should ensure not to accidentally\ncall expensive functions even when `log.V` is turned off. `log.V` offers two\nAPIs. The more convenient one carries the risk of this accidental expense. When\nin doubt, use the slightly more verbose style.\n\n```go\n// Good:\nfor _, sql := range queries {\n  log.V(1).Infof(\"Handling %v\", sql)\n  if log.V(2) {\n    log.Infof(\"Handling %v\", sql.Explain())\n  }\n  sql.Run(...)\n}\n```\n\n```go\n// Bad:\n// sql.Explain called even when this log is not printed.\nlog.V(2).Infof(\"Handling %v\", sql.Explain())\n```\n\n[`log.V`]: https://pkg.go.dev/github.com/golang/glog#V\n\n<a id=\"program-init\"></a>\n\n### Program initialization\n\nProgram initialization errors (such as bad flags and configuration) should be\npropagated upward to `main`, which should call `log.Exit` with an error that\nexplains how to fix the error. In these cases, `log.Fatal` should not generally\nbe used, because a stack trace that points at the check is not likely to be as\nuseful as a human-generated, actionable message.\n\n<a id=\"checks-and-panics\"></a>\n\n### Program checks and panics\n\nAs stated in the [decision against panics], standard error handling should be\nstructured around error return values. Libraries should prefer returning an\nerror to the caller rather than aborting the program, especially for transient\nerrors.\n\nIt is occasionally necessary to perform consistency checks on an invariant and\nterminate the program if it is violated. In general, this is only done when a\nfailure of the invariant check means that the internal state has become\nunrecoverable. The most reliable way to do this in the Google codebase is to\ncall `log.Fatal`. Using `panic` in these cases is not reliable, because it is\npossible for deferred functions to deadlock or further corrupt internal or\nexternal state.\n\nSimilarly, resist the temptation to recover panics to avoid crashes, as doing so\ncan result in propagating a corrupted state. The further you are from the panic,\nthe less you know about the state of the program, which could be holding locks\nor other resources. The program can then develop other unexpected failure modes\nthat can make the problem even more difficult to diagnose. Instead of trying to\nhandle unexpected panics in code, use monitoring tools to surface unexpected\nfailures and fix related bugs with a high priority.\n\n**Note:** The standard [`net/http` server] violates this advice and recovers\npanics from request handlers. Consensus among experienced Go engineers is that\nthis was a historical mistake. If you sample server logs from application\nservers in other languages, it is common to find large stacktraces that are left\nunhandled. Avoid this pitfall in your servers.\n\n[decision against panics]: https://google.github.io/styleguide/go/decisions#dont-panic\n[`net/http` server]: https://pkg.go.dev/net/http#Server\n\n<a id=\"when-to-panic\"></a>\n\n### When to panic\n\nThe standard library panics on API misuse. For example, [`reflect`] issues a\npanic in many cases where a value is accessed in a way that suggests it was\nmisinterpreted. This is analogous to the panics on core language bugs such as\naccessing an element of a slice that is out of bounds. Code review and tests\nshould discover such bugs, which are not expected to appear in production code.\nThese panics act as invariant checks that do not depend on a library, as the\nstandard library does not have access to the [levelled `log`] package that the\nGoogle codebase uses.\n\n[`reflect`]: https://pkg.go.dev/reflect\n[levelled `log`]: decisions#logging\n\nAnother case in which panics can be useful, though uncommon, is as an internal\nimplementation detail of a package which always has a matching recover in the\ncallchain. Parsers and similar deeply nested, tightly coupled internal function\ngroups can benefit from this design, where plumbing error returns adds\ncomplexity without value.\n\nThe key attribute of this design is that these **panics are never allowed to\nescape across package boundaries** and do not form part of the package's API.\nThis is typically accomplished with a top-level deferred function that uses\n`recover` to translate a propagated panic into a returned error at the public\nAPI boundary. It requires the code that panics and recovers to distinguish\nbetween panics that the code raises itself and those that it doesn't:\n\n```go\n// Good:\ntype syntaxError struct {\n  msg string\n}\n\nfunc parseInt(in string) int {\n  n, err := strconv.Atoi(in)\n  if err != nil {\n    panic(&syntaxError{\"not a valid integer\"})\n  }\n}\n\nfunc Parse(in string) (_ *Node, err error) {\n  defer func() {\n    if p := recover(); p != nil {\n      sErr, ok := p.(*syntaxError)\n      if !ok {\n        panic(p) // Propagate the panic since it is outside our code's domain.\n      }\n      err = fmt.Errorf(\"syntax error: %v\", sErr.msg)\n    }\n  }()\n  ... // Parse input calling parseInt internally to parse integers\n}\n```\n\n> **Warning:** Code employing this pattern must take care to manage any\n> resources associated with the code run in such defer-managed sections (e.g.,\n> close, free, or unlock).\n>\n> See: [Go Tip #81: Avoiding Resource Leaks in API Design]\n\nPanic is also used when the compiler cannot identify unreachable code, for\nexample when using a function like `log.Fatal` that will not return:\n\n```go\n// Good:\nfunc answer(i int) string {\n    switch i {\n    case 42:\n        return \"yup\"\n    case 54:\n        return \"base 13, huh\"\n    default:\n        log.Fatalf(\"Sorry, %d is not the answer.\", i)\n        panic(\"unreachable\")\n    }\n}\n```\n\n[Do not call `log` functions before flags have been parsed.](https://pkg.go.dev/github.com/golang/glog#pkg-overview)\nIf you must die in a package initialization function (an `init` or a\n[\"must\" function](decisions#must-functions)), a panic is acceptable in place of\nthe fatal logging call.\n\nSee also:\n\n*   [Handling panics](https://go.dev/ref/spec#Handling_panics) and\n    [Run-time Panics](https://go.dev/ref/spec#Run_time_panics) in the language\n    specification\n*   [Defer, Panic, and Recover](https://go.dev/blog/defer-panic-and-recover)\n*   [On the uses and misuses of panics in Go](https://eli.thegreenplace.net/2018/on-the-uses-and-misuses-of-panics-in-go/)\n\n[Go Tip #81: Avoiding Resource Leaks in API Design]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"documentation\"></a>\n\n## Documentation\n\n<a id=\"documentation-conventions\"></a>\n\n### Conventions\n\nThis section augments the decisions document's [commentary] section.\n\nGo code that is documented in familiar style is easier to read and less likely\nto be misused than something misdocumented or not documented at all. Runnable\n[examples] show up in Godoc and Code Search and are an excellent way of\nexplaining how to use your code.\n\n[examples]: decisions#examples\n\n<a id=\"documentation-conventions-params\"></a>\n\n#### Parameters and configuration\n\nNot every parameter must be enumerated in the documentation. This applies to:\n\n*   function and method parameters\n*   struct fields\n*   APIs for options\n\nDocument the error-prone or non-obvious fields and parameters by saying why they\nare interesting.\n\nIn the following snippet, the highlighted commentary adds little useful\ninformation to the reader:\n\n```go\n// Bad:\n// Sprintf formats according to a format specifier and returns the resulting\n// string.\n//\n// format is the format, and data is the interpolation data.\nfunc Sprintf(format string, data ...any) string\n```\n\nHowever, this snippet demonstrates a code scenario similar to the previous where\nthe commentary instead states something non-obvious or materially helpful to the\nreader:\n\n```go\n// Good:\n// Sprintf formats according to a format specifier and returns the resulting\n// string.\n//\n// The provided data is used to interpolate the format string. If the data does\n// not match the expected format verbs or the amount of data does not satisfy\n// the format specification, the function will inline warnings about formatting\n// errors into the output string as described by the Format errors section\n// above.\nfunc Sprintf(format string, data ...any) string\n```\n\nConsider your likely audience in choosing what to document and at what depth.\nMaintainers, newcomers to the team, external users, and even yourself six months\nin the future may appreciate slightly different information from what is on your\nmind when you first come to write your docs.\n\nSee also:\n\n*   [GoTip #41: Identify Function Call Parameters]\n*   [GoTip #51: Patterns for Configuration]\n\n[commentary]: decisions#commentary\n[GoTip #41: Identify Function Call Parameters]: https://google.github.io/styleguide/go/index.html#gotip\n[GoTip #51: Patterns for Configuration]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"documentation-conventions-contexts\"></a>\n\n#### Contexts\n\nIt is implied that the cancellation of a context argument interrupts the\nfunction it is provided to. If the function can return an error, conventionally\nit is `ctx.Err()`.\n\nThis fact does not need to be restated:\n\n```go\n// Bad:\n// Run executes the worker's run loop.\n//\n// The method will process work until the context is cancelled and accordingly\n// returns an error.\nfunc (Worker) Run(ctx context.Context) error\n```\n\nBecause that is implied, the following is better:\n\n```go\n// Good:\n// Run executes the worker's run loop.\nfunc (Worker) Run(ctx context.Context) error\n```\n\nWhere context behavior is different or non-obvious, it should be expressly\ndocumented if any of the following are true.\n\n*   The function returns an error other than `ctx.Err()` when the context is\n    cancelled:\n\n    ```go\n    // Good:\n    // Run executes the worker's run loop.\n    //\n    // If the context is cancelled, Run returns a nil error.\n    func (Worker) Run(ctx context.Context) error\n    ```\n\n*   The function has other mechanisms that may interrupt it or affect lifetime:\n\n    ```go\n    // Good:\n    // Run executes the worker's run loop.\n    //\n    // Run processes work until the context is cancelled or Stop is called.\n    // Context cancellation is handled asynchronously internally: run may return\n    // before all work has stopped. The Stop method is synchronous and waits\n    // until all operations from the run loop finish. Use Stop for graceful\n    // shutdown.\n    func (Worker) Run(ctx context.Context) error\n\n    func (Worker) Stop()\n    ```\n\n*   The function has special expectations about context lifetime, lineage, or\n    attached values:\n\n    ```go\n    // Good:\n    // NewReceiver starts receiving messages sent to the specified queue.\n    // The context should not have a deadline.\n    func NewReceiver(ctx context.Context) *Receiver\n\n    // Principal returns a human-readable name of the party who made the call.\n    // The context must have a value attached to it from security.NewContext.\n    func Principal(ctx context.Context) (name string, ok bool)\n    ```\n\n    **Warning:** Avoid designing APIs that make such demands (like contexts not\n    having deadlines) from their callers. The above is only an example of how to\n    document this if it cannot be avoided, not an endorsement of the pattern.\n\n<a id=\"documentation-conventions-concurrency\"></a>\n\n#### Concurrency\n\nGo users assume that conceptually read-only operations are safe for concurrent\nuse and do not require extra synchronization.\n\nThe extra remark about concurrency can safely be removed in this Godoc:\n\n```go\n// Len returns the number of bytes of the unread portion of the buffer;\n// b.Len() == len(b.Bytes()).\n//\n// It is safe to be called concurrently by multiple goroutines.\nfunc (*Buffer) Len() int\n```\n\nMutating operations, however, are not assumed to be safe for concurrent use and\nrequire the user to consider synchronization.\n\nSimilarly, the extra remark about concurrency can safely be removed here:\n\n```go\n// Grow grows the buffer's capacity.\n//\n// It is not safe to be called concurrently by multiple goroutines.\nfunc (*Buffer) Grow(n int)\n```\n\nDocumentation is strongly encouraged if any of the following are true.\n\n*   It is unclear whether the operation is read-only or mutating:\n\n    ```go\n    // Good:\n    package lrucache\n\n    // Lookup returns the data associated with the key from the cache.\n    //\n    // This operation is not safe for concurrent use.\n    func (*Cache) Lookup(key string) (data []byte, ok bool)\n    ```\n\n    Why? A cache hit when looking up the key mutate a LRU cache internally. How\n    this is implemented may not be obvious to all readers.\n\n*   Synchronization is provided by the API:\n\n    ```go\n    // Good:\n    package fortune_go_proto\n\n    // NewFortuneTellerClient returns an *rpc.Client for the FortuneTeller service.\n    // It is safe for simultaneous use by multiple goroutines.\n    func NewFortuneTellerClient(cc *rpc.ClientConn) *FortuneTellerClient\n    ```\n\n    Why? Stubby provides synchronization.\n\n    **Note:** If the API is a type and the API provides synchronization in\n    entirety, conventionally only the type definition documents the semantics.\n\n*   The API consumes user-implemented types of interfaces, and the interface's\n    consumer has particular concurrency requirements:\n\n    ```go\n    // Good:\n    package health\n\n    // A Watcher reports the health of some entity (usually a backend service).\n    //\n    // Watcher methods are safe for simultaneous use by multiple goroutines.\n    type Watcher interface {\n        // Watch sends true on the passed-in channel when the Watcher's\n        // status has changed.\n        Watch(changed chan<- bool) (unwatch func())\n\n        // Health returns nil if the entity being watched is healthy, or a\n        // non-nil error explaining why the entity is not healthy.\n        Health() error\n    }\n    ```\n\n    Why? Whether an API is safe for use by multiple goroutines is part of its\n    contract.\n\n<a id=\"documentation-conventions-cleanup\"></a>\n\n#### Cleanup\n\nDocument any explicit cleanup requirements that the API has. Otherwise, callers\nwon't use the API correctly, leading to resource leaks and other possible bugs.\n\nCall out cleanups that are up to the caller:\n\n```go\n// Good:\n// NewTicker returns a new Ticker containing a channel that will send the\n// current time on the channel after each tick.\n//\n// Call Stop to release the Ticker's associated resources when done.\nfunc NewTicker(d Duration) *Ticker\n\nfunc (*Ticker) Stop()\n```\n\nIf it is potentially unclear how to clean up the resources, explain how:\n\n```go\n// Good:\n// Get issues a GET to the specified URL.\n//\n// When err is nil, resp always contains a non-nil resp.Body.\n// Caller should close resp.Body when done reading from it.\n//\n//    resp, err := http.Get(\"http://example.com/\")\n//    if err != nil {\n//        // handle error\n//    }\n//    defer resp.Body.Close()\n//    body, err := io.ReadAll(resp.Body)\nfunc (c *Client) Get(url string) (resp *Response, err error)\n```\n\nSee also:\n\n*   [GoTip #110: Don’t Mix Exit With Defer]\n\n[GoTip #110: Don’t Mix Exit With Defer]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"documentation-conventions-errors\"></a>\n\n#### Errors\n\nDocument significant error sentinel values or error types that your functions\nreturn to callers so that callers can anticipate what types of conditions they\ncan handle in their code.\n\n```go\n// Good:\npackage os\n\n// Read reads up to len(b) bytes from the File and stores them in b. It returns\n// the number of bytes read and any error encountered.\n//\n// At end of file, Read returns 0, io.EOF.\nfunc (*File) Read(b []byte) (n int, err error) {\n```\n\nWhen a function returns a specific error type, correctly note whether the error\nis a pointer receiver or not:\n\n```go\n// Good:\npackage os\n\ntype PathError struct {\n    Op   string\n    Path string\n    Err  error\n}\n\n// Chdir changes the current working directory to the named directory.\n//\n// If there is an error, it will be of type *PathError.\nfunc Chdir(dir string) error {\n```\n\nDocumenting whether the values returned are pointer receivers enables callers to\ncorrectly compare the errors using [`errors.Is`], [`errors.As`], and\n[`package cmp`]. This is because a non-pointer value is not equivalent to a\npointer value.\n\n**Note:** In the `Chdir` example, the return type is written as `error` rather\nthan `*PathError` due to\n[how nil interface values work](https://go.dev/doc/faq#nil_error).\n\nDocument overall error conventions in the\n[package's documentation](decisions#package-comments) when the behavior is\napplicable to most errors found in the package:\n\n```go\n// Good:\n// Package os provides a platform-independent interface to operating system\n// functionality.\n//\n// Often, more information is available within the error. For example, if a\n// call that takes a file name fails, such as Open or Stat, the error will\n// include the failing file name when printed and will be of type *PathError,\n// which may be unpacked for more information.\npackage os\n```\n\nThoughtful application of these approaches can add\n[extra information to errors](#error-extra-info) without much effort and help\ncallers avoid adding redundant annotations.\n\nSee also:\n\n*   [Go Tip #106: Error Naming Conventions](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #89: When to Use Canonical Status Codes as Errors](https://google.github.io/styleguide/go/index.html#gotip)\n\n<a id=\"documentation-preview\"></a>\n\n### Preview\n\nGo features a\n[documentation server](https://pkg.go.dev/golang.org/x/pkgsite/cmd/pkgsite). It\nis recommended to preview the documentation your code produces both before and\nduring the code review process. This helps to validate that the\n[godoc formatting] is rendered correctly.\n\n[godoc formatting]: #godoc-formatting\n\n<a id=\"godoc-formatting\"></a>\n\n### Godoc formatting\n\n[Godoc] provides some specific syntax to [format documentation].\n\n*   A blank line is required to separate paragraphs:\n\n    ```go\n    // Good:\n    // LoadConfig reads a configuration out of the named file.\n    //\n    // See some/shortlink for config file format details.\n    ```\n\n*   Test files can contain [runnable examples] that appear attached to the\n    corresponding documentation in godoc:\n\n    ```go\n    // Good:\n    func ExampleConfig_WriteTo() {\n      cfg := &Config{\n        Name: \"example\",\n      }\n      if err := cfg.WriteTo(os.Stdout); err != nil {\n        log.Exitf(\"Failed to write config: %s\", err)\n      }\n      // Output:\n      // {\n      //   \"name\": \"example\"\n      // }\n    }\n    ```\n\n*   Indenting lines by an additional two spaces formats them verbatim:\n\n    ```go\n    // Good:\n    // Update runs the function in an atomic transaction.\n    //\n    // This is typically used with an anonymous TransactionFunc:\n    //\n    //   if err := db.Update(func(state *State) { state.Foo = bar }); err != nil {\n    //     //...\n    //   }\n    ```\n\n    Note, however, that it can often be more appropriate to put code in a\n    runnable example instead of including it in a comment.\n\n    This verbatim formatting can be leveraged for formatting that is not native\n    to godoc, such as lists and tables:\n\n    ```go\n    // Good:\n    // LoadConfig reads a configuration out of the named file.\n    //\n    // LoadConfig treats the following keys in special ways:\n    //   \"import\" will make this configuration inherit from the named file.\n    //   \"env\" if present will be populated with the system environment.\n    ```\n\n*   A single line that begins with a capital letter, contains no punctuation\n    except parentheses and commas, and is followed by another paragraph, is\n    formatted as a header:\n\n    ```go\n    // Good:\n    // The following line is formatted as a heading.\n    //\n    // Using headings\n    //\n    // Headings come with autogenerated anchor tags for easy linking.\n    ```\n\n[Godoc]: https://pkg.go.dev/\n[format documentation]: https://go.dev/doc/comment\n[runnable examples]: decisions#examples\n\n<a id=\"signal-boost\"></a>\n\n### Signal boosting\n\nSometimes a line of code looks like something common, but actually isn't. One of\nthe best examples of this is an `err == nil` check (since `err != nil` is much\nmore common). The following two conditional checks are hard to distinguish:\n\n```go\n// Good:\nif err := doSomething(); err != nil {\n    // ...\n}\n```\n\n```go\n// Bad:\nif err := doSomething(); err == nil {\n    // ...\n}\n```\n\nYou can instead \"boost\" the signal of the conditional by adding a comment:\n\n```go\n// Good:\nif err := doSomething(); err == nil { // if NO error\n    // ...\n}\n```\n\nThe comment draws attention to the difference in the conditional.\n\n<a id=\"vardecls\"></a>\n\n## Variable declarations\n\n<a id=\"vardeclinitialization\"></a>\n\n### Initialization\n\nFor consistency, prefer `:=` over `var` when initializing a new variable with a\nnon-zero value.\n\n```go\n// Good:\ni := 42\n```\n\n```go\n// Bad:\nvar i = 42\n```\n\n<a id=\"vardeclzero\"></a>\n\n### Declaring variables with zero values\n\nThe following declarations use the [zero value]:\n\n```go\n// Good:\nvar (\n    coords Point\n    magic  [4]byte\n    primes []int\n)\n```\n\n[zero value]: https://golang.org/ref/spec#The_zero_value\n\nYou should declare values using the zero value when you want to convey an empty\nvalue that **is ready for later use**. Using composite literals with explicit\ninitialization can be clunky:\n\n```go\n// Bad:\nvar (\n    coords = Point{X: 0, Y: 0}\n    magic  = [4]byte{0, 0, 0, 0}\n    primes = []int(nil)\n)\n```\n\nA common application of zero value declaration is when using a variable as the\noutput when unmarshalling:\n\n```go\n// Good:\nvar coords Point\nif err := json.Unmarshal(data, &coords); err != nil {\n```\n\nIt is also okay to use the zero value in the following form when you need a\nvariable of a pointer type:\n\n```go\n// Good:\nmsg := new(pb.Bar) // or \"&pb.Bar{}\"\nif err := proto.Unmarshal(data, msg); err != nil {\n```\n\nIf you need a lock or other field that [must not be copied](decisions#copying)\nin your struct, you can make it a value type to take advantage of zero value\ninitialization. It does mean that the containing type must now be passed via a\npointer and not a value. Methods on the type must take pointer receivers.\n\n```go\n// Good:\ntype Counter struct {\n    // This field does not have to be \"*sync.Mutex\". However,\n    // users must now pass *Counter objects between themselves, not Counter.\n    mu   sync.Mutex\n    data map[string]int64\n}\n\n// Note this must be a pointer receiver to prevent copying.\nfunc (c *Counter) IncrementBy(name string, n int64)\n```\n\nIt's acceptable to use value types for local variables of composites (such as\nstructs and arrays) even if they contain such uncopyable fields. However, if the\ncomposite is returned by the function, or if all accesses to it end up needing\nto take an address anyway, prefer declaring the variable as a pointer type at\nthe outset. Similarly, protobuf messages should be declared as pointer types.\n\n```go\n// Good:\nfunc NewCounter(name string) *Counter {\n    c := new(Counter) // \"&Counter{}\" is also fine.\n    registerCounter(name, c)\n    return c\n}\n\nvar msg = new(pb.Bar) // or \"&pb.Bar{}\".\n```\n\nThis is because `*pb.Something` satisfies [`proto.Message`] while `pb.Something`\ndoes not.\n\n```go\n// Bad:\nfunc NewCounter(name string) *Counter {\n    var c Counter\n    registerCounter(name, &c)\n    return &c\n}\n\nvar msg = pb.Bar{}\n```\n\n[`proto.Message`]: https://pkg.go.dev/google.golang.org/protobuf/proto#Message\n\n> **Important:** Map types must be explicitly initialized before they can be\n> modified. However, reading from zero-value maps is perfectly fine.\n>\n> For map and slice types, if the code is particularly performance sensitive and\n> if you know the sizes in advance, see the [size hints](#vardeclsize) section.\n\n<a id=\"vardeclcomposite\"></a>\n\n### Composite literals\n\nThe following are [composite literal] declarations:\n\n```go\n// Good:\nvar (\n    coords   = Point{X: x, Y: y}\n    magic    = [4]byte{'I', 'W', 'A', 'D'}\n    primes   = []int{2, 3, 5, 7, 11}\n    captains = map[string]string{\"Kirk\": \"James Tiberius\", \"Picard\": \"Jean-Luc\"}\n)\n```\n\nYou should declare a value using a composite literal when you know initial\nelements or members.\n\nIn contrast, using composite literals to declare empty or memberless values can\nbe visually noisy compared to [zero-value initialization](#vardeclzero).\n\nWhen you need a pointer to a zero value, you have two options: empty composite\nliterals and `new`. Both are fine, but the `new` keyword can serve to remind the\nreader that if a non-zero value were needed, a composite literal wouldn't work:\n\n```go\n// Good:\nvar (\n  buf = new(bytes.Buffer) // non-empty Buffers are initialized with constructors.\n  msg = new(pb.Message) // non-empty proto messages are initialized with builders or by setting fields one by one.\n)\n```\n\n[composite literal]: https://golang.org/ref/spec#Composite_literals\n\n<a id=\"vardeclsize\"></a>\n\n### Size hints\n\nThe following are declarations that take advantage of size hints in order to\npreallocate capacity:\n\n```go\n// Good:\nvar (\n    // Preferred buffer size for target filesystem: st_blksize.\n    buf = make([]byte, 131072)\n    // Typically process up to 8-10 elements per run (16 is a safe assumption).\n    q = make([]Node, 0, 16)\n    // Each shard processes shardSize (typically 32000+) elements.\n    seen = make(map[string]bool, shardSize)\n)\n```\n\nSize hints and preallocation are important steps **when combined with empirical\nanalysis of the code and its integrations**, to create performance-sensitive and\nresource-efficient code.\n\nMost code does not need a size hint or preallocation, and can allow the runtime\nto grow the slice or map as necessary. It is acceptable to preallocate when the\nfinal size is known (e.g. when converting between a map and a slice) but this is\nnot a readability requirement, and may not be worth the clutter in small cases.\n\n**Warning:** Preallocating more memory than you need can waste memory in the\nfleet or even harm performance. When in doubt, see\n[GoTip #3: Benchmarking Go Code] and default to a\n[zero initialization](#vardeclzero) or a\n[composite literal declaration](#vardeclcomposite).\n\n[GoTip #3: Benchmarking Go Code]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"decl-chan\"></a>\n\n### Channel direction\n\nSpecify [channel direction] where possible.\n\n```go\n// Good:\n// sum computes the sum of all of the values. It reads from the channel until\n// the channel is closed.\nfunc sum(values <-chan int) int {\n    // ...\n}\n```\n\nThis prevents casual programming errors that are possible without specification:\n\n```go\n// Bad:\nfunc sum(values chan int) (out int) {\n    for v := range values {\n        out += v\n    }\n    // values must already be closed for this code to be reachable, which means\n    // a second close triggers a panic.\n    close(values)\n}\n```\n\nWhen the direction is specified, the compiler catches simple errors like this.\nIt also helps to convey a measure of ownership to the type.\n\nSee also Bryan Mills' talk \"Rethinking Classical Concurrency Patterns\":\n[slides][rethinking-concurrency-slides] [video][rethinking-concurrency-video].\n\n[rethinking-concurrency-slides]: https://drive.google.com/file/d/1nPdvhB0PutEJzdCq5ms6UI58dp50fcAN/view?usp=sharing\n[rethinking-concurrency-video]: https://www.youtube.com/watch?v=5zXAHh5tJqQ\n[channel direction]: https://go.dev/ref/spec#Channel_types\n\n<a id=\"funcargs\"></a>\n\n## Function argument lists\n\nDon't let the signature of a function get too long. As more parameters are added\nto a function, the role of individual parameters becomes less clear, and\nadjacent parameters of the same type become easier to confuse. Functions with\nlarge numbers of arguments are less memorable and more difficult to read at the\ncall-site.\n\nWhen designing an API, consider splitting a highly configurable function whose\nsignature is growing complex into several simpler ones. These can share an\n(unexported) implementation if necessary.\n\nWhere a function requires many inputs, consider introducing an [option struct]\nfor some of the arguments or employing the more advanced [variadic options]\ntechnique. The primary consideration for which strategy to choose should be how\nthe function call looks across all expected use cases.\n\nThe recommendations below primarily apply to exported APIs, which are held to a\nhigher standard than unexported ones. These techniques may be unnecessary for\nyour use case. Use your judgment, and balance the principles of [clarity] and\n[least mechanism].\n\nSee also:\n[Go Tip #24: Use Case-Specific Constructions](https://google.github.io/styleguide/go/index.html#gotip)\n\n[option struct]: #option-structure\n[variadic options]: #variadic-options\n[clarity]: guide#clarity\n[least mechanism]: guide#least-mechanism\n\n<a id=\"option-structure\"></a>\n\n### Option structure\n\nAn option structure is a struct type that collects some or all of the arguments\nof a function or method, that is then passed as the last argument to the\nfunction or method. (The struct should be exported only if it is used in an\nexported function.)\n\nUsing an option structure has a number of benefits:\n\n*   The struct literal includes both fields and values for each argument, which\n    makes them self-documenting and harder to swap.\n*   Irrelevant or \"default\" fields can be omitted.\n*   Callers can share the option struct and write helpers to operate on it.\n*   Structs provide cleaner per-field documentation than function arguments.\n*   Option structs can grow over time without impacting call-sites.\n\nHere is an example of a function that could be improved:\n\n```go\n// Bad:\nfunc EnableReplication(ctx context.Context, config *replicator.Config, primaryRegions, readonlyRegions []string, replicateExisting, overwritePolicies bool, replicationInterval time.Duration, copyWorkers int, healthWatcher health.Watcher) {\n    // ...\n}\n```\n\nThe function above could be rewritten with an option structure as follows:\n\n```go\n// Good:\ntype ReplicationOptions struct {\n    Config              *replicator.Config\n    PrimaryRegions      []string\n    ReadonlyRegions     []string\n    ReplicateExisting   bool\n    OverwritePolicies   bool\n    ReplicationInterval time.Duration\n    CopyWorkers         int\n    HealthWatcher       health.Watcher\n}\n\nfunc EnableReplication(ctx context.Context, opts ReplicationOptions) {\n    // ...\n}\n```\n\nThe function can then be called in a different package:\n\n```go\n// Good:\nfunc foo(ctx context.Context) {\n    // Complex call:\n    storage.EnableReplication(ctx, storage.ReplicationOptions{\n        Config:              config,\n        PrimaryRegions:      []string{\"us-east1\", \"us-central2\", \"us-west3\"},\n        ReadonlyRegions:     []string{\"us-east5\", \"us-central6\"},\n        OverwritePolicies:   true,\n        ReplicationInterval: 1 * time.Hour,\n        CopyWorkers:         100,\n        HealthWatcher:       watcher,\n    })\n\n    // Simple call:\n    storage.EnableReplication(ctx, storage.ReplicationOptions{\n        Config:         config,\n        PrimaryRegions: []string{\"us-east1\", \"us-central2\", \"us-west3\"},\n    })\n}\n```\n\n**Note:** [Contexts are never included in option structs](decisions#contexts).\n\nThis option is often preferred when some of the following apply:\n\n*   All callers need to specify one or more of the options.\n*   A large number of callers need to provide many options.\n*   The options are shared between multiple functions that the user will call.\n\n<a id=\"variadic-options\"></a>\n\n### Variadic options\n\nUsing variadic options, exported functions are created which return closures\nthat can be passed to the [variadic (`...`) parameter] of a function. The\nfunction takes as its parameters the values of the option (if any), and the\nreturned closure accepts a mutable reference (usually a pointer to a struct\ntype) that will be updated based on the inputs.\n\n[variadic (`...`) parameter]: https://golang.org/ref/spec#Passing_arguments_to_..._parameters\n\nUsing variadic options can provide a number of benefits:\n\n*   Options take no space at a call-site when no configuration is needed.\n*   Options are still values, so callers can share them, write helpers, and\n    accumulate them.\n*   Options can accept multiple parameters (e.g. `cartesian.Translate(dx, dy\n    int) TransformOption`).\n*   The option functions can return a named type to group options together in\n    godoc.\n*   Packages can allow (or prevent) third-party packages to define (or from\n    defining) their own options.\n\n**Note:** Using variadic options requires a substantial amount of additional\ncode (see the following example), so it should only be used when the advantages\noutweigh the overhead.\n\nHere is an example of a function that could be improved:\n\n```go\n// Bad:\nfunc EnableReplication(ctx context.Context, config *placer.Config, primaryCells, readonlyCells []string, replicateExisting, overwritePolicies bool, replicationInterval time.Duration, copyWorkers int, healthWatcher health.Watcher) {\n  ...\n}\n```\n\nThe example above could be rewritten with variadic options as follows:\n\n```go\n// Good:\ntype replicationOptions struct {\n    readonlyCells       []string\n    replicateExisting   bool\n    overwritePolicies   bool\n    replicationInterval time.Duration\n    copyWorkers         int\n    healthWatcher       health.Watcher\n}\n\n// A ReplicationOption configures EnableReplication.\ntype ReplicationOption func(*replicationOptions)\n\n// ReadonlyCells adds additional cells that should additionally\n// contain read-only replicas of the data.\n//\n// Passing this option multiple times will add additional\n// read-only cells.\n//\n// Default: none\nfunc ReadonlyCells(cells ...string) ReplicationOption {\n    return func(opts *replicationOptions) {\n        opts.readonlyCells = append(opts.readonlyCells, cells...)\n    }\n}\n\n// ReplicateExisting controls whether files that already exist in the\n// primary cells will be replicated.  Otherwise, only newly-added\n// files will be candidates for replication.\n//\n// Passing this option again will overwrite earlier values.\n//\n// Default: false\nfunc ReplicateExisting(enabled bool) ReplicationOption {\n    return func(opts *replicationOptions) {\n        opts.replicateExisting = enabled\n    }\n}\n\n// ... other options ...\n\n// DefaultReplicationOptions control the default values before\n// applying options passed to EnableReplication.\nvar DefaultReplicationOptions = []ReplicationOption{\n    OverwritePolicies(true),\n    ReplicationInterval(12 * time.Hour),\n    CopyWorkers(10),\n}\n\nfunc EnableReplication(ctx context.Context, config *placer.Config, primaryCells []string, opts ...ReplicationOption) {\n    var options replicationOptions\n    for _, opt := range DefaultReplicationOptions {\n        opt(&options)\n    }\n    for _, opt := range opts {\n        opt(&options)\n    }\n}\n```\n\nThe function can then be called in a different package:\n\n```go\n// Good:\nfunc foo(ctx context.Context) {\n    // Complex call:\n    storage.EnableReplication(ctx, config, []string{\"po\", \"is\", \"ea\"},\n        storage.ReadonlyCells(\"ix\", \"gg\"),\n        storage.OverwritePolicies(true),\n        storage.ReplicationInterval(1*time.Hour),\n        storage.CopyWorkers(100),\n        storage.HealthWatcher(watcher),\n    )\n\n    // Simple call:\n    storage.EnableReplication(ctx, config, []string{\"po\", \"is\", \"ea\"})\n}\n```\n\nPrefer this option when many of the following apply:\n\n*   Most callers will not need to specify any options.\n*   Most options are used infrequently.\n*   There are a large number of options.\n*   Options require arguments.\n*   Options could fail or be set incorrectly (in which case the option function\n    returns an `error`).\n*   Options require a lot of documentation that can be hard to fit in a struct.\n*   Users or other packages can provide custom options.\n\nOptions in this style should accept parameters rather than using presence to\nsignal their value; the latter can make dynamic composition of arguments much\nmore difficult. For example, binary settings should accept a boolean (e.g.\n`rpc.FailFast(enable bool)` is preferable to `rpc.EnableFailFast()`). An\nenumerated option should accept an enumerated constant (e.g.\n`log.Format(log.Capacitor)` is preferable to `log.CapacitorFormat()`). The\nalternative makes it much more difficult for users who must programmatically\nchoose which options to pass; such users are forced to change the actual\ncomposition of the parameters rather than simply changing the arguments to the\noptions. Don't assume that all users will know the full set of options\nstatically.\n\nIn general, options should be processed in order. If there is a conflict or if a\nnon-cumulative option is passed multiple times, the last argument should win.\n\nThe parameter to the option function is generally unexported in this pattern, to\nrestrict the options to being defined only within the package itself. This is a\ngood default, though there may be times when it is appropriate to allow other\npackages to define options.\n\nSee [Rob Pike's original blog post] and [Dave Cheney's talk] for a more in-depth\nlook at how these options can be used.\n\n[Rob Pike's original blog post]: http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html\n[Dave Cheney's talk]: https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis\n\n<a id=\"complex-clis\"></a>\n\n## Complex command-line interfaces\n\nSome programs wish to present users with a rich command-line interface that\nincludes sub-commands. For example, `kubectl create`, `kubectl run`, and many\nother sub-commands are all provided by the program `kubectl`. There are at least\nthe following libraries in common use for achieving this.\n\nIf you don't have a preference or other considerations are equal, [subcommands]\nis recommended, since it is the simplest and is easy to use correctly. However,\nif you need different features that it doesn't provide, pick one of the other\noptions.\n\n*   **[cobra]**\n\n    *   Flag convention: getopt\n    *   Common outside the Google codebase.\n    *   Many extra features.\n    *   Pitfalls in usage (see below).\n\n*   **[subcommands]**\n\n    *   Flag convention: Go\n    *   Simple and easy to use correctly.\n    *   Recommended if you don't need extra features.\n\n**Warning**: cobra command functions should use `cmd.Context()` to obtain a\ncontext rather than creating their own root context with `context.Background`.\nCode that uses the subcommands package already receives the correct context as a\nfunction parameter.\n\nYou are not required to place each subcommand in a separate package, and it is\noften not necessary to do so. Apply the same considerations about package\nboundaries as in any Go codebase. If your code can be used both as a library and\nas a binary, it is usually beneficial to separate the CLI code and the library,\nmaking the CLI just one more of its clients. (This is not specific to CLIs that\nhave subcommands, but is mentioned here because it is a common place where it\ncomes up.)\n\n[subcommands]: https://pkg.go.dev/github.com/google/subcommands\n[cobra]: https://pkg.go.dev/github.com/spf13/cobra\n\n<a id=\"tests\"></a>\n\n## Tests\n\n<a id=\"test-functions\"></a>\n\n### Leave testing to the `Test` function\n\n<!-- Note to maintainers: This section overlaps with decisions#assert and\ndecisions#mark-test-helpers. The point is not to repeat information, but\nto have one place that summarizes the distinction that newcomers to the\nlanguage often wonder about. -->\n\nGo distinguishes between \"test helpers\" and \"assertion helpers\":\n\n*   **Test helpers** are functions that do setup or cleanup tasks. All failures\n    that occur in test helpers are expected to be failures of the environment\n    (not from the code under test) — for example when a test database cannot be\n    started because there are no more free ports on this machine. For functions\n    like these, calling `t.Helper` is often appropriate to\n    [mark them as a test helper]. See [error handling in test helpers] for more\n    details.\n\n*   **Assertion helpers** are functions that check the correctness of a system\n    and fail the test if an expectation is not met. Assertion helpers are\n    [not considered idiomatic] in Go.\n\nThe purpose of a test is to report pass/fail conditions of the code under test.\nThe ideal place to fail a test is within the `Test` function itself, as that\nensures that [failure messages] and the test logic are clear.\n\n[mark them as a test helper]: decisions#mark-test-helpers\n[error handling in test helpers]: #test-helper-error-handling\n[not considered idiomatic]: decisions#assert\n[failure messages]: decisions#useful-test-failures\n\nAs your testing code grows, it may become necessary to factor out some\nfunctionality to separate functions. Standard software engineering\nconsiderations still apply, as *test code is still code*. If the functionality\ndoes not interact with the testing framework, then all of the usual rules apply.\nWhen the common code interacts with the framework, however, some care must be\ntaken to avoid common pitfalls that can lead to uninformative failure messages\nand unmaintainable tests.\n\nIf many separate test cases require the same validation logic, arrange the test\nin one of the following ways instead of using assertion helpers or complex\nvalidation functions:\n\n*   Inline the logic (both the validation and the failure) in the `Test`\n    function, even if it is repetitive. This works best in simple cases.\n*   If inputs are similar, consider unifying them into a [table-driven test]\n    while keeping the logic inlined in the loop. This helps to avoid repetition\n    while keeping the validation and failure in the `Test`.\n*   If there are multiple callers who need the same validation function but\n    table tests are not suitable (typically because the inputs are not simple\n    enough or the validation is required as part of a sequence of operations),\n    arrange the validation function so that it returns a value (typically an\n    `error`) rather than taking a `testing.T` parameter and using it to fail the\n    test. Use logic within the `Test` to decide whether to fail, and to provide\n    [useful test failures]. You can also create test helpers to factor out\n    common boilerplate setup code.\n\nThe design outlined in the last point maintains orthogonality. For example,\n[package `cmp`] is not designed to fail tests, but rather to compare (and to\ndiff) values. It therefore does not need to know about the context in which the\ncomparison was made, since the caller can supply that. If your common testing\ncode provides a `cmp.Transformer` for your data type, that can often be the\nsimplest design. For other validations, consider returning an `error` value.\n\n```go\n// Good:\n// polygonCmp returns a cmp.Option that equates s2 geometry objects up to\n// some small floating-point error.\nfunc polygonCmp() cmp.Option {\n    return cmp.Options{\n        cmp.Transformer(\"polygon\", func(p *s2.Polygon) []*s2.Loop { return p.Loops() }),\n        cmp.Transformer(\"loop\", func(l *s2.Loop) []s2.Point { return l.Vertices() }),\n        cmpopts.EquateApprox(0.00000001, 0),\n        cmpopts.EquateEmpty(),\n    }\n}\n\nfunc TestFenceposts(t *testing.T) {\n    // This is a test for a fictional function, Fenceposts, which draws a fence\n    // around some Place object. The details are not important, except that\n    // the result is some object that has s2 geometry (github.com/golang/geo/s2)\n    got := Fencepost(tomsDiner, 1*meter)\n    if diff := cmp.Diff(want, got, polygonCmp()); diff != \"\" {\n        t.Errorf(\"Fencepost(tomsDiner, 1m) returned unexpected diff (-want+got):\\n%v\", diff)\n    }\n}\n\nfunc FuzzFencepost(f *testing.F) {\n    // Fuzz test (https://go.dev/doc/fuzz) for the same.\n\n    f.Add(tomsDiner, 1*meter)\n    f.Add(school, 3*meter)\n\n    f.Fuzz(func(t *testing.T, geo Place, padding Length) {\n        got := Fencepost(geo, padding)\n        // Simple reference implementation: not used in prod, but easy to\n        // reason about and therefore useful to check against in random tests.\n        reference := slowFencepost(geo, padding)\n\n        // In the fuzz test, inputs and outputs can be large so don't\n        // bother with printing a diff. cmp.Equal is enough.\n        if !cmp.Equal(got, reference, polygonCmp()) {\n            t.Errorf(\"Fencepost returned wrong placement\")\n        }\n    })\n}\n```\n\nThe `polygonCmp` function is agnostic about how it's called; it doesn't take a\nconcrete input type nor does it police what to do in case two objects don't\nmatch. Therefore, more callers can make use of it.\n\n**Note:** There is an analogy between test helpers and plain library code. Code\nin libraries should usually [not panic] except in rare circumstances; code\ncalled from a test should not stop the test unless there is\n[no point in proceeding].\n\n[table-driven test]: decisions#table-driven-tests\n[useful test failures]: decisions#useful-test-failures\n[package `cmp`]: https://pkg.go.dev/github.com/google/go-cmp/cmp\n[not panic]: decisions#dont-panic\n[no point in proceeding]: #t-fatal\n\n<a id=\"test-validation-apis\"></a>\n\n### Designing extensible validation APIs\n\nMost of the advice about testing in the style guide is about testing your own\ncode. This section is about how to provide facilities for other people to test\nthe code they write to ensure that it conforms to your library's requirements.\n\n<a id=\"test-validation-apis-what\"></a>\n\n#### Acceptance testing\n\nSuch testing is referred to as [acceptance testing]. The premise of this kind of\ntesting is that the person using the test does not know every last detail of\nwhat goes on in the test; they just hand the inputs over to the testing facility\nto do the work. This can be thought of as a form of [inversion of control].\n\nIn a typical Go test, the test function controls the program flow, and the\n[no assert](decisions#assert) and [test functions](#test-functions) guidance\nencourages you to keep it that way. This section explains how to author support\nfor these tests in a way that is consistent with Go style.\n\nBefore diving into how, consider an example from [`io/fs`], excerpted below:\n\n```go\ntype FS interface {\n    Open(name string) (File, error)\n}\n```\n\nWhile there exist well-known implementations of `fs.FS`, a Go developer may be\nexpected to author one. To help validate the user-implemented `fs.FS` is\ncorrect, a generic library has been provided in [`testing/fstest`] called\n[`fstest.TestFS`]. This API treats the implementation as a blackbox to make sure\nit upholds the most basic parts of the `io/fs` contract.\n\n[acceptance testing]: https://en.wikipedia.org/wiki/Acceptance_testing\n[inversion of control]: https://en.wikipedia.org/wiki/Inversion_of_control\n[`io/fs`]: https://pkg.go.dev/io/fs\n[`testing/fstest`]: https://pkg.go.dev/testing/fstest\n[`fstest.TestFS`]: https://pkg.go.dev/testing/fstest#TestFS\n\n<a id=\"test-validation-apis-writing\"></a>\n\n#### Writing an acceptance test\n\nNow that we know what an acceptance test is and why you might use one, let's\nexplore building an acceptance test for `package chess`, a package used to\nsimulate chess games. Users of `chess` are expected to implement the\n`chess.Player` interface. These implementations are the primary thing we will\nvalidate. Our acceptance test concerns itself with whether the player\nimplementation makes legal moves, not whether the moves are smart.\n\n1.  Create a new package for the validation behavior,\n    [customarily named](#naming-doubles-helper-package) by appending the word\n    `test` to the package name (for example, `chesstest`).\n\n1.  Create the function that performs the validation by accepting the\n    implementation under test as an argument and exercises it:\n\n    ```go\n    // ExercisePlayer tests a Player implementation in a single turn on a board.\n    // The board itself is spot checked for sensibility and correctness.\n    //\n    // It returns a nil error if the player makes a correct move in the context\n    // of the provided board. Otherwise ExercisePlayer returns one of this\n    // package's errors to indicate how and why the player failed the\n    // validation.\n    func ExercisePlayer(b *chess.Board, p chess.Player) error\n    ```\n\n    The test should note which invariants are broken and how. Your design can\n    choose between two disciplines for failure reporting:\n\n    *   **Fail fast**: return an error as soon as the implementation violates an\n        invariant.\n\n        This is the simplest approach, and it works well if the acceptance test\n        is expected to execute quickly. Simple error [sentinels] and\n        [custom types] can be used easily here, which conversely makes testing\n        the acceptance test easy.\n\n        ```go\n        for color, army := range b.Armies {\n            // The king should never leave the board, because the game ends at\n            // checkmate.\n            if army.King == nil {\n                return &MissingPieceError{Color: color, Piece: chess.King}\n            }\n        }\n        ```\n\n    *   **Aggregate all failures**: collect all failures, and report them all.\n\n        This approach resembles the [keep going](decisions#keep-going) guidance\n        in feel and may be preferable if the acceptance test is expected to\n        execute slowly.\n\n        How you aggregate the failures should be dictated by whether you want to\n        give users the ability or yourself the ability to interrogate individual\n        failures (for example, for you to test your acceptance test). Below\n        demonstrates using a [custom error type][custom types] that\n        [aggregates errors]:\n\n        ```go\n        var badMoves []error\n\n        move := p.Move()\n        if putsOwnKingIntoCheck(b, move) {\n            badMoves = append(badMoves, PutsSelfIntoCheckError{Move: move})\n        }\n\n        if len(badMoves) > 0 {\n            return SimulationError{BadMoves: badMoves}\n        }\n        return nil\n        ```\n\nThe acceptance test should honor the [keep going](decisions#keep-going) guidance\nby not calling `t.Fatal` unless the test detects a broken invariant in the\nsystem being exercised.\n\nFor example, `t.Fatal` should be reserved for exceptional cases such as\n[setup failure](#test-helper-error-handling) as usual:\n\n```go\nfunc ExerciseGame(t *testing.T, cfg *Config, p chess.Player) error {\n    t.Helper()\n\n    if cfg.Simulation == Modem {\n        conn, err := modempool.Allocate()\n        if err != nil {\n            t.Fatalf(\"No modem for the opponent could be provisioned: %v\", err)\n        }\n        t.Cleanup(func() { modempool.Return(conn) })\n    }\n    // Run acceptance test (a whole game).\n}\n```\n\nThis technique can help you create concise, canonical validations. But do not\nattempt to use it to bypass the [guidance on assertions](decisions#assert).\n\nThe final product should be in a form similar to this for end users:\n\n```go\n// Good:\npackage deepblue_test\n\nimport (\n    \"chesstest\"\n    \"deepblue\"\n)\n\nfunc TestAcceptance(t *testing.T) {\n    player := deepblue.New()\n    err := chesstest.ExerciseGame(t, chesstest.SimpleGame, player)\n    if err != nil {\n        t.Errorf(\"Deep Blue player failed acceptance test: %v\", err)\n    }\n}\n```\n\n[sentinels]: https://google.github.io/styleguide/go/index.html#gotip\n[custom types]: https://google.github.io/styleguide/go/index.html#gotip\n[aggregates errors]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"use-real-transports\"></a>\n\n### Use real transports\n\nWhen testing component integrations, especially where HTTP or RPC are used as\nthe underlying transport between the components, prefer using the real\nunderlying transport to connect to the test version of the backend.\n\nFor example, suppose the code you want to test (sometimes referred to as \"system\nunder test\" or SUT) interacts with a backend that implements the\n[long running operations] API. To test your SUT, use a real [OperationsClient]\nthat is connected to a\n[test double](https://abseil.io/resources/swe-book/html/ch13.html#basic_concepts)\n(e.g., a mock, stub, or fake) of the [OperationsServer].\n\n[test double]: https://abseil.io/resources/swe-book/html/ch13.html#basic_concepts\n[long running operations]: https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning\n[OperationsClient]: https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#OperationsClient\n[OperationsServer]: https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#OperationsServer\n\nThis is recommended over hand-implementing the client, due to the complexity of\nimitating client behavior correctly. By using the production client with a\ntest-specific server, you ensure your test is using as much of the real code as\npossible.\n\n**Tip:** Where possible, use a testing library provided by the authors of the\nservice under test.\n\n<a id=\"t-fatal\"></a>\n\n### `t.Error` vs. `t.Fatal`\n\nAs discussed in [decisions](decisions#keep-going), tests should generally not\nabort at the first encountered problem.\n\nHowever, some situations require that the test not proceed. Calling `t.Fatal` is\nappropriate when some piece of test setup fails, especially in\n[test setup helpers], without which you cannot run the rest of the test. In a\ntable-driven test, `t.Fatal` is appropriate for failures that set up the whole\ntest function before the test loop. Failures that affect a single entry in the\ntest table, which make it impossible to continue with that entry, should be\nreported as follows:\n\n*   If you're not using `t.Run` subtests, use `t.Error` followed by a `continue`\n    statement to move on to the next table entry.\n*   If you're using subtests (and you're inside a call to `t.Run`), use\n    `t.Fatal`, which ends the current subtest and allows your test case to\n    progress to the next subtest.\n\n**Warning:** It is not always safe to call `t.Fatal` and similar functions.\n[More details here](#t-fatal-goroutine).\n\n[test setup helpers]: #test-helper-error-handling\n\n<a id=\"test-helper-error-handling\"></a>\n\n### Error handling in test helpers\n\n**Note:** This section discusses [test helpers] in the sense Go uses the term:\nfunctions that perform test setup and cleanup, not common assertion facilities.\nSee the [test functions](#test-functions) section for more discussion.\n\n[test helpers]: decisions#mark-test-helpers\n\nOperations performed by a test helper sometimes fail. For example, setting up a\ndirectory with files involves I/O, which can fail. When test helpers fail, their\nfailure often signifies that the test cannot continue, since a setup\nprecondition failed. When this happens, prefer calling one of the `Fatal`\nfunctions in the helper:\n\n```go\n// Good:\nfunc mustAddGameAssets(t *testing.T, dir string) {\n    t.Helper()\n    if err := os.WriteFile(path.Join(dir, \"pak0.pak\"), pak0, 0644); err != nil {\n        t.Fatalf(\"Setup failed: could not write pak0 asset: %v\", err)\n    }\n    if err := os.WriteFile(path.Join(dir, \"pak1.pak\"), pak1, 0644); err != nil {\n        t.Fatalf(\"Setup failed: could not write pak1 asset: %v\", err)\n    }\n}\n```\n\nThis keeps the calling side cleaner than if the helper were to return the error\nto the test itself:\n\n```go\n// Bad:\nfunc addGameAssets(t *testing.T, dir string) error {\n    t.Helper()\n    if err := os.WriteFile(path.Join(d, \"pak0.pak\"), pak0, 0644); err != nil {\n        return err\n    }\n    if err := os.WriteFile(path.Join(d, \"pak1.pak\"), pak1, 0644); err != nil {\n        return err\n    }\n    return nil\n}\n```\n\n**Warning:** It is not always safe to call `t.Fatal` and similar functions.\n[More details](#t-fatal-goroutine) here.\n\nThe failure message should include a description of what happened. This is\nimportant, as you may be providing a testing API to many users, especially as\nthe number of error-producing steps in the helper increases. When the test\nfails, the user should know where, and why.\n\n**Tip:** Go 1.14 introduced a [`t.Cleanup`] function that can be used to\nregister cleanup functions that run when your test completes. The function also\nworks with test helpers. See\n[GoTip #4: Cleaning Up Your Tests](https://google.github.io/styleguide/go/index.html#gotip)\nfor guidance on simplifying test helpers.\n\nThe snippet below in a fictional file called `paint_test.go` demonstrates how\n`(*testing.T).Helper` influences failure reporting in a Go test:\n\n```go\npackage paint_test\n\nimport (\n    \"fmt\"\n    \"testing\"\n)\n\nfunc paint(color string) error {\n    return fmt.Errorf(\"no %q paint today\", color)\n}\n\nfunc badSetup(t *testing.T) {\n    // This should call t.Helper, but doesn't.\n    if err := paint(\"taupe\"); err != nil {\n        t.Fatalf(\"Could not paint the house under test: %v\", err) // line 15\n    }\n}\n\nfunc goodSetup(t *testing.T) {\n    t.Helper()\n    if err := paint(\"lilac\"); err != nil {\n        t.Fatalf(\"Could not paint the house under test: %v\", err)\n    }\n}\n\nfunc TestBad(t *testing.T) {\n    badSetup(t)\n    // ...\n}\n\nfunc TestGood(t *testing.T) {\n    goodSetup(t) // line 32\n    // ...\n}\n```\n\nHere is an example of this output when run. Note the highlighted text and how it\ndiffers:\n\n```text\n=== RUN   TestBad\n    paint_test.go:15: Could not paint the house under test: no \"taupe\" paint today\n--- FAIL: TestBad (0.00s)\n=== RUN   TestGood\n    paint_test.go:32: Could not paint the house under test: no \"lilac\" paint today\n--- FAIL: TestGood (0.00s)\nFAIL\n```\n\nThe error with `paint_test.go:15` refers to the line of the setup function that\nfailed in `badSetup`:\n\n`t.Fatalf(\"Could not paint the house under test: %v\", err)`\n\nWhereas `paint_test.go:32` refers to the line of the test that failed in\n`TestGood`:\n\n`goodSetup(t)`\n\nCorrectly using `(*testing.T).Helper` attributes the location of the failure\nmuch better when:\n\n*   the helper functions grow\n*   the helper functions call other helpers\n*   the amount of helper usage in the test functions grow\n\n**Tip:** If a helper calls `(*testing.T).Error` or `(*testing.T).Fatal`, provide\nsome context in the format string to help determine what went wrong and why.\n\n**Tip:** If nothing a helper does can cause a test to fail, it doesn't need to\ncall `t.Helper`. Simplify its signature by removing `t` from the function\nparameter list.\n\n[`t.Cleanup`]: https://pkg.go.dev/testing#T.Cleanup\n\n<a id=\"t-fatal-goroutine\"></a>\n\n### Don't call `t.Fatal` from separate goroutines\n\nAs [documented in package testing](https://pkg.go.dev/testing#T), it is\nincorrect to call `t.FailNow`, `t.Fatal`, etc. from any goroutine but the one\nrunning the Test function (or the subtest). If your test starts new goroutines,\nthey must not call these functions from inside these goroutines.\n\n[Test helpers](#test-functions) usually don't signal failure from new\ngoroutines, and therefore it is all right for them to use `t.Fatal`. If in\ndoubt, call `t.Error` and return instead.\n\n```go\n// Good:\nfunc TestRevEngine(t *testing.T) {\n    engine, err := Start()\n    if err != nil {\n        t.Fatalf(\"Engine failed to start: %v\", err)\n    }\n\n    num := 11\n    var wg sync.WaitGroup\n    wg.Add(num)\n    for i := 0; i < num; i++ {\n        go func() {\n            defer wg.Done()\n            if err := engine.Vroom(); err != nil {\n                // This cannot be t.Fatalf.\n                t.Errorf(\"No vroom left on engine: %v\", err)\n                return\n            }\n            if rpm := engine.Tachometer(); rpm > 1e6 {\n                t.Errorf(\"Inconceivable engine rate: %d\", rpm)\n            }\n        }()\n    }\n    wg.Wait()\n\n    if seen := engine.NumVrooms(); seen != num {\n        t.Errorf(\"engine.NumVrooms() = %d, want %d\", seen, num)\n    }\n}\n```\n\nAdding `t.Parallel` to a test or subtest does not make it unsafe to call\n`t.Fatal`.\n\nWhen all calls to the `testing` API are in the [test function](#test-functions),\nit is usually easy to spot incorrect usage because the `go` keyword is plain to\nsee. Passing `testing.T` arguments around makes tracking such usage harder.\nTypically, the reason for passing these arguments is to introduce a test helper,\nand those should not depend on the system under test. Therefore, if a test\nhelper [registers a fatal test failure](#test-helper-error-handling), it can and\nshould do so from the test's goroutine.\n\n<a id=\"t-field-names\"></a>\n\n### Use field names in struct literals\n\n<a id=\"t-field-labels\"></a>\n\nIn table-driven tests, prefer to specify field names when initializing test case\nstruct literals. This is helpful when the test cases cover a large amount of\nvertical space (e.g. more than 20-30 lines), when there are adjacent fields with\nthe same type, and also when you wish to omit fields which have the zero value.\nFor example:\n\n```go\n// Good:\nfunc TestStrJoin(t *testing.T) {\n    tests := []struct {\n        slice     []string\n        separator string\n        skipEmpty bool\n        want      string\n    }{\n        {\n            slice:     []string{\"a\", \"b\", \"\"},\n            separator: \",\",\n            want:      \"a,b,\",\n        },\n        {\n            slice:     []string{\"a\", \"b\", \"\"},\n            separator: \",\",\n            skipEmpty: true,\n            want:      \"a,b\",\n        },\n        // ...\n    }\n    // ...\n}\n```\n\n<a id=\"t-common-setup-scope\"></a>\n\n### Keep setup code scoped to specific tests\n\nWhere possible, setup of resources and dependencies should be as closely scoped\nto specific test cases as possible. For example, given a setup function:\n\n```go\n// mustLoadDataSet loads a data set for the tests.\n//\n// This example is very simple and easy to read. Often realistic setup is more\n// complex, error-prone, and potentially slow.\nfunc mustLoadDataset(t *testing.T) []byte {\n    t.Helper()\n    data, err := os.ReadFile(\"path/to/your/project/testdata/dataset\")\n\n    if err != nil {\n        t.Fatalf(\"Could not load dataset: %v\", err)\n    }\n    return data\n}\n```\n\nCall `mustLoadDataset` explicitly in test functions that need it:\n\n```go\n// Good:\nfunc TestParseData(t *testing.T) {\n    data := mustLoadDataset(t)\n    parsed, err := ParseData(data)\n    if err != nil {\n        t.Fatalf(\"Unexpected error parsing data: %v\", err)\n    }\n    want := &DataTable{ /* ... */ }\n    if got := parsed; !cmp.Equal(got, want) {\n        t.Errorf(\"ParseData(data) = %v, want %v\", got, want)\n    }\n}\n\nfunc TestListContents(t *testing.T) {\n    data := mustLoadDataset(t)\n    contents, err := ListContents(data)\n    if err != nil {\n        t.Fatalf(\"Unexpected error listing contents: %v\", err)\n    }\n    want := []string{ /* ... */ }\n    if got := contents; !cmp.Equal(got, want) {\n        t.Errorf(\"ListContents(data) = %v, want %v\", got, want)\n    }\n}\n\nfunc TestRegression682831(t *testing.T) {\n    if got, want := guessOS(\"zpc79.example.com\"), \"grhat\"; got != want {\n        t.Errorf(`guessOS(\"zpc79.example.com\") = %q, want %q`, got, want)\n    }\n}\n```\n\nThe test function `TestRegression682831` does not use the data set and therefore\ndoes not call `mustLoadDataset`, which could be slow and failure-prone:\n\n```go\n// Bad:\nvar dataset []byte\n\nfunc TestParseData(t *testing.T) {\n    // As documented above without calling mustLoadDataset directly.\n}\n\nfunc TestListContents(t *testing.T) {\n    // As documented above without calling mustLoadDataset directly.\n}\n\nfunc TestRegression682831(t *testing.T) {\n    if got, want := guessOS(\"zpc79.example.com\"), \"grhat\"; got != want {\n        t.Errorf(`guessOS(\"zpc79.example.com\") = %q, want %q`, got, want)\n    }\n}\n\nfunc init() {\n    dataset = mustLoadDataset()\n}\n```\n\nA user may wish to run a function in isolation of the others and should not be\npenalized by these factors:\n\n```shell\n# No reason for this to perform the expensive initialization.\n$ go test -run TestRegression682831\n```\n\n<a id=\"t-custom-main\"></a>\n\n#### When to use a custom `TestMain` entrypoint\n\nIf **all tests in the package** require common setup and the **setup requires\nteardown**, you can use a [custom testmain entrypoint]. This can happen if the\nresource the test cases require is especially expensive to setup, and the cost\nshould be amortized. Typically you have extracted any unrelated tests from the\ntest suite at that point. It is typically only used for [functional tests].\n\nUsing a custom `TestMain` **should not be your first choice** due the amount of\ncare that should be taken for correct use. Consider first whether the solution\nin the [*amortizing common test setup*] section or an ordinary [test helper] is\nsufficient for your needs.\n\n[custom testmain entrypoint]: https://golang.org/pkg/testing/#hdr-Main\n[functional tests]: https://en.wikipedia.org/wiki/Functional_testing\n[*amortizing common test setup*]: #t-setup-amortization\n[test helper]: #t-common-setup-scope\n\n```go\n// Good:\nvar db *sql.DB\n\nfunc TestInsert(t *testing.T) { /* omitted */ }\n\nfunc TestSelect(t *testing.T) { /* omitted */ }\n\nfunc TestUpdate(t *testing.T) { /* omitted */ }\n\nfunc TestDelete(t *testing.T) { /* omitted */ }\n\n// runMain sets up the test dependencies and eventually executes the tests.\n// It is defined as a separate function to enable the setup stages to clearly\n// defer their teardown steps.\nfunc runMain(ctx context.Context, m *testing.M) (code int, err error) {\n    ctx, cancel := context.WithCancel(ctx)\n    defer cancel()\n\n    d, err := setupDatabase(ctx)\n    if err != nil {\n        return 0, err\n    }\n    defer d.Close() // Expressly clean up database.\n    db = d          // db is defined as a package-level variable.\n\n    // m.Run() executes the regular, user-defined test functions.\n    // Any defer statements that have been made will be run after m.Run()\n    // completes.\n    return m.Run(), nil\n}\n\nfunc TestMain(m *testing.M) {\n    code, err := runMain(context.Background(), m)\n    if err != nil {\n        // Failure messages should be written to STDERR, which log.Fatal uses.\n        log.Fatal(err)\n    }\n    // NOTE: defer statements do not run past here due to os.Exit\n    //       terminating the process.\n    os.Exit(code)\n}\n```\n\nIdeally a test case is hermetic between invocations of itself and between other\ntest cases.\n\nAt the very least, ensure that individual test cases reset any global state they\nhave modified if they have done so (for instance, if the tests are working with\nan external database).\n\n<a id=\"t-setup-amortization\"></a>\n\n#### Amortizing common test setup\n\nUsing a `sync.Once` may be appropriate, though not required, if all of the\nfollowing are true about the common setup:\n\n*   It is expensive.\n*   It only applies to some tests.\n*   It does not require teardown.\n\n```go\n// Good:\nvar dataset struct {\n    once sync.Once\n    data []byte\n    err  error\n}\n\nfunc mustLoadDataset(t *testing.T) []byte {\n    t.Helper()\n    dataset.once.Do(func() {\n        data, err := os.ReadFile(\"path/to/your/project/testdata/dataset\")\n        // dataset is defined as a package-level variable.\n        dataset.data = data\n        dataset.err = err\n    })\n    if err := dataset.err; err != nil {\n        t.Fatalf(\"Could not load dataset: %v\", err)\n    }\n    return dataset.data\n}\n```\n\nWhen `mustLoadDataset` is used in multiple test functions, its cost is\namortized:\n\n```go\n// Good:\nfunc TestParseData(t *testing.T) {\n    data := mustLoadDataset(t)\n\n    // As documented above.\n}\n\nfunc TestListContents(t *testing.T) {\n    data := mustLoadDataset(t)\n\n    // As documented above.\n}\n\nfunc TestRegression682831(t *testing.T) {\n    if got, want := guessOS(\"zpc79.example.com\"), \"grhat\"; got != want {\n        t.Errorf(`guessOS(\"zpc79.example.com\") = %q, want %q`, got, want)\n    }\n}\n```\n\nThe reason that common teardown is tricky is there is no uniform place to\nregister cleanup routines. If the setup function (in this case\n`mustLoadDataset`) relies on a context, `sync.Once` may be problematic. This is\nbecause the second of two racing calls to the setup function would need to wait\nfor the first call to finish before returning. This period of waiting cannot be\neasily made to respect the context's cancellation.\n\n<a id=\"string-concat\"></a>\n\n## String concatenation\n\nThere are several ways to concatenate strings in Go. Some examples include:\n\n*   The \"+\" operator\n*   `fmt.Sprintf`\n*   `strings.Builder`\n*   `text/template`\n*   `safehtml/template`\n\nThough there is no one-size-fits-all rule for which to choose, the following\nguidance outlines when each method is preferred.\n\n<a id=\"string-concat-simple\"></a>\n\n### Prefer \"+\" for simple cases\n\nPrefer using \"+\" when concatenating few strings. This method is syntactically\nthe simplest and requires no import.\n\n```go\n// Good:\nkey := \"projectid: \" + p\n```\n\n<a id=\"string-concat-fmt\"></a>\n\n### Prefer `fmt.Sprintf` when formatting\n\nPrefer using `fmt.Sprintf` when building a complex string with formatting. Using\nmany \"+\" operators may obscure the end result.\n\n```go\n// Good:\nstr := fmt.Sprintf(\"%s [%s:%d]-> %s\", src, qos, mtu, dst)\n```\n\n```go\n// Bad:\nbad := src.String() + \" [\" + qos.String() + \":\" + strconv.Itoa(mtu) + \"]-> \" + dst.String()\n```\n\n**Best Practice:** When the output of the string-building operation is an\n`io.Writer`, don't construct a temporary string with `fmt.Sprintf` just to send\nit to the Writer. Instead, use `fmt.Fprintf` to emit to the Writer directly.\n\nWhen the formatting is even more complex, prefer [`text/template`] or\n[`safehtml/template`] as appropriate.\n\n[`text/template`]: https://pkg.go.dev/text/template\n[`safehtml/template`]: https://pkg.go.dev/github.com/google/safehtml/template\n\n<a id=\"string-concat-piecemeal\"></a>\n\n### Prefer `strings.Builder` for constructing a string piecemeal\n\nPrefer using `strings.Builder` when building a string bit-by-bit.\n`strings.Builder` takes amortized linear time, whereas \"+\" and `fmt.Sprintf`\ntake quadratic time when called sequentially to form a larger string.\n\n```go\n// Good:\nb := new(strings.Builder)\nfor i, d := range digitsOfPi {\n    fmt.Fprintf(b, \"the %d digit of pi is: %d\\n\", i, d)\n}\nstr := b.String()\n```\n\n**Note:** For more discussion, see\n[GoTip #29: Building Strings Efficiently](https://google.github.io/styleguide/go/index.html#gotip).\n\n<a id=\"string-constants\"></a>\n\n### Constant strings\n\nPrefer to use backticks (\\`) when constructing constant, multi-line string\nliterals.\n\n```go\n// Good:\nusage := `Usage:\n\ncustom_tool [args]`\n```\n\n```go\n// Bad:\nusage := \"\" +\n  \"Usage:\\n\" +\n  \"\\n\" +\n  \"custom_tool [args]\"\n```\n\n<!--\n\n-->\n\n{% endraw %}\n\n<a id=\"globals\"></a>\n\n## Global state\n\nLibraries should not force their clients to use APIs that rely on\n[global state](https://en.wikipedia.org/wiki/Global_variable). They are advised\nnot to expose APIs or export\n[package level](https://go.dev/ref/spec#TopLevelDecl) variables that control\nbehavior for all clients as parts of their API. The rest of the section uses\n\"global\" and \"package level state\" synonymously.\n\nInstead, if your functionality maintains state, allow your clients to create and\nuse instance values.\n\n**Important:** While this guidance is applicable to all developers, it is most\ncritical for infrastructure providers who offer libraries, integrations, and\nservices to other teams.\n\n```go\n// Good:\n// Package sidecar manages subprocesses that provide features for applications.\npackage sidecar\n\ntype Registry struct { plugins map[string]*Plugin }\n\nfunc New() *Registry { return &Registry{plugins: make(map[string]*Plugin)} }\n\nfunc (r *Registry) Register(name string, p *Plugin) error { ... }\n```\n\nYour users will instantiate the data they need (a `*sidecar.Registry`) and then\npass it as an explicit dependency:\n\n```go\n// Good:\npackage main\n\nfunc main() {\n  sidecars := sidecar.New()\n  if err := sidecars.Register(\"Cloud Logger\", cloudlogger.New()); err != nil {\n    log.Exitf(\"Could not setup cloud logger: %v\", err)\n  }\n  cfg := &myapp.Config{Sidecars: sidecars}\n  myapp.Run(context.Background(), cfg)\n}\n```\n\nThere are different approaches to migrating existing code to support dependency\npassing. The main one you will use is passing dependencies as parameters to\nconstructors, functions, methods, or struct fields on the call chain.\n\nSee also:\n\n*   [Go Tip #5: Slimming Your Client Libraries](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #24: Use Case-Specific Constructions](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #40: Improving Time Testability with Function Parameters](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #41: Identify Function Call Parameters](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #44: Improving Time Testability with Struct Fields](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #80: Dependency Injection Principles](https://google.github.io/styleguide/go/index.html#gotip)\n\nAPIs that do not support explicit dependency passing become fragile as the\nnumber of clients increases:\n\n```go\n// Bad:\npackage sidecar\n\nvar registry = make(map[string]*Plugin)\n\nfunc Register(name string, p *Plugin) error { /* registers plugin in registry */ }\n```\n\nConsider what happens in the case of tests exercising code that transitively\nrelies on a sidecar for cloud logging.\n\n```go\n// Bad:\npackage app\n\nimport (\n  \"cloudlogger\"\n  \"sidecar\"\n  \"testing\"\n)\n\nfunc TestEndToEnd(t *testing.T) {\n  // The system under test (SUT) relies on a sidecar for a production cloud\n  // logger already being registered.\n  ... // Exercise SUT and check invariants.\n}\n\nfunc TestRegression_NetworkUnavailability(t *testing.T) {\n  // We had an outage because of a network partition that rendered the cloud\n  // logger inoperative, so we added a regression test to exercise the SUT with\n  // a test double that simulates network unavailability with the logger.\n  sidecar.Register(\"cloudlogger\", cloudloggertest.UnavailableLogger)\n  ... // Exercise SUT and check invariants.\n}\n\nfunc TestRegression_InvalidUser(t *testing.T) {\n  // The system under test (SUT) relies on a sidecar for a production cloud\n  // logger already being registered.\n  //\n  // Oops. cloudloggertest.UnavailableLogger is still registered from the\n  // previous test.\n  ... // Exercise SUT and check invariants.\n}\n```\n\nGo tests are executed sequentially by default, so the tests above run as:\n\n1.  `TestEndToEnd`\n2.  `TestRegression_NetworkUnavailability`, which overrides the default value of\n    cloudlogger\n3.  `TestRegression_InvalidUser`, which requires the default value of\n    cloudlogger registered in `package sidecar`\n\nThis creates an order-dependent test case, which breaks running with test\nfilters, and prevents tests from running in parallel or being sharded.\n\nUsing global state poses problems that lack easy answers for you and the API's\nclients:\n\n*   What happens if a client needs to use different and separately operating\n    sets of `Plugin`s (for example, to support multiple servers) in the same\n    process space?\n\n*   What happens if a client wants to replace a registered `Plugin` with an\n    alternative implementation in a test, like a [test double]?\n\n    What happens if a client's tests require hermeticity between instances of a\n    `Plugin`, or between all of the plugins registered?\n\n*   What happens if multiple clients `Register` a `Plugin` under the same name?\n    Which one wins, if any?\n\n    How should errors be [handled](decisions#handle-errors)? If the code panics\n    or calls `log.Fatal`, will that always be\n    [appropriate for all places in which API would be called](decisions#dont-panic)?\n    Can a client verify it doesn't do something bad before doing so?\n\n*   Are there certain stages in a program's startup phases or lifetime during\n    which `Register` can be called and when it can't?\n\n    What happens if `Register` is called at the wrong time? A client could call\n    `Register` in [`func init`](https://go.dev/ref/spec#Package_initialization),\n    before flags are parsed, or after `main`. The stage at which a function is\n    called affects error handling. If the author of an API assumes the API is\n    *only* called during program initialization without the requirement that it\n    is, the assumption may nudge the author to design error handling to\n    [abort the program](best-practices#program-init) by modeling the API as a\n    `Must`-like function. Aborting is not appropriate for general-purpose\n    library functions that can be used at any stage.\n\n*   What if the client's and the designer's concurrency needs are mismatched?\n\nSee also:\n\n*   [Go Tip #36: Enclosing Package-Level State](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #71: Reducing Parallel Test Flakiness](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #80: Dependency Injection Principles](https://google.github.io/styleguide/go/index.html#gotip)\n*   Error Handling:\n    [Look Before You Leap](https://docs.python.org/3/glossary.html#term-LBYL)\n    versus\n    [Easier to Ask for Forgiveness than Permission](https://docs.python.org/3/glossary.html#term-EAFP)\n*   [Unit Testing Practices on Public APIs]\n\nGlobal state has cascading effects on the\n[health of the Google codebase](guide.md#maintainability). Global state should\nbe approached with **extreme scrutiny**.\n\n[Global state comes in several forms](#globals-forms), and you can use a few\n[litmus tests to identify when it is safe](#globals-litmus-tests).\n\n[Unit Testing Practices on Public APIs]: index.md#unit-testing-practices\n\n<a id=\"globals-forms\"></a>\n\n### Major forms of package state APIs\n\nSeveral of the most common problematic API forms are enumerated below:\n\n*   Top-level variables irrespective of whether they are exported.\n\n    ```go\n    // Bad:\n    package logger\n\n    // Sinks manages the default output sources for this package's logging API.  This\n    // variable should be set at package initialization time and never thereafter.\n    var Sinks []Sink\n    ```\n\n    See the [litmus tests](#globals-litmus-tests) to know when these are safe.\n\n*   The\n    [service locator pattern](https://en.wikipedia.org/wiki/Service_locator_pattern).\n    See the [first example](#globals). The service locator pattern itself is not\n    problematic, rather the locator being defined as global.\n\n*   Registries for\n    [callbacks](https://en.wikipedia.org/wiki/Callback_\\(computer_programming\\))\n    and similar behaviors.\n\n    ```go\n    // Bad:\n    package health\n\n    var unhealthyFuncs []func\n\n    func OnUnhealthy(f func()) {\n      unhealthyFuncs = append(unhealthyFuncs, f)\n    }\n    ```\n\n*   Thick-Client singletons for things like backends, storage, data access\n    layers, and other system resources. These often pose additional problems\n    with service reliability.\n\n    ```go\n    // Bad:\n    package useradmin\n\n    var client pb.UserAdminServiceClientInterface\n\n    func Client() *pb.UserAdminServiceClient {\n        if client == nil {\n            client = ...  // Set up client.\n        }\n        return client\n    }\n    ```\n\n> **Note:** Many legacy APIs in the Google codebase do not follow this guidance;\n> in fact, some Go standard libraries allow for configuration via global values.\n> Nevertheless, the legacy API's contravention of this guidance\n> **[should not be used as precedent](guide#local-consistency)** for continuing\n> the pattern.\n>\n> It is better to invest in proper API design today than pay for redesigning\n> later.\n\n<a id=\"globals-litmus-tests\"></a>\n\n### Litmus tests\n\n[APIs using the patterns above](#globals-forms) are unsafe when:\n\n*   Multiple functions interact via global state when executed in the same\n    program, despite being otherwise independent (for example, authored by\n    different authors in vastly different directories).\n*   Independent test cases interact with each other through global state.\n*   Users of the API are tempted to swap or replace global state for testing\n    purposes, particularly to replace any part of the state with a\n    [test double], like a stub, fake, spy, or mock.\n*   Users have to consider special ordering requirements when interacting with\n    global state: `func init`, whether flags are parsed yet, etc.\n\nProvided the conditions above are avoided, there are a **few limited\ncircumstances under which these APIs are safe**, namely when any of the\nfollowing is true:\n\n*   The global state is logically constant\n    ([example](https://github.com/klauspost/compress/blob/290f4cfacb3eff892555a491e3eeb569a48665e7/zstd/snappy.go#L413)).\n*   The package's observable behavior is stateless. For example, a public\n    function may use a private global variable as a cache, but so long as the\n    caller can't distinguish cache hits from misses, the function is stateless.\n*   The global state does not bleed into things that are external to the\n    program, like sidecar processes or files on a shared filesystem.\n*   There is no expectation of predictable behavior\n    ([example](https://pkg.go.dev/math/rand)).\n\n> **Note:**\n> [Sidecar processes](https://www.oreilly.com/library/view/designing-distributed-systems/9781491983638/ch02.html)\n> may **not** strictly be process-local. They can and often are shared with more\n> than one application process. Moreover, these sidecars often interact with\n> external distributed systems.\n>\n> Further, the same stateless, idempotent, and local rules in addition to the\n> base considerations above would apply to the code of the sidecar process\n> itself!\n\nAn example of one of these safe situations is\n[`package image`](https://pkg.go.dev/image) with its\n[`image.RegisterFormat`](https://pkg.go.dev/image#RegisterFormat) function.\nConsider the litmus tests from above applied to a typical decoder, like the one\nfor handling the [PNG](https://pkg.go.dev/image/png) format:\n\n*   Multiple calls to `package image`'s APIs that use the registered decoders\n    (for example, `image.Decode`) cannot interfere with one another, similarly\n    for tests. The only exception is `image.RegisterFormat`, but that is\n    mitigated by the points below.\n*   It is extremely unlikely that a user would want to replace a decoder with a\n    [test double], as the PNG decoder exemplifies a case in which our codebase's\n    preference for real objects applies. However, a user would be more likely to\n    replace a decoder with a test double if the decoder statefully interacted\n    with operating system resources (for example, the network).\n*   Collisions in registration are conceivable, though they are probably rare in\n    practice.\n*   The decoders are stateless, idempotent, and pure.\n\n<a id=\"globals-default-instance\"></a>\n\n### Providing a default instance\n\nWhile not recommended, it is acceptable to provide a simplified API that uses\npackage level state if you need to maximize convenience for the user.\n\nFollow the [litmus tests](#globals-litmus-tests) with these guidelines in such\ncases:\n\n1.  The package must offer clients the ability to create isolated instances of\n    package types as [described above](#globals-forms).\n2.  The public APIs that use global state must be a thin proxy to the previous\n    API. A good example of this is\n    [`http.Handle`](https://pkg.go.dev/net/http#Handle) internally calling\n    [`(*http.ServeMux).Handle`](https://pkg.go.dev/net/http#ServeMux.Handle) on\n    the package variable\n    [`http.DefaultServeMux`](https://pkg.go.dev/net/http#DefaultServeMux).\n3.  This package-level API must only be used by [binary build targets], not\n    [libraries], unless the libraries are undertaking a refactoring to support\n    dependency passing. Infrastructure libraries that can be imported by other\n    packages must not rely on package-level state of the packages they import.\n\n    For example, an infrastructure provider implementing a sidecar that is to be\n    shared with other teams using the API from the top should offer an API to\n    accommodate this:\n\n    ```go\n    // Good:\n    package cloudlogger\n\n    func New() *Logger { ... }\n\n    func Register(r *sidecar.Registry, l *Logger) {\n      r.Register(\"Cloud Logging\", l)\n    }\n    ```\n\n4.  This package-level API must [document](#documentation-conventions) and\n    enforce its invariants (for example, at which stage in the program's life it\n    can be called, whether it can be used concurrently). Further, it must\n    provide an API to reset global state to a known-good default (for example,\n    to facilitate testing).\n\n[binary build targets]: https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/rules.md#go_binary\n[libraries]: https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/rules.md#go_library\n\nSee also:\n\n*   [Go Tip #36: Enclosing Package-Level State](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #80: Dependency Injection Principles](https://google.github.io/styleguide/go/index.html#gotip)\n\n<a id=\"interfaces\"></a>\n\n## Interfaces\n\nInterfaces in Go are powerful but can be overused or misunderstood. Because Go\ninterfaces are satisfied implicitly, they are a structural tool rather than a\ndeclarative one. The following guidance provides the best practices for how to\ndesign and return interfaces in Go without over-engineering your codebase.\n\nRefer to [Decisions' section on interfaces](decisions#interfaces) for a summary.\n\n<a id=\"avoid-unnecessary-interfaces\"></a>\n\n### Avoid unnecessary interfaces\n\nThe most common mistake is creating an interface before a\n[real need](guide#simplicity) exists.\n\n1.  **Don’t confuse the concept with the keyword:** Just because you are\n    designing a \"service\" or a \"repository\" or similar pattern doesn't mean you\n    need a named interface type (e.g., `type Service interface`). Focus on the\n    behavior and its concrete implementation first.\n\n2.  **Reuse existing interfaces:** If an interface already exists, especially in\n    generated code, like a RPC client or server, use it ([testing RPC]). Do not\n    wrap a generated RPC code in a new, manual interface just for the sake of\n    abstraction or testing. [Use real transports](#use-real-transports) instead.\n\n3.  **Don't define back doors only for tests:** Do not export a [test double]\n    implementation of an interface from an API that consumes it. Instead, prefer\n    to design the API so that it can be tested using the [public API] of the\n    real implementation.\n\n    Every exported type increases the cognitive load for the reader. When you\n    export a test double alongside the real implementation, you force the reader\n    to understand three entities (the interface, the real implementation, and\n    the test double) instead of one.\n\n    Export an interface for a test double when you have a\n    [material need](guide#least-mechanism) to support substitution.\n\nWhen it does make sense to create an interface:\n\n1.  **Multiple implementations:** When there are two or more concrete types that\n    must be handled by the same logic (e.g., something that operates with both\n    [json.Encoder](https://pkg.go.dev/encoding/json#Encoder) and\n    [gob.GobEncoder](https://pkg.go.dev/encoding/gob#GobEncoder)), the API\n    consumer could define an interface.\n\n2.  **Decoupling packages:** To break circular dependencies between two packages\n    (see an [example](#avoiding-circular-dependencies)), an API producer could\n    define an interface.\n\n    **Caution:** Carefully observe guidance on [Package Size](#package-size).\n    Introducing interfaces to break dependency cycles is often a signal of\n    improperly structured packages.\n\n3.  **Hiding complexity:** When a concrete type has a massive API surface, but a\n    specific function only needs one or two methods, an API consumer may define\n    an interface.\n\n<a id=\"interface-ownership-and-visibility\"></a>\n\n### Interface ownership and visibility\n\n1.  **Do not export interface types unnecessarily:** If an interface is only\n    used internally within a package to satisfy a specific logic flow, keep the\n    interface unexported. Exporting an interface commits you to maintaining that\n    API for external callers.\n\n2.  **The consumer defines the interface:** In Go, interfaces generally belong\n    in the package that uses them, not the package that implements them. The\n    consumer should define only the methods they actually use\n    [GoTip #78: Minimal Viable Interfaces], adhering to the idea that\n    [the bigger the interface, the weaker the abstraction](https://go-proverbs.github.io/).\n\n    There are common scenarios where it often makes sense for the producer (the\n    package providing the logic) to export the interface:\n\n    *   **The interface is the product:** When a package’s primary purpose is to\n        provide a common protocol that many different implementations must\n        follow, the producer defines the interface. For example,\n        [io.Writer](https://pkg.go.dev/io#Writer),\n        [hash.Hash](https://pkg.go.dev/hash#Hash). The concept of \"protocol\"\n        includes aspects like [documentation](#documentation) about critical\n        behaviors (e.g., expected use case, edge cases, concurrency) that need\n        to be centrally and canonically explicated. Another prominent example of\n        this is generated interfaces from protobuf. It doesn't abstract a\n        specific behavior, it defines a boundary. Its purpose is to ensure that\n        your server implementation exactly matches the schema defined in the\n        `.proto` file. Here, the interface serves as a rigid legal contract\n        between the service and its clients.\n\n        For large systems, if the interface lives inside a huge implementation\n        package, every client is forced to import the entire world just to\n        reference the interface. You may define the interface in a standalone,\n        implementation-free package, avoiding unnecessary symbols and potential\n        circular dependencies. This is also the same philosophy used by\n        generated code from protobuf.\n\n    *   **Prevent interface bloat:** In large codebases, maintenance becomes\n        difficult if numerous packages utilize the same `AuthService` while each\n        defining an identical `type Authorizer interface`. While Go often favors\n        [a little copying over a little dependency](https://go-proverbs.github.io/),\n        keep in mind that maintaining perfectly mirrored interfaces (see point\n        above) across many packages can create an unnecessary burden.\n\n    *   **Resolve circular dependency:** see\n        [an example](#avoiding-circular-dependencies) below.\n\n<a id=\"designing-effective-interfaces\"></a>\n\n### Designing effective interfaces\n\n1.  **Keep interfaces small:** The larger the interface,\n    [the harder it is to implement and to write code that takes advantage of it](https://go-proverbs.github.io/).\n    Small interfaces are easier to compose into larger ones if needed.\n\n2.  **Documentation:** Treat every interface as the \"user manual\" for your\n    abstraction. The depth of your documentation should be proportional to the\n    interface's cognitive load, not just the count of its methods. Whether an\n    interface has ten methods or a single `Write` of\n    [io.Writer](https://pkg.go.dev/io#Writer), if a programmer is expected to\n    interact with that type, the API must be documented thoroughly.\n\n    *   **Single-method interfaces:** documentation on the type itself is\n        usually sufficient (e.g., io.Writer). Explain its contract, edge cases,\n        and expected errors.\n    *   **Multi-method interfaces:** each individual method requires its own\n        documentation.\n    *   **Unexported interfaces:** consider documenting them anyway. They are\n        often the glue that holds complex internal logic together, and because\n        they are invisible to external users, they can easily become mystery\n        code for future maintainers (including your future self).\n\n3.  **Accept interfaces, return concrete types:** Returning a concrete type\n    allows the caller to use the full functionality of the value without being\n    locked into a specific interface abstraction\n    [GoTip #49: Accept Interfaces, Return Concrete Types].\n\nThere are several common scenarios where returning an interface is the idiomatic\nchoice:\n\n1.  **Encapsulation:** While interfaces cannot strictly hide exported methods\n    (as they remain accessible via type assertions), returning an interface is a\n    powerful tool for limiting the default API surface and guiding the caller's\n    behavior.. The most common example is the `error` interface; you\n    [almost never return a concrete error type](decisions#errors) like\n    `*MyCustomError`.\n\n    Consider a `ThrottledReader` that implements `io.Reader` but also has a\n    `Refill` method for internal bucket management. Returning the concrete\n    `*ThrottledReader` invites the caller to manage the bucket manually, which\n    could lead to race conditions or broken rate-limiting logic. By returning an\n    interface, you tell the caller that your only job is to consume this reader.\n    If you try to cast this back to a `ThrottledReader` to `Refill` the internal\n    bucket, you are breaking the contract.\n\n    ```go\n    // Good:\n    type ThrottledReader struct {\n        source     io.Reader\n        limit      int  // bytes per second\n        balance    int  // current allowance of bytes\n        lastRefill time.Time\n    }\n\n    // Read implements the io.Reader interface with rate-limiting logic.\n    func (t *ThrottledReader) Read(p []byte) (int, error) { ... }\n\n    // Refill manually adds tokens to the bucket.\n    // INTERNAL USE ONLY: Calling this from outside breaks the rate limit logic.\n    func (t *ThrottledReader) Refill(amount int) {\n        t.balance = min(t.balance + amount, t.limit)\n    }\n\n    // New returns the io.Reader with rate-limiting.\n    func New(r io.Reader, bytesPerSec int) io.Reader {\n        return &ThrottledReader{\n            source:     r,\n            limit:      bytesPerSec,\n            balance:    bytesPerSec, // start with a full bucket\n            lastRefill: time.Now(),\n        }\n    }\n    ```\n\n    This raises a natural question: if `Refill` is dangerous, why export it at\n    all? In complex systems, you often need internal orchestration. For example,\n    an `AggregateReader` manages multiple `ThrottledReader` values to ensure\n    total bandwidth across all streams stays under a global limit. This\n    coordinator needs to call Refill to distribute tokens, but the non-power\n    user processing the data should never see that capability.\n\n    **Caution:** Before returning an interface to hide implementation, ask:\n    \"Would a user calling these extra methods actually break the system's\n    integrity or meaningfully limit maintainability?\" If the extra details allow\n    the user to bypass safety checks, or if exposing the concrete type makes it\n    impossible to change the underlying provider later without a breaking\n    change, you may return an interface. Do not rotely encapsulate without\n    reason.\n\n2.  **Certain patterns:** If a function is designed to return one of several\n    different concrete types based on decisions made at runtime, it must return\n    an interface. This is commonly true with command, chaining, factory, and\n    [strategy](https://en.wikipedia.org/wiki/Strategy_pattern) patterns.\n    Consider this code that selects which encoder to use based the requested\n    format:\n\n    ```go\n    // Good:\n    func NewWriter(format string) io.Writer {\n        switch format {\n        case \"json\":\n            return &jsonWriter{}\n        case \"xml\":\n            return &xmlWriter{}\n        default:\n            return &textWriter{}\n        }\n    }\n    ```\n\n    The following example of a chaining API demonstrates how returning an\n    interface enables polymorphic behavior. By allowing callers to use either\n    `client.Do(req)` or `client.WithAuth(\"token\").Do(req)`, you can swap\n    implementations without breaking the calling code.\n\n    ```go\n    // Good:\n    type Client interface {\n        WithAuth(token string) Client\n        Do(req *Request) error\n    }\n    ```\n\n    These patterns are guidelines, not rules. Avoid forcing an interface if a\n    single, robust concrete type can handle the abstraction internally. For\n    example, the standard [database/sql](https://pkg.go.dev/database/sql#DB)\n    library exports a single concrete `DB` type instead of forcing an interface\n    to handle types like `MySQLDB` and `OracleDB`.\n\n3.  <span id=\"avoiding-circular-dependencies\">**Avoiding circular\n    dependencies:**</span> If returning a concrete type would require importing\n    a package that already imports your current package, you must return an\n    interface to break the circular dependency.\n\n    For example:\n\n    ```go\n    // Bad:\n    package app\n\n    import \"myproject/plugin\"\n\n    type Config struct {\n        APIKey string\n    }\n\n    func Start() {\n        p := plugin.New()\n    }\n    ```\n\n    ```go\n    // Bad:\n    package plugin\n\n    import \"myproject/app\"  // ERROR: Import cycle!\n\n    func New() *app.Config {\n        return &app.Config{APIKey: \"secret\"}\n    }\n    ```\n\n    In this case, `plugin`'s `New` cannot return `*app.Config` because it would\n    create a circular import. To break this, we use the fact that interfaces are\n    satisfied implicitly. We move the \"contract\" to a neutral place or have the\n    producer return an interface that the consumer already understands.\n\n    If `plugin`'s `New` returns an interface instead of the concrete\n    `*app.Config` struct, it no longer needs to import package `app`.\n\n    ```go\n    package plugin\n\n    type Configurer interface {\n        APIKey() string\n    }\n\n    type localConfig struct {\n        key string\n    }\n\n    func (c localConfig) APIKey() string { return c.key }\n\n    // New returns the interface Configurer instead of the concrete app.Config\n    func New() Configurer {\n        return &localConfig{key: \"secret\"}\n    }\n    ```\n\n    ```go\n    package app\n\n    import \"myproject/plugin\"\n\n    func Start() {\n        conf := plugin.New()  // 'conf' is now a Configurer interface\n        fmt.Println(conf.APIKey())\n    }\n    ```\n\n    **Caution:** Carefully observe guidance on [Package Size](#package-size).\n    Introducing interfaces to break dependency cycles is often a signal of\n    improperly structured packages. Consolidated packages are often preferred\n    over too many too small packages that fail to stand on their own.\n\n[GoTip #78: Minimal Viable Interfaces]: https://google.github.io/styleguide/go/index.html#gotip\n[GoTip #49: Accept Interfaces, Return Concrete Types]: https://google.github.io/styleguide/go/index.html#gotip\n[testing RPC]: https://codelabs.developers.google.com/grpc/getting-started-grpc-go#3\n[test double]: https://abseil.io/resources/swe-book/html/ch13.html\n[public API]: https://abseil.io/resources/swe-book/html/ch12.html#test_via_public_apis\n"
  },
  {
    "path": "go/decisions.md",
    "content": "<!--* toc_depth: 3 *-->\n\n# Go Style Decisions\n\nhttps://google.github.io/styleguide/go/decisions\n\n[Overview](index) | [Guide](guide) | [Decisions](decisions) |\n[Best practices](best-practices)\n\n<!--\n\n-->\n\n{% raw %}\n\n**Note:** This is part of a series of documents that outline [Go Style](index)\nat Google. This document is **[normative](index#normative) but not\n[canonical](index#canonical)**, and is subordinate to the\n[core style guide](guide). See [the overview](index#about) for more information.\n\n<a id=\"about\"></a>\n\n## About\n\nThis document contains style decisions intended to unify and provide standard\nguidance, explanations, and examples for the advice given by the Go readability\nmentors.\n\nThis document is **not exhaustive** and will grow over time. In cases where\n[the core style guide](guide) contradicts the advice given here, **the style\nguide takes precedence**, and this document should be updated accordingly.\n\nSee [the Overview](https://google.github.io/styleguide/go#about) for the full\nset of Go Style documents.\n\nThe following sections have moved from style decisions to another part of the\nguide:\n\n*   **MixedCaps**: see [guide#mixed-caps](guide#mixed-caps)\n    <a id=\"mixed-caps\"></a>\n\n*   **Formatting**: see [guide#formatting](guide#formatting)\n    <a id=\"formatting\"></a>\n\n*   **Line Length**: see [guide#line-length](guide#line-length)\n    <a id=\"line-length\"></a>\n\n<a id=\"naming\"></a>\n\n## Naming\n\nSee the naming section within [the core style guide](guide#naming) for\noverarching guidance on naming. The following sections provide further\nclarification on specific areas within naming.\n\n<a id=\"underscores\"></a>\n\n### Underscores\n\nNames in Go should in general not contain underscores. There are three\nexceptions to this principle:\n\n1.  Package names that are only imported by generated code may contain\n    underscores. See [package names](#package-names) for more detail around how\n    to choose multi-word package names.\n1.  Test, Benchmark and Example function names within `*_test.go` files may\n    include underscores.\n1.  Low-level libraries that interoperate with the operating system or cgo may\n    reuse identifiers, as is done in [`syscall`]. This is expected to be very\n    rare in most codebases.\n\n**Note:** Filenames of source code are not Go identifiers and do not have to\nfollow these conventions. They may contain underscores.\n\n[`syscall`]: https://pkg.go.dev/syscall#pkg-constants\n\n<a id=\"package-names\"></a>\n\n### Package names\n\n<a id=\"TOC-PackageNames\"></a>\n\nIn Go, package names must be concise and use only lowercase letters and numbers\n(e.g., [`k8s`], [`oauth2`]). Multi-word package names should remain unbroken and\nin all lowercase (e.g., [`tabwriter`] instead of `tabWriter`, `TabWriter`, or\n`tab_writer`).\n\nAvoid selecting package names that are likely to be [shadowed] by commonly used\nlocal variable names. For example, `usercount` is a better package name than\n`count`, since `count` is a commonly used variable name.\n\nGo package names should not have underscores. If you need to import a package\nthat does have one in its name (usually from generated or third party code), it\nmust be renamed at import time to a name that is suitable for use in Go code.\n\nAn exception to this is that package names that are only imported by generated\ncode may contain underscores. Specific examples include:\n\n*   Using the `_test` suffix for unit tests that only exercise the exported API\n    of a package (package `testing` calls these\n    [\"black box tests\"](https://pkg.go.dev/testing)). For example, a package\n    `linkedlist` must define its black box unit tests in a package named\n    `linkedlist_test` (not `linked_list_test`)\n\n*   Using underscores and the `_test` suffix for packages that specify\n    functional or integration tests. For example, a linked list service\n    integration test could be named `linked_list_service_test`\n\n*   Using the `_test` suffix for\n    [package-level documentation examples](https://go.dev/blog/examples)\n\n[`tabwriter`]: https://pkg.go.dev/text/tabwriter\n[`k8s`]: https://pkg.go.dev/k8s.io/client-go/kubernetes\n[`oauth2`]: https://pkg.go.dev/golang.org/x/oauth2\n[shadowed]: best-practices#shadowing\n\nAvoid uninformative package names like `util`, `utility`, `common`, `helper`,\n`model`, `testhelper`, and so on that would tempt users of the package to\n[rename it when importing](#import-renaming). See:\n\n*   [Guidance on so-called \"utility packages\"](best-practices#util-packages)\n*   [Go Tip #97: What's in a Name](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #108: The Power of a Good Package Name](https://google.github.io/styleguide/go/index.html#gotip)\n\nWhen an imported package is renamed (e.g. `import foopb\n\"path/to/foo_go_proto\"`), the local name for the package must comply with the\nrules above, as the local name dictates how the symbols in the package are\nreferenced in the file. If a given import is renamed in multiple files,\nparticularly in the same or nearby packages, the same local name should be used\nwherever possible for consistency.\n\n<!--#include file=\"/go/g3doc/style/includes/special-name-exception.md\"-->\n\nSee also: [Go blog post about package names](https://go.dev/blog/package-names).\n\n<a id=\"receiver-names\"></a>\n\n### Receiver names\n\n<a id=\"TOC-ReceiverNames\"></a>\n\n[Receiver] variable names must be:\n\n*   Short (usually one or two letters in length)\n*   Abbreviations for the type itself\n*   Applied consistently to every receiver for that type\n*   Not an underscore; omit the name if it is unused\n\nLong Name                   | Better Name\n--------------------------- | -------------------------\n`func (tray Tray)`          | `func (t Tray)`\n`func (info *ResearchInfo)` | `func (ri *ResearchInfo)`\n`func (this *ReportWriter)` | `func (w *ReportWriter)`\n`func (self *Scanner)`      | `func (s *Scanner)`\n\n[Receiver]: https://golang.org/ref/spec#Method_declarations\n\n<a id=\"constant-names\"></a>\n\n### Constant names\n\nConstant names must use [MixedCaps] like all other names in Go. ([Exported]\nconstants start with uppercase, while unexported constants start with\nlowercase.) This applies even when it breaks conventions in other languages.\nConstant names should not be a derivative of their values and should instead\nexplain what the value denotes.\n\n```go\n// Good:\nconst MaxPacketSize = 512\n\nconst (\n    ExecuteBit = 1 << iota\n    WriteBit\n    ReadBit\n)\n```\n\n[MixedCaps]: guide#mixed-caps\n[Exported]: https://tour.golang.org/basics/3\n\nDo not use non-MixedCaps constant names or constants with a `K` prefix.\n\n```go\n// Bad:\nconst MAX_PACKET_SIZE = 512\nconst kMaxBufferSize = 1024\nconst KMaxUsersPergroup = 500\n```\n\nName constants based on their role, not their values. If a constant does not\nhave a role apart from its value, then it is unnecessary to define it as a\nconstant.\n\n```go\n// Bad:\nconst Twelve = 12\n\nconst (\n    UserNameColumn = \"username\"\n    GroupColumn    = \"group\"\n)\n```\n\n<!--#include file=\"/go/g3doc/style/includes/special-name-exception.md\"-->\n\n<a id=\"initialisms\"></a>\n\n### Initialisms\n\n<a id=\"TOC-Initialisms\"></a>\n\nWords in names that are initialisms or acronyms (e.g., `URL` and `NATO`) should\nhave the same case. `URL` should appear as `URL` or `url` (as in `urlPony`, or\n`URLPony`), never as `Url`. As a general rule, identifiers (e.g., `ID` and `DB`)\nshould also be capitalized similar to their usage in English prose.\n\n*   In names with multiple initialisms (e.g. `XMLAPI` because it contains `XML`\n    and `API`), each letter within a given initialism should have the same case,\n    but each initialism in the name does not need to have the same case.\n*   In names with an initialism containing a lowercase letter (e.g. `DDoS`,\n    `iOS`, `gRPC`), the initialism should appear as it would in standard prose,\n    unless you need to change the first letter for the sake of [exportedness].\n    In these cases, the entire initialism should be the same case (e.g. `ddos`,\n    `IOS`, `GRPC`).\n\n[exportedness]: https://golang.org/ref/spec#Exported_identifiers\n\n<!-- Keep this table narrow. If it must grow wider, replace with a list. -->\n\nEnglish Usage | Scope      | Correct  | Incorrect\n------------- | ---------- | -------- | --------------------------------------\nXML API       | Exported   | `XMLAPI` | `XmlApi`, `XMLApi`, `XmlAPI`, `XMLapi`\nXML API       | Unexported | `xmlAPI` | `xmlapi`, `xmlApi`\niOS           | Exported   | `IOS`    | `Ios`, `IoS`\niOS           | Unexported | `iOS`    | `ios`\ngRPC          | Exported   | `GRPC`   | `Grpc`\ngRPC          | Unexported | `gRPC`   | `grpc`\nDDoS          | Exported   | `DDoS`   | `DDOS`, `Ddos`\nDDoS          | Unexported | `ddos`   | `dDoS`, `dDOS`\nID            | Exported   | `ID`     | `Id`\nID            | Unexported | `id`     | `iD`\nDB            | Exported   | `DB`     | `Db`\nDB            | Unexported | `db`     | `dB`\nTxn           | Exported   | `Txn`    | `TXN`\n\n<!--#include file=\"/go/g3doc/style/includes/special-name-exception.md\"-->\n\n<a id=\"getters\"></a>\n\n### Getters\n\n<a id=\"TOC-Getters\"></a>\n\nFunction and method names should not use a `Get` or `get` prefix, unless the\nunderlying concept uses the word \"get\" (e.g. an HTTP GET). Prefer starting the\nname with the noun directly, for example use `Counts` over `GetCounts`.\n\nIf the function involves performing a complex computation or executing a remote\ncall, a different word like `Compute` or `Fetch` can be used in place of `Get`,\nto make it clear to a reader that the function call may take time and could\nblock or fail.\n\n<!--#include file=\"/go/g3doc/style/includes/special-name-exception.md\"-->\n\n<a id=\"variable-names\"></a>\n\n### Variable names\n\n<a id=\"TOC-VariableNames\"></a>\n\nThe general rule of thumb is that the length of a name should be proportional to\nthe size of its scope and inversely proportional to the number of times that it\nis used within that scope. A variable created at file scope may require multiple\nwords, whereas a variable scoped to a single inner block may be a single word or\neven just a character or two, to keep the code clear and avoid extraneous\ninformation.\n\nHere is a rough baseline. These numeric guidelines are not strict rules. Apply\njudgement based on context, [clarity], and [concision].\n\n*   A small scope is one in which one or two small operations are performed, say\n    1-7 lines.\n*   A medium scope is a few small or one large operation, say 8-15 lines.\n*   A large scope is one or a few large operations, say 15-25 lines.\n*   A very large scope is anything that spans more than a page (say, more than\n    25 lines).\n\n[clarity]: guide#clarity\n[concision]: guide#concision\n\nA name that might be perfectly clear (e.g., `c` for a counter) within a small\nscope could be insufficient in a larger scope and would require clarification to\nremind the reader of its purpose further along in the code. A scope in which\nthere are many variables, or variables that represent similar values or\nconcepts, may necessitate longer variable names than the scope suggests.\n\nThe specificity of the concept can also help to keep a variable's name concise.\nFor example, assuming there is only a single database in use, a short variable\nname like `db` that might normally be reserved for very small scopes may remain\nperfectly clear even if the scope is very large. In this case, a single word\n`database` is likely acceptable based on the size of the scope, but is not\nrequired as `db` is a very common shortening for the word with few alternate\ninterpretations.\n\nThe name of a local variable should reflect what it contains and how it is being\nused in the current context, rather than where the value originated. For\nexample, it is often the case that the best local variable name is not the same\nas the struct or protocol buffer field name.\n\nIn general:\n\n*   Single-word names like `count` or `options` are a good starting point.\n*   Additional words can be added to disambiguate similar names, for example\n    `userCount` and `projectCount`.\n*   Do not simply drop letters to save typing. For example `Sandbox` is\n    preferred over `Sbx`, particularly for exported names.\n*   Omit [types and type-like words] from most variable names.\n    *   For a number, `userCount` is a better name than `numUsers` or\n        `usersInt`.\n    *   For a slice, `users` is a better name than `userSlice`.\n    *   It is acceptable to include a type-like qualifier if there are two\n        versions of a value in scope, for example you might have an input stored\n        in `ageString` and use `age` for the parsed value.\n*   Omit words that are clear from the [surrounding context]. For example, in\n    the implementation of a `UserCount` method, a local variable called\n    `userCount` is probably redundant; `count`, `users`, or even `c` are just as\n    readable.\n\n[types and type-like words]: #repetitive-with-type\n[surrounding context]: #repetitive-in-context\n\n<a id=\"v\"></a>\n\n#### Single-letter variable names\n\nSingle-letter variable names can be a useful tool to minimize\n[repetition](#repetition), but can also make code needlessly opaque. Limit their\nuse to instances where the full word is obvious and where it would be repetitive\nfor it to appear in place of the single-letter variable.\n\nIn general:\n\n*   For a [method receiver variable], a one-letter or two-letter name is\n    preferred.\n*   Using familiar variable names for common types is often helpful:\n    *   `r` for an `io.Reader` or `*http.Request`\n    *   `w` for an `io.Writer` or `http.ResponseWriter`\n*   Single-letter identifiers are acceptable as integer loop variables,\n    particularly for indices (e.g., `i`) and coordinates (e.g., `x` and `y`).\n*   Abbreviations can be acceptable loop identifiers when the scope is short,\n    for example `for _, n := range nodes { ... }`.\n\n[method receiver variable]: #receiver-names\n\n<a id=\"repetition\"></a>\n\n### Repetition\n\n<!--\nNote to future editors:\n\nDo not use the term \"stutter\" to refer to cases when a name is repetitive.\n-->\n\nA piece of Go source code should avoid unnecessary repetition. One common source\nof this is repetitive names, which often include unnecessary words or repeat\ntheir context or type. Code itself can also be unnecessarily repetitive if the\nsame or a similar code segment appears multiple times in close proximity.\n\nRepetitive naming can come in many forms, including:\n\n<a id=\"repetitive-with-package\"></a>\n\n#### Package vs. exported symbol name\n\nWhen naming exported symbols, the name of the package is always visible outside\nyour package, so redundant information between the two should be reduced or\neliminated. If a package exports only one type and it is named after the package\nitself, the canonical name for the constructor is `New` if one is required.\n\n> **Examples:** Repetitive Name -> Better Name\n>\n> *   `widget.NewWidget` -> `widget.New`\n> *   `widget.NewWidgetWithName` -> `widget.NewWithName`\n> *   `db.LoadFromDatabase` -> `db.Load`\n> *   `goatteleportutil.CountGoatsTeleported` -> `gtutil.CountGoatsTeleported`\n>     or `goatteleport.Count`\n> *   `myteampb.MyTeamMethodRequest` -> `mtpb.MyTeamMethodRequest` or\n>     `myteampb.MethodRequest`\n\n<a id=\"repetitive-with-type\"></a>\n\n#### Variable name vs. type\n\nThe compiler always knows the type of a variable, and in most cases it is also\nclear to the reader what type a variable is by how it is used. It is only\nnecessary to clarify the type of a variable if its value appears twice in the\nsame scope.\n\nRepetitive Name               | Better Name\n----------------------------- | ----------------------\n`var numUsers int`            | `var users int`\n`var nameString string`       | `var name string`\n`var primaryProject *Project` | `var primary *Project`\n\nIf the value appears in multiple forms, this can be clarified either with an\nextra word like `raw` and `parsed` or with the underlying representation:\n\n```go\n// Good:\nlimitRaw := r.FormValue(\"limit\")\nlimit, err := strconv.Atoi(limitRaw)\n```\n\n```go\n// Good:\nlimitStr := r.FormValue(\"limit\")\nlimit, err := strconv.Atoi(limitStr)\n```\n\n<a id=\"repetitive-in-context\"></a>\n\n#### External context vs. local names\n\nNames that include information from their surrounding context often create extra\nnoise without benefit. The package name, method name, type name, function name,\nimport path, and even filename can all provide context that automatically\nqualifies all names within.\n\n```go\n// Bad:\n// In package \"ads/targeting/revenue/reporting\"\ntype AdsTargetingRevenueReport struct{}\n\nfunc (p *Project) ProjectName() string\n```\n\n```go\n// Good:\n// In package \"ads/targeting/revenue/reporting\"\ntype Report struct{}\n\nfunc (p *Project) Name() string\n```\n\n```go\n// Bad:\n// In package \"sqldb\"\ntype DBConnection struct{}\n```\n\n```go\n// Good:\n// In package \"sqldb\"\ntype Connection struct{}\n```\n\n```go\n// Bad:\n// In package \"ads/targeting\"\nfunc Process(in *pb.FooProto) *Report {\n    adsTargetingID := in.GetAdsTargetingID()\n}\n```\n\n```go\n// Good:\n// In package \"ads/targeting\"\nfunc Process(in *pb.FooProto) *Report {\n    id := in.GetAdsTargetingID()\n}\n```\n\nRepetition should generally be evaluated in the context of the user of the\nsymbol, rather than in isolation. For example, the following code has lots of\nnames that may be fine in some circumstances, but redundant in context:\n\n```go\n// Bad:\nfunc (db *DB) UserCount() (userCount int, err error) {\n    var userCountInt64 int64\n    if dbLoadError := db.LoadFromDatabase(\"count(distinct users)\", &userCountInt64); dbLoadError != nil {\n        return 0, fmt.Errorf(\"failed to load user count: %s\", dbLoadError)\n    }\n    userCount = int(userCountInt64)\n    return userCount, nil\n}\n```\n\nInstead, information about names that are clear from context or usage can often\nbe omitted:\n\n```go\n// Good:\nfunc (db *DB) UserCount() (int, error) {\n    var count int64\n    if err := db.Load(\"count(distinct users)\", &count); err != nil {\n        return 0, fmt.Errorf(\"failed to load user count: %s\", err)\n    }\n    return int(count), nil\n}\n```\n\n<a id=\"commentary\"></a>\n\n## Commentary\n\nThe conventions around commentary (which include what to comment, what style to\nuse, how to provide runnable examples, etc.) are intended to support the\nexperience of reading the documentation of a public API. See\n[Effective Go](http://golang.org/doc/effective_go.html#commentary) for more\ninformation.\n\nThe best practices document's section on [documentation conventions] discusses\nthis further.\n\n**Best Practice:** Use [doc preview] during development and code review to see\nwhether the documentation and runnable examples are useful and are presented the\nway you expect them to be.\n\n**Tip:** Godoc uses very little special formatting; lists and code snippets\nshould usually be indented to avoid linewrapping. Apart from indentation,\ndecoration should generally be avoided.\n\n[doc preview]: best-practices#documentation-preview\n[documentation conventions]:  best-practices#documentation-conventions\n\n<a id=\"comment-line-length\"></a>\n\n### Comment line length\n\nThere is no fixed [line length] for comments in Go.\n\n[line length]: guide#line-length\n\nLong comment lines should be wrapped to ensure that source is readable in tools\nwhich do not perform automatic wrapping of comment lines. If you are uncertain\nwhere to wrap, 80 or 100 columns are common choices. However, this is not a hard\ncut-off; there are situations where breaking a long literal text is harmful.\nThere is no requirement for the specific column width at which wrapping occurs.\nAim to be [consistent](guide#consistency) within a file.\n\nSee this [post from The Go Blog on documentation] for more on commentary.\n\n[post from The Go Blog on documentation]: https://blog.golang.org/godoc-documenting-go-code\n\n```text\n# Good:\n// This is a comment paragraph.\n// The length of individual lines doesn't matter in Godoc;\n// but the choice of wrapping makes it easy to read on narrow screens.\n//\n// Don't worry too much about the long URL:\n// https://supercalifragilisticexpialidocious.example.com:8080/Animalia/Chordata/Mammalia/Rodentia/Geomyoidea/Geomyidae/\n//\n// Similarly, if you have other information that is made awkward\n// by too many line breaks, use your judgment and include a long line\n// if it helps rather than hinders.\n```\n\nAvoid comments that fit large amounts of text onto a single line, which is a\npoor reader experience.\n\n```text\n# Bad:\n// This is a comment paragraph. While some code editors and viewers will wrap the paragraph for the reader, others will display a very long line that will overflow most windows and require users to scroll horizontally. In addition, even on a screen capable of displaying the entire line, it is easier to read a narrower paragraph than very wide one.\n//\n// Don't worry too much about the long URL:\n// https://supercalifragilisticexpialidocious.example.com:8080/Animalia/Chordata/Mammalia/Rodentia/Geomyoidea/Geomyidae/\n```\n\n<a id=\"doc-comments\"></a>\n\n### Doc comments\n\n<a id=\"TOC-DocComments\"></a>\n\nAll top-level exported names must have doc comments, as should unexported type\nor function declarations with unobvious behavior or meaning. These comments\nshould be [full sentences] that begin with the name of the object being\ndescribed. An article (\"a\", \"an\", \"the\") can precede the name to make it read\nmore naturally.\n\n```go\n// Good:\n// A Request represents a request to run a command.\ntype Request struct { ...\n\n// Encode writes the JSON encoding of req to w.\nfunc Encode(w io.Writer, req *Request) { ...\n```\n\nDoc comments appear in [Godoc](https://pkg.go.dev/) and are surfaced by IDEs,\nand therefore should be written for anyone using the package.\n\n[full sentences]: #comment-sentences\n\nA documentation comment applies to the following symbol, or the group of fields\nif it appears in a struct.\n\n```go\n// Good:\n// Options configure the group management service.\ntype Options struct {\n    // General setup:\n    Name  string\n    Group *FooGroup\n\n    // Dependencies:\n    DB *sql.DB\n\n    // Customization:\n    LargeGroupThreshold int // optional; default: 10\n    MinimumMembers      int // optional; default: 2\n}\n```\n\n**Best Practice:** If you have doc comments for unexported code, follow the same\ncustom as if it were exported (namely, starting the comment with the unexported\nname). This makes it easy to export it later by simply replacing the unexported\nname with the newly-exported one across both comments and code.\n\n<a id=\"comment-sentences\"></a>\n\n### Comment sentences\n\n<a id=\"TOC-CommentSentences\"></a>\n\nComments that are complete sentences should be capitalized and punctuated like\nstandard English sentences. (As an exception, it is okay to begin a sentence\nwith an uncapitalized identifier name if it is otherwise clear. Such cases are\nprobably best done only at the beginning of a paragraph.)\n\nComments that are sentence fragments have no such requirements for punctuation\nor capitalization.\n\n[Documentation comments] should always be complete sentences, and as such should\nalways be capitalized and punctuated. Simple end-of-line comments (especially\nfor struct fields) can be simple phrases that assume the field name is the\nsubject.\n\n```go\n// Good:\n// A Server handles serving quotes from the collected works of Shakespeare.\ntype Server struct {\n    // BaseDir points to the base directory under which Shakespeare's works are stored.\n    //\n    // The directory structure is expected to be the following:\n    //   {BaseDir}/manifest.json\n    //   {BaseDir}/{name}/{name}-part{number}.txt\n    BaseDir string\n\n    WelcomeMessage  string // displayed when user logs in\n    ProtocolVersion string // checked against incoming requests\n    PageLength      int    // lines per page when printing (optional; default: 20)\n}\n```\n\n[Documentation comments]: #doc-comments\n\n<a id=\"examples\"></a>\n\n### Examples\n\n<a id=\"TOC-Examples\"></a>\n\nPackages should clearly document their intended usage. Try to provide a\n[runnable example]; examples show up in Godoc. Runnable examples belong in the\ntest file, not the production source file. See this example ([Godoc], [source]).\n\n[runnable example]: http://blog.golang.org/examples\n[Godoc]: https://pkg.go.dev/time#example-Duration\n[source]: https://cs.opensource.google/go/go/+/HEAD:src/time/example_test.go\n\nIf it isn't feasible to provide a runnable example, example code can be provided\nwithin code comments. As with other code and command-line snippets in comments,\nit should follow standard formatting conventions.\n\n<a id=\"named-result-parameters\"></a>\n\n### Named result parameters\n\n<a id=\"TOC-NamedResultParameters\"></a>\n\nWhen naming parameters, consider how function signatures appear in Godoc. The\nname of the function itself and the type of the result parameters are often\nsufficiently clear.\n\n```go\n// Good:\nfunc (n *Node) Parent1() *Node\nfunc (n *Node) Parent2() (*Node, error)\n```\n\nIf a function returns two or more parameters of the same type, adding names can\nbe useful.\n\n```go\n// Good:\nfunc (n *Node) Children() (left, right *Node, err error)\n```\n\nIf the caller must take action on particular result parameters, naming them can\nhelp suggest what the action is:\n\n```go\n// Good:\n// WithTimeout returns a context that will be canceled no later than d duration\n// from now.\n//\n// The caller must arrange for the returned cancel function to be called when\n// the context is no longer needed to prevent a resource leak.\nfunc WithTimeout(parent Context, d time.Duration) (ctx Context, cancel func())\n```\n\nIn the code above, cancellation is a particular action a caller must take.\nHowever, were the result parameters written as `(Context, func())` alone, it\nwould be unclear what is meant by \"cancel function\".\n\nDon't use named result parameters when the names produce\n[unnecessary repetition](#repetitive-with-type).\n\n```go\n// Bad:\nfunc (n *Node) Parent1() (node *Node)\nfunc (n *Node) Parent2() (node *Node, err error)\n```\n\nDon't name result parameters in order to avoid declaring a variable inside the\nfunction. This practice results in unnecessary API verbosity at the cost of\nminor implementation brevity.\n\n[Naked returns] are acceptable only in a small function. Once it's a\nmedium-sized function, be explicit with your returned values. Similarly, do not\nname result parameters just because it enables you to use naked returns.\n[Clarity](guide#clarity) is always more important than saving a few lines in\nyour function.\n\nIt is always acceptable to name a result parameter if its value must be changed\nin a deferred closure.\n\n> **Tip:** Types can often be clearer than names in function signatures.\n> [GoTip #38: Functions as Named Types] demonstrates this.\n>\n> In, [`WithTimeout`] above, the real code uses a [`CancelFunc`] instead of a\n> raw `func()` in the result parameter list and requires little effort to\n> document.\n\n[Naked returns]: https://tour.golang.org/basics/7\n[GoTip #38: Functions as Named Types]: https://google.github.io/styleguide/go/index.html#gotip\n[`WithTimeout`]: https://pkg.go.dev/context#WithTimeout\n[`CancelFunc`]: https://pkg.go.dev/context#CancelFunc\n\n<a id=\"package-comments\"></a>\n\n### Package comments\n\n<a id=\"TOC-PackageComments\"></a>\n\nPackage comments must appear immediately above the package clause with no blank\nline between the comment and the package name. Example:\n\n```go\n// Good:\n// Package math provides basic constants and mathematical functions.\n//\n// This package does not guarantee bit-identical results across architectures.\npackage math\n```\n\nThere must be a single package comment per package. If a package is composed of\nmultiple files, exactly one of the files should have a package comment.\n\nComments for `main` packages have a slightly different form, where the name of\nthe `go_binary` rule in the BUILD file takes the place of the package name.\n\n```go\n// Good:\n// The seed_generator command is a utility that generates a Finch seed file\n// from a set of JSON study configs.\npackage main\n```\n\nOther styles of comment are fine as long as the name of the binary is exactly as\nwritten in the BUILD file. When the binary name is the first word, capitalizing\nit is required even though it does not strictly match the spelling of the\ncommand-line invocation.\n\n```go\n// Good:\n// Binary seed_generator ...\n// Command seed_generator ...\n// Program seed_generator ...\n// The seed_generator command ...\n// The seed_generator program ...\n// Seed_generator ...\n```\n\nTips:\n\n*   Example command-line invocations and API usage can be useful documentation.\n    For Godoc formatting, indent the comment lines containing code.\n\n*   If there is no obvious primary file or if the package comment is\n    extraordinarily long, it is acceptable to put the doc comment in a file\n    named `doc.go` with only the comment and the package clause.\n\n*   Multiline comments can be used instead of multiple single-line comments.\n    This is primarily useful if the documentation contains sections which may be\n    useful to copy and paste from the source file, as with sample command-lines\n    (for binaries) and template examples.\n\n    ```go\n    // Good:\n    /*\n    The seed_generator command is a utility that generates a Finch seed file\n    from a set of JSON study configs.\n\n        seed_generator *.json | base64 > finch-seed.base64\n    */\n    package template\n    ```\n\n*   Comments intended for maintainers and that apply to the whole file are\n    typically placed after import declarations. These are not surfaced in Godoc\n    and are not subject to the rules above on package comments.\n\n<a id=\"imports\"></a>\n\n## Imports\n\n<a id=\"TOC-Imports\"></a>\n\n<a id=\"import-renaming\"></a>\n\n### Import renaming\n\nPackage imports shouldn't normally be renamed, but there are cases where they\nmust be renamed or where a rename improves readability.\n\nLocal names for imported packages must follow\n[the guidance around package naming](#package-names), including the prohibition\non the use of underscores and capital letters. Try to be\n[consistent](guide#consistency) by always using the same local name for the same\nimported package.\n\nAn imported package *must* be renamed to avoid a name collision with other\nimports. (A corollary of this is that [good package names](#package-names)\nshould not require renaming.) In the event of a name collision, prefer to rename\nthe most local or project-specific import.\n\nGenerated protocol buffer packages *must* be renamed to remove underscores from\ntheir names, and their local names must have a `pb` suffix. See\n[proto and stub best practices](best-practices#import-protos) for more\ninformation.\n\n```go\n// Good:\nimport (\n    foosvcpb \"path/to/package/foo_service_go_proto\"\n)\n```\n\nLastly, an imported, non-autogenerated package *can* be renamed if it has an\nuninformative name (e.g. `util` or `v1`) Do this sparingly: do not rename the\npackage if the code surrounding the use of the package conveys enough context.\nWhen possible, prefer refactoring the package itself with a more suitable name.\n\n```go\n// Good:\nimport (\n    core \"github.com/kubernetes/api/core/v1\"\n    meta \"github.com/kubernetes/apimachinery/pkg/apis/meta/v1beta1\"\n)\n```\n\nIf you need to import a package whose name collides with a common local variable\nname that you want to use (e.g. `url`, `ssh`) and you wish to rename the\npackage, the preferred way to do so is with the `pkg` suffix (e.g. `urlpkg`).\nNote that it is possible to shadow a package with a local variable; this rename\nis only necessary if the package still needs to be used when such a variable is\nin scope.\n\n<a id=\"import-grouping\"></a>\n\n### Import grouping\n\nImports should be organized into the following groups, in order:\n\n1.  Standard library packages\n\n1.  Other (project and vendored) packages\n\n1.  Protocol Buffer imports (e.g., `fpb \"path/to/foo_go_proto\"`)\n\n1.  Import for [side-effects](https://go.dev/doc/effective_go#blank_import)\n    (e.g., `_ \"path/to/package\"`)\n\n```go\n// Good:\npackage main\n\nimport (\n    \"fmt\"\n    \"hash/adler32\"\n    \"os\"\n\n    \"github.com/dsnet/compress/flate\"\n    \"golang.org/x/text/encoding\"\n    \"google.golang.org/protobuf/proto\"\n\n    foopb \"myproj/foo/proto/proto\"\n\n    _ \"myproj/rpc/protocols/dial\"\n    _ \"myproj/security/auth/authhooks\"\n)\n```\n\n<a id=\"import-blank\"></a>\n\n### Import \"blank\" (`import _`)\n\n<a id=\"TOC-ImportBlank\"></a>\n\nPackages that are imported only for their side effects (using the syntax `import\n_ \"package\"`) may only be imported in a main package, or in tests that require\nthem.\n\nSome examples of such packages include:\n\n*   [time/tzdata](https://pkg.go.dev/time/tzdata)\n\n*   [image/jpeg](https://pkg.go.dev/image/jpeg) in image processing code\n\nAvoid blank imports in library packages, even if the library indirectly depends\non them. Constraining side-effect imports to the main package helps control\ndependencies, and makes it possible to write tests that rely on a different\nimport without conflict or wasted build costs.\n\nThe following are the only exceptions to this rule:\n\n*   You may use a blank import to bypass the check for disallowed imports in the\n    [nogo static checker].\n\n*   You may use a blank import of the [embed](https://pkg.go.dev/embed) package\n    in a source file which uses the `//go:embed` compiler directive.\n\n**Tip:** If you create a library package that indirectly depends on a\nside-effect import in production, document the intended usage.\n\n[nogo static checker]: https://github.com/bazelbuild/rules_go/blob/master/go/nogo.rst\n\n<a id=\"import-dot\"></a>\n\n### Import \"dot\" (`import .`)\n\n<a id=\"TOC-ImportDot\"></a>\n\nThe `import .` form is a language feature that allows bringing identifiers\nexported from another package to the current package without qualification. See\nthe [language spec](https://go.dev/ref/spec#Import_declarations) for more.\n\nDo **not** use this feature in the Google codebase; it makes it harder to tell\nwhere the functionality is coming from.\n\n```go\n// Bad:\npackage foo_test\n\nimport (\n    \"bar/testutil\" // also imports \"foo\"\n    . \"foo\"\n)\n\nvar myThing = Bar() // Bar defined in package foo; no qualification needed.\n```\n\n```go\n// Good:\npackage foo_test\n\nimport (\n    \"bar/testutil\" // also imports \"foo\"\n    \"foo\"\n)\n\nvar myThing = foo.Bar()\n```\n\n<a id=\"errors\"></a>\n\n## Errors\n\n<a id=\"returning-errors\"></a>\n\n### Returning errors\n\n<a id=\"TOC-ReturningErrors\"></a>\n\nUse `error` to signal that a function can fail. By convention, `error` is the\nlast result parameter.\n\n```go\n// Good:\nfunc Good() error { /* ... */ }\n```\n\nReturning a `nil` error is the idiomatic way to signal a successful operation\nthat could otherwise fail. If a function returns an error, callers must treat\nall non-error return values as unspecified unless explicitly documented\notherwise. Commonly, the non-error return values are their zero values, but this\ncannot be assumed.\n\n```go\n// Good:\nfunc GoodLookup() (*Result, error) {\n    // ...\n    if err != nil {\n        return nil, err\n    }\n    return res, nil\n}\n```\n\nExported functions that return errors should return them using the `error` type.\nConcrete error types are susceptible to subtle bugs: a concrete `nil` pointer\ncan get wrapped into an interface and thus become a non-nil value (see the\n[Go FAQ entry on the topic][nil error]).\n\n```go\n// Bad:\nfunc Bad() *os.PathError { /*...*/ }\n```\n\n**Tip:** A function that takes a [`context.Context`] argument should usually\nreturn an `error` so that the caller can determine if the context was cancelled\nwhile the function was running.\n\n[nil error]: https://golang.org/doc/faq#nil_error\n\n<a id=\"error-strings\"></a>\n\n### Error strings\n\n<a id=\"TOC-ErrorStrings\"></a>\n\nError strings should not be capitalized (unless beginning with an exported name,\na proper noun or an acronym) and should not end with punctuation. This is\nbecause error strings usually appear within other context before being printed\nto the user.\n\n```go\n// Bad:\nerr := fmt.Errorf(\"Something bad happened.\")\n```\n\n```go\n// Good:\nerr := fmt.Errorf(\"something bad happened\")\n```\n\nOn the other hand, the style for the full displayed message (logging, test\nfailure, API response, or other UI) depends, but should typically be\ncapitalized.\n\n```go\n// Good:\nlog.Infof(\"Operation aborted: %v\", err)\nlog.Errorf(\"Operation aborted: %v\", err)\nt.Errorf(\"Op(%q) failed unexpectedly; err=%v\", args, err)\n```\n\n<a id=\"handle-errors\"></a>\n\n### Handle errors\n\n<a id=\"TOC-HandleErrors\"></a>\n\nCode that encounters an error should make a deliberate choice about how to\nhandle it. It is not usually appropriate to discard errors using `_` variables.\nIf a function returns an error, do one of the following:\n\n*   Handle and address the error immediately.\n*   Return the error to the caller.\n*   In exceptional situations, call [`log.Fatal`] or (if absolutely necessary)\n    `panic`.\n\n**Note:** `log.Fatalf` is not the standard library log. See [#logging].\n\nIn the rare circumstance where it is appropriate to ignore or discard an error\n(for example a call to [`(*bytes.Buffer).Write`] that is documented to never\nfail), an accompanying comment should explain why this is safe.\n\n```go\n// Good:\nvar b *bytes.Buffer\n\nn, _ := b.Write(p) // never returns a non-nil error\n```\n\nFor more discussion and examples of error handling, see\n[Effective Go](http://golang.org/doc/effective_go.html#errors) and\n[best practices](best-practices.md#error-handling).\n\n[`(*bytes.Buffer).Write`]: https://pkg.go.dev/bytes#Buffer.Write\n\n<a id=\"in-band-errors\"></a>\n\n### In-band errors\n\n<a id=\"TOC-In-Band-Errors\"></a>\n\nIn C and similar languages, it is common for functions to return values like -1,\nnull, or the empty string to signal errors or missing results. This is known as\nin-band error handling.\n\n```go\n// Bad:\n// Lookup returns the value for key or -1 if there is no mapping for key.\nfunc Lookup(key string) int\n```\n\nFailing to check for an in-band error value can lead to bugs and can attribute\nerrors to the wrong function.\n\n```go\n// Bad:\n// The following line returns an error that Parse failed for the input value,\n// whereas the failure was that there is no mapping for missingKey.\nreturn Parse(Lookup(missingKey))\n```\n\nGo's support for multiple return values provides a better solution (see the\n[Effective Go section on multiple returns]). Instead of requiring clients to\ncheck for an in-band error value, a function should return an additional value\nto indicate whether its other return values are valid. This return value may be\nan error or a boolean when no explanation is needed, and should be the final\nreturn value.\n\n```go\n// Good:\n// Lookup returns the value for key or ok=false if there is no mapping for key.\nfunc Lookup(key string) (value string, ok bool)\n```\n\nThis API prevents the caller from incorrectly writing `Parse(Lookup(key))` which\ncauses a compile-time error, since `Lookup(key)` has 2 outputs.\n\nReturning errors in this way encourages more robust and explicit error handling:\n\n```go\n// Good:\nvalue, ok := Lookup(key)\nif !ok {\n    return fmt.Errorf(\"no value for %q\", key)\n}\nreturn Parse(value)\n```\n\nSome standard library functions, like those in package `strings`, return in-band\nerror values. This greatly simplifies string-manipulation code at the cost of\nrequiring more diligence from the programmer. In general, Go code in the Google\ncodebase should return additional values for errors.\n\n[Effective Go section on multiple returns]: http://golang.org/doc/effective_go.html#multiple-returns\n\n<a id=\"indent-error-flow\"></a>\n\n### Indent error flow\n\n<a id=\"TOC-IndentErrorFlow\"></a>\n\nHandle errors before proceeding with the rest of your code. This improves the\nreadability of the code by enabling the reader to find the normal path quickly.\nThis same logic applies to any block which tests a condition then ends in a\nterminal condition (e.g., `return`, `panic`, `log.Fatal`).\n\nCode that runs if the terminal condition is not met should appear after the `if`\nblock, and should not be indented in an `else` clause.\n\n```go\n// Good:\nif err != nil {\n    // error handling\n    return // or continue, etc.\n}\n// normal code\n```\n\n```go\n// Bad:\nif err != nil {\n    // error handling\n} else {\n    // normal code that looks abnormal due to indentation\n}\n```\n\n> **Tip:** If you are using a variable for more than a few lines of code, it is\n> generally not worth using the `if`-with-initializer style. In these cases, it\n> is usually better to move the declaration out and use a standard `if`\n> statement:\n>\n> ```go\n> // Good:\n> x, err := f()\n> if err != nil {\n>   // error handling\n>   return\n> }\n> // lots of code that uses x\n> // across multiple lines\n> ```\n>\n> ```go\n> // Bad:\n> if x, err := f(); err != nil {\n>   // error handling\n>   return\n> } else {\n>   // lots of code that uses x\n>   // across multiple lines\n> }\n> ```\n\nSee [Go Tip #1: Line of Sight] and\n[TotT: Reduce Code Complexity by Reducing Nesting](https://testing.googleblog.com/2017/06/code-health-reduce-nesting-reduce.html)\nfor more details.\n\n[Go Tip #1: Line of Sight]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"language\"></a>\n\n## Language\n\n<a id=\"literal-formatting\"></a>\n\n### Literal formatting\n\nGo has an exceptionally powerful [composite literal syntax], with which it is\npossible to express deeply-nested, complicated values in a single expression.\nWhere possible, this literal syntax should be used instead of building values\nfield-by-field. The `gofmt` formatting for literals is generally quite good, but\nthere are some additional rules for keeping these literals readable and\nmaintainable.\n\n[composite literal syntax]: https://golang.org/ref/spec#Composite_literals\n\n<a id=\"literal-field-names\"></a>\n\n#### Field names\n\nStruct literals must specify **field names** for types defined outside the\ncurrent package.\n\n*   Include field names for types from other packages.\n\n    ```go\n    // Good:\n    // https://pkg.go.dev/encoding/csv#Reader\n    r := csv.Reader{\n      Comma: ',',\n      Comment: '#',\n      FieldsPerRecord: 4,\n    }\n    ```\n\n    The position of fields in a struct and the full set of fields (both of which\n    are necessary to get right when field names are omitted) are not usually\n    considered to be part of a struct's public API; specifying the field name is\n    needed to avoid unnecessary coupling.\n\n    ```go\n    // Bad:\n    r := csv.Reader{',', '#', 4, false, false, false, false}\n    ```\n\n*   For package-local types, field names are optional.\n\n    ```go\n    // Good:\n    okay := Type{42}\n    also := internalType{4, 2}\n    ```\n\n    Field names should still be used if it makes the code clearer, and it is\n    very common to do so. For example, a struct with a large number of fields\n    should almost always be initialized with field names.\n\n    <!-- TODO: Maybe a better example here that doesn't have many fields. -->\n\n    ```go\n    // Good:\n    okay := StructWithLotsOfFields{\n      field1: 1,\n      field2: \"two\",\n      field3: 3.14,\n      field4: true,\n    }\n    ```\n\n<a id=\"literal-matching-braces\"></a>\n\n#### Matching braces\n\nThe closing half of a brace pair should always appear on a line with the same\namount of indentation as the opening brace. One-line literals necessarily have\nthis property. When the literal spans multiple lines, maintaining this property\nkeeps the brace matching for literals the same as brace matching for common Go\nsyntactic constructs like functions and `if` statements.\n\nThe most common mistake in this area is putting the closing brace on the same\nline as a value in a multi-line struct literal. In these cases, the line should\nend with a comma and the closing brace should appear on the next line.\n\n```go\n// Good:\ngood := []*Type{{Key: \"value\"}}\n```\n\n```go\n// Good:\ngood := []*Type{\n    {Key: \"multi\"},\n    {Key: \"line\"},\n}\n```\n\n```go\n// Bad:\nbad := []*Type{\n    {Key: \"multi\"},\n    {Key: \"line\"}}\n```\n\n```go\n// Bad:\nbad := []*Type{\n    {\n        Key: \"value\"},\n}\n```\n\n<a id=\"literal-cuddled-braces\"></a>\n\n#### Cuddled braces\n\nDropping whitespace between braces (aka \"cuddling\" them) for slice and array\nliterals is only permitted when both of the following are true.\n\n*   The [indentation matches](#literal-matching-braces)\n*   The inner values are also literals or proto builders (i.e. not a variable or\n    other expression)\n\n```go\n// Good:\ngood := []*Type{\n    { // Not cuddled\n        Field: \"value\",\n    },\n    {\n        Field: \"value\",\n    },\n}\n```\n\n```go\n// Good:\ngood := []*Type{{ // Cuddled correctly\n    Field: \"value\",\n}, {\n    Field: \"value\",\n}}\n```\n\n```go\n// Good:\ngood := []*Type{\n    first, // Can't be cuddled\n    {Field: \"second\"},\n}\n```\n\n```go\n// Good:\nokay := []*pb.Type{pb.Type_builder{\n    Field: \"first\", // Proto Builders may be cuddled to save vertical space\n}.Build(), pb.Type_builder{\n    Field: \"second\",\n}.Build()}\n```\n\n```go\n// Bad:\nbad := []*Type{\n    first,\n    {\n        Field: \"second\",\n    }}\n```\n\n<a id=\"literal-repeated-type-names\"></a>\n\n#### Repeated type names\n\nRepeated type names may be omitted from slice and map literals. This can be\nhelpful in reducing clutter. A reasonable occasion for repeating the type names\nexplicitly is when dealing with a complex type that is not common in your\nproject, when the repetitive type names are on lines that are far apart and can\nremind the reader of the context.\n\n```go\n// Good:\ngood := []*Type{\n    {A: 42},\n    {A: 43},\n}\n```\n\n```go\n// Bad:\nrepetitive := []*Type{\n    &Type{A: 42},\n    &Type{A: 43},\n}\n```\n\n```go\n// Good:\ngood := map[Type1]*Type2{\n    {A: 1}: {B: 2},\n    {A: 3}: {B: 4},\n}\n```\n\n```go\n// Bad:\nrepetitive := map[Type1]*Type2{\n    Type1{A: 1}: &Type2{B: 2},\n    Type1{A: 3}: &Type2{B: 4},\n}\n```\n\n**Tip:** If you want to remove repetitive type names in struct literals, you can\nrun `gofmt -s`.\n\n<a id=\"literal-zero-value-fields\"></a>\n\n#### Zero-value fields\n\n[Zero-value] fields may be omitted from struct literals when clarity is not lost\nas a result.\n\nWell-designed APIs often employ zero-value construction for enhanced\nreadability. For example, omitting the three zero-value fields from the\nfollowing struct draws attention to the only option that is being specified.\n\n[Zero-value]: https://golang.org/ref/spec#The_zero_value\n\n```go\n// Bad:\nimport (\n  \"github.com/golang/leveldb\"\n  \"github.com/golang/leveldb/db\"\n)\n\nldb := leveldb.Open(\"/my/table\", &db.Options{\n    BlockSize: 1<<16,\n    ErrorIfDBExists: true,\n\n    // These fields all have their zero values.\n    BlockRestartInterval: 0,\n    Comparer: nil,\n    Compression: nil,\n    FileSystem: nil,\n    FilterPolicy: nil,\n    MaxOpenFiles: 0,\n    WriteBufferSize: 0,\n    VerifyChecksums: false,\n})\n```\n\n```go\n// Good:\nimport (\n  \"github.com/golang/leveldb\"\n  \"github.com/golang/leveldb/db\"\n)\n\nldb := leveldb.Open(\"/my/table\", &db.Options{\n    BlockSize: 1<<16,\n    ErrorIfDBExists: true,\n})\n```\n\nStructs within table-driven tests often benefit from [explicit field names],\nespecially when the test struct is not trivial. This allows the author to omit\nthe zero-valued fields entirely when the fields in question are not related to\nthe test case. For example, successful test cases should omit any error-related\nor failure-related fields. In cases where the zero value is necessary to\nunderstand the test case, such as testing for zero or `nil` inputs, the field\nnames should be specified.\n\n[explicit field names]: #literal-field-names\n\n**Concise**\n\n```go\ntests := []struct {\n    input      string\n    wantPieces []string\n    wantErr    error\n}{\n    {\n        input:      \"1.2.3.4\",\n        wantPieces: []string{\"1\", \"2\", \"3\", \"4\"},\n    },\n    {\n        input:   \"hostname\",\n        wantErr: ErrBadHostname,\n    },\n}\n```\n\n**Explicit**\n\n```go\ntests := []struct {\n    input    string\n    wantIPv4 bool\n    wantIPv6 bool\n    wantErr  bool\n}{\n    {\n        input:    \"1.2.3.4\",\n        wantIPv4: true,\n        wantIPv6: false,\n    },\n    {\n        input:    \"1:2::3:4\",\n        wantIPv4: false,\n        wantIPv6: true,\n    },\n    {\n        input:    \"hostname\",\n        wantIPv4: false,\n        wantIPv6: false,\n        wantErr:  true,\n    },\n}\n```\n\n<a id=\"nil-slices\"></a>\n\n### Nil slices\n\nFor most purposes, there is no functional difference between `nil` and the empty\nslice. Built-in functions like `len` and `cap` behave as expected on `nil`\nslices.\n\n```go\n// Good:\nimport \"fmt\"\n\nvar s []int         // nil\n\nfmt.Println(s)      // []\nfmt.Println(len(s)) // 0\nfmt.Println(cap(s)) // 0\nfor range s {...}   // no-op\n\ns = append(s, 42)\nfmt.Println(s)      // [42]\n```\n\nIf you declare an empty slice as a local variable (especially if it can be the\nsource of a return value), prefer the nil initialization to reduce the risk of\nbugs by callers.\n\n```go\n// Good:\nvar t []string\n```\n\n```go\n// Bad:\nt := []string{}\n```\n\nDo not create APIs that force their clients to make distinctions between nil and\nthe empty slice.\n\n```go\n// Good:\n// Ping pings its targets.\n// Returns hosts that successfully responded.\nfunc Ping(hosts []string) ([]string, error) { ... }\n```\n\n```go\n// Bad:\n// Ping pings its targets and returns a list of hosts\n// that successfully responded. Can be empty if the input was empty.\n// nil signifies that a system error occurred.\nfunc Ping(hosts []string) []string { ... }\n```\n\nWhen designing interfaces, avoid making a distinction between a `nil` slice and\na non-`nil`, zero-length slice, as this can lead to subtle programming errors.\nThis is typically accomplished by using `len` to check for emptiness, rather\nthan `== nil`.\n\nThis implementation accepts both `nil` and zero-length slices as \"empty\":\n\n```go\n// Good:\n// describeInts describes s with the given prefix, unless s is empty.\nfunc describeInts(prefix string, s []int) {\n    if len(s) == 0 {\n        return\n    }\n    fmt.Println(prefix, s)\n}\n```\n\nInstead of relying on the distinction as a part of the API:\n\n```go\n// Bad:\nfunc maybeInts() []int { /* ... */ }\n\n// describeInts describes s with the given prefix; pass nil to skip completely.\nfunc describeInts(prefix string, s []int) {\n  // The behavior of this function unintentionally changes depending on what\n  // maybeInts() returns in 'empty' cases (nil or []int{}).\n  if s == nil {\n    return\n  }\n  fmt.Println(prefix, s)\n}\n\ndescribeInts(\"Here are some ints:\", maybeInts())\n```\n\nSee [in-band errors] for further discussion.\n\n[in-band errors]: #in-band-errors\n\n<a id=\"indentation-confusion\"></a>\n\n### Indentation confusion\n\nAvoid introducing a line break if it would align the rest of the line with an\nindented code block. If this is unavoidable, leave a space to separate the code\nin the block from the wrapped line.\n\n```go\n// Bad:\nif longCondition1 && longCondition2 &&\n    // Conditions 3 and 4 have the same indentation as the code within the if.\n    longCondition3 && longCondition4 {\n    log.Info(\"all conditions met\")\n}\n```\n\nSee the following sections for specific guidelines and examples:\n\n*   [Function formatting](#func-formatting)\n*   [Conditionals and loops](#conditional-formatting)\n*   [Literal formatting](#literal-formatting)\n\n<a id=\"func-formatting\"></a>\n\n### Function formatting\n\nThe signature of a function or method declaration should remain on a single line\nto avoid [indentation confusion](#indentation-confusion).\n\nFunction argument lists can make some of the longest lines in a Go source file.\nHowever, they precede a change in indentation, and therefore it is difficult to\nbreak the line in a way that does not make subsequent lines look like part of\nthe function body in a confusing way:\n\n```go\n// Bad:\nfunc (r *SomeType) SomeLongFunctionName(foo1, foo2, foo3 string,\n    foo4, foo5, foo6 int) {\n    foo7 := bar(foo1)\n    // ...\n}\n```\n\nSee [best practices](best-practices#funcargs) for a few options for shortening\nthe call sites of functions that would otherwise have many arguments.\n\nLines can often be shortened by factoring out local variables.\n\n```go\n// Good:\nlocal := helper(some, parameters, here)\ngood := foo.Call(list, of, parameters, local)\n```\n\nSimilarly, function and method calls should not be separated based solely on\nline length.\n\n```go\n// Good:\ngood := foo.Call(long, list, of, parameters, all, on, one, line)\n```\n\n```go\n// Bad:\nbad := foo.Call(long, list, of, parameters,\n    with, arbitrary, line, breaks)\n```\n\nAvoid adding inline comments to specific function arguments where possible.\nInstead, use an [option struct](best-practices#option-structure) or add more\ndetail to the function documentation.\n\n```go\n// Good:\ngood := server.New(ctx, server.Options{Port: 42})\n```\n\n```go\n// Bad:\nbad := server.New(\n    ctx,\n    42, // Port\n)\n```\n\nIf the API cannot be changed or if the local call is unusual (whether or not the\ncall is too long), it is always permissible to add line breaks if it aids in\nunderstanding the call.\n\n```go\n// Good:\ncanvas.RenderHeptagon(fillColor,\n    x0, y0, vertexColor0,\n    x1, y1, vertexColor1,\n    x2, y2, vertexColor2,\n    x3, y3, vertexColor3,\n    x4, y4, vertexColor4,\n    x5, y5, vertexColor5,\n    x6, y6, vertexColor6,\n)\n```\n\nNote that the lines in the above example are not wrapped at a specific column\nboundary but are grouped based on vertex coordinates and color.\n\nLong string literals within functions should not be broken for the sake of line\nlength. For functions that include such strings, a line break can be added after\nthe string format, and the arguments can be provided on the next or subsequent\nlines. The decision about where the line breaks should go is best made based on\nsemantic groupings of inputs, rather than based purely on line length.\n\n```go\n// Good:\nlog.Warningf(\"Database key (%q, %d, %q) incompatible in transaction started by (%q, %d, %q)\",\n    currentCustomer, currentOffset, currentKey,\n    txCustomer, txOffset, txKey)\n```\n\n```go\n// Bad:\nlog.Warningf(\"Database key (%q, %d, %q) incompatible in\"+\n    \" transaction started by (%q, %d, %q)\",\n    currentCustomer, currentOffset, currentKey, txCustomer,\n    txOffset, txKey)\n```\n\n<a id=\"conditional-formatting\"></a>\n\n### Conditionals and loops\n\nAn `if` statement should not be line broken; multi-line `if` clauses can lead to\n[indentation confusion](#indentation-confusion).\n\n```go\n// Bad:\n// The second if statement is aligned with the code within the if block, causing\n// indentation confusion.\nif db.CurrentStatusIs(db.InTransaction) &&\n    db.ValuesEqual(db.TransactionKey(), row.Key()) {\n    return db.Errorf(db.TransactionError, \"query failed: row (%v): key does not match transaction key\", row)\n}\n```\n\nIf the short-circuit behavior is not required, the boolean operands can be\nextracted directly:\n\n```go\n// Good:\ninTransaction := db.CurrentStatusIs(db.InTransaction)\nkeysMatch := db.ValuesEqual(db.TransactionKey(), row.Key())\nif inTransaction && keysMatch {\n    return db.Error(db.TransactionError, \"query failed: row (%v): key does not match transaction key\", row)\n}\n```\n\nThere may also be other locals that can be extracted, especially if the\nconditional is already repetitive:\n\n```go\n// Good:\nuid := user.GetUniqueUserID()\nif db.UserIsAdmin(uid) || db.UserHasPermission(uid, perms.ViewServerConfig) || db.UserHasPermission(uid, perms.CreateGroup) {\n    // ...\n}\n```\n\n```go\n// Bad:\nif db.UserIsAdmin(user.GetUniqueUserID()) || db.UserHasPermission(user.GetUniqueUserID(), perms.ViewServerConfig) || db.UserHasPermission(user.GetUniqueUserID(), perms.CreateGroup) {\n    // ...\n}\n```\n\n`if` statements that contain closures or multi-line struct literals should\nensure that the [braces match](#literal-matching-braces) to avoid\n[indentation confusion](#indentation-confusion).\n\n```go\n// Good:\nif err := db.RunInTransaction(func(tx *db.TX) error {\n    return tx.Execute(userUpdate, x, y, z)\n}); err != nil {\n    return fmt.Errorf(\"user update failed: %s\", err)\n}\n```\n\n```go\n// Good:\nif _, err := client.Update(ctx, &upb.UserUpdateRequest{\n    ID:   userID,\n    User: user,\n}); err != nil {\n    return fmt.Errorf(\"user update failed: %s\", err)\n}\n```\n\nSimilarly, don't try inserting artificial linebreaks into `for` statements. You\ncan always let the line simply be long if there is no elegant way to refactor\nit:\n\n```go\n// Good:\nfor i, max := 0, collection.Size(); i < max && !collection.HasPendingWriters(); i++ {\n    // ...\n}\n```\n\nOften, though, there is:\n\n```go\n// Good:\nfor i, max := 0, collection.Size(); i < max; i++ {\n    if collection.HasPendingWriters() {\n        break\n    }\n    // ...\n}\n```\n\n`switch` and `case` statements should also remain on a single line.\n\n```go\n// Good:\nswitch good := db.TransactionStatus(); good {\ncase db.TransactionStarting, db.TransactionActive, db.TransactionWaiting:\n    // ...\ncase db.TransactionCommitted, db.NoTransaction:\n    // ...\ndefault:\n    // ...\n}\n```\n\n```go\n// Bad:\nswitch bad := db.TransactionStatus(); bad {\ncase db.TransactionStarting,\n    db.TransactionActive,\n    db.TransactionWaiting:\n    // ...\ncase db.TransactionCommitted,\n    db.NoTransaction:\n    // ...\ndefault:\n    // ...\n}\n```\n\nIf the line is excessively long, indent all cases and separate them with a blank\nline to avoid [indentation confusion](#indentation-confusion):\n\n```go\n// Good:\nswitch db.TransactionStatus() {\ncase\n    db.TransactionStarting,\n    db.TransactionActive,\n    db.TransactionWaiting,\n    db.TransactionCommitted:\n\n    // ...\ncase db.NoTransaction:\n    // ...\ndefault:\n    // ...\n}\n```\n\nIn conditionals comparing a variable to a constant, place the variable value on\nthe left hand side of the equality operator:\n\n```go\n// Good:\nif result == \"foo\" {\n  // ...\n}\n```\n\nInstead of the less clear phrasing where the constant comes first\n([\"Yoda style conditionals\"](https://en.wikipedia.org/wiki/Yoda_conditions)):\n\n```go\n// Bad:\nif \"foo\" == result {\n  // ...\n}\n```\n\n<a id=\"copying\"></a>\n\n### Copying\n\n<a id=\"TOC-Copying\"></a>\n\nTo avoid unexpected aliasing and similar bugs, be careful when copying a struct\nfrom another package. For example, synchronization objects such as `sync.Mutex`\nmust not be copied.\n\nThe `bytes.Buffer` type contains a `[]byte` slice and, as an optimization for\nsmall strings, a small byte array to which the slice may refer. If you copy a\n`Buffer`, the slice in the copy may alias the array in the original, causing\nsubsequent method calls to have surprising effects.\n\nIn general, do not copy a value of type `T` if its methods are associated with\nthe pointer type, `*T`.\n\n```go\n// Bad:\nb1 := bytes.Buffer{}\nb2 := b1\n```\n\nInvoking a method that takes a value receiver can hide the copy. When you author\nan API, you should generally take and return pointer types if your structs\ncontain fields that should not be copied.\n\nThese are acceptable:\n\n```go\n// Good:\ntype Record struct {\n  buf bytes.Buffer\n  // other fields omitted\n}\n\nfunc New() *Record {...}\n\nfunc (r *Record) Process(...) {...}\n\nfunc Consumer(r *Record) {...}\n```\n\nBut these are usually wrong:\n\n```go\n// Bad:\ntype Record struct {\n  buf bytes.Buffer\n  // other fields omitted\n}\n\n\nfunc (r Record) Process(...) {...} // Makes a copy of r.buf\n\nfunc Consumer(r Record) {...} // Makes a copy of r.buf\n```\n\nThis guidance also applies to copying `sync.Mutex`.\n\n<a id=\"dont-panic\"></a>\n\n### Don't panic\n\n<a id=\"TOC-Don-t-Panic\"></a>\n\nDo not use `panic` for normal error handling. Instead, use `error` and multiple\nreturn values. See the [Effective Go section on errors].\n\nWithin `package main` and initialization code, consider [`log.Exit`] for errors\nthat should terminate the program (e.g., invalid configuration), as in many of\nthese cases a stack trace will not help the reader. Please note that\n[`log.Exit`] calls [`os.Exit`] and any deferred functions will not be run.\n\nFor errors that indicate \"impossible\" conditions, namely bugs that should always\nbe caught during code review and/or testing, a function may reasonably return an\nerror or call [`log.Fatal`].\n\nAlso see [when panic is acceptable](best-practices.md#when-to-panic).\n\n**Note:** `log.Fatalf` is not the standard library log. See [#logging].\n\n[Effective Go section on errors]: http://golang.org/doc/effective_go.html#errors\n[`os.Exit`]: https://pkg.go.dev/os#Exit\n\n<a id=\"must-functions\"></a>\n\n### Must functions\n\nSetup helper functions that stop the program on failure follow the naming\nconvention `MustXYZ` (or `mustXYZ`). In general, they should only be called\nearly on program startup, not on things like user input where normal Go error\nhandling is preferred.\n\nThis often comes up for functions called to initialize package-level variables\nexclusively at\n[package initialization time](https://golang.org/ref/spec#Package_initialization)\n(e.g. [template.Must](https://golang.org/pkg/text/template/#Must) and\n[regexp.MustCompile](https://golang.org/pkg/regexp/#MustCompile)).\n\n```go\n// Good:\nfunc MustParse(version string) *Version {\n    v, err := Parse(version)\n    if err != nil {\n        panic(fmt.Sprintf(\"MustParse(%q) = _, %v\", version, err))\n    }\n    return v\n}\n\n// Package level \"constant\". If we wanted to use `Parse`, we would have had to\n// set the value in `init`.\nvar DefaultVersion = MustParse(\"1.2.3\")\n```\n\nThe same convention may be used in test helpers that only stop the current test\n(using `t.Fatal`). Such helpers are often convenient in creating test values,\nfor example in struct fields of [table driven tests](#table-driven-tests), as\nfunctions that return errors cannot be directly assigned to a struct field.\n\n```go\n// Good:\nfunc mustMarshalAny(t *testing.T, m proto.Message) *anypb.Any {\n  t.Helper()\n  any, err := anypb.New(m)\n  if err != nil {\n    t.Fatalf(\"mustMarshalAny(t, m) = %v; want %v\", err, nil)\n  }\n  return any\n}\n\nfunc TestCreateObject(t *testing.T) {\n  tests := []struct{\n    desc string\n    data *anypb.Any\n  }{\n    {\n      desc: \"my test case\",\n      // Creating values directly within table driven test cases.\n      data: mustMarshalAny(t, mypb.Object{}),\n    },\n    // ...\n  }\n  // ...\n}\n```\n\nIn both of these cases, the value of this pattern is that the helpers can be\ncalled in a \"value\" context. These helpers should not be called in places where\nit's difficult to ensure an error would be caught or in a context where an error\nshould be [checked](#handle-errors) (e.g., in many request handlers). For\nconstant inputs, this allows tests to easily ensure that the `Must` arguments\nare well-formed, and for non-constant inputs it permits tests to validate that\nerrors are [properly handled or propagated](best-practices#error-handling).\n\nWhere `Must` functions are used in a test, they should generally be\n[marked as a test helper](#mark-test-helpers) and call `t.Fatal` on error (see\n[error handling in test helpers](best-practices#test-helper-error-handling) for\nmore considerations of using that).\n\nThey should not be used when\n[ordinary error handling](best-practices#error-handling) is possible (including\nwith some refactoring):\n\n```go\n// Bad:\nfunc Version(o *servicepb.Object) (*version.Version, error) {\n    // Return error instead of using Must functions.\n    v := version.MustParse(o.GetVersionString())\n    return dealiasVersion(v)\n}\n```\n\n<a id=\"goroutine-lifetimes\"></a>\n\n### Goroutine lifetimes\n\n<a id=\"TOC-GoroutineLifetimes\"></a>\n\nWhen you spawn goroutines, make it clear when or whether they exit.\n\nGoroutines can leak by blocking on channel sends or receives. The garbage\ncollector will not terminate a goroutine blocked on a channel even if no other\ngoroutine has a reference to the channel.\n\nEven when goroutines do not leak, leaving them in-flight when they are no longer\nneeded can cause other subtle and hard-to-diagnose problems. Sending on a\nchannel that has been closed causes a panic.\n\n```go\n// Bad:\nch := make(chan int)\nch <- 42\nclose(ch)\nch <- 13 // panic\n```\n\nModifying still-in-use inputs \"after the result isn't needed\" can lead to data\nraces. Leaving goroutines in-flight for arbitrarily long can lead to\nunpredictable memory usage.\n\nConcurrent code should be written such that the goroutine lifetimes are obvious.\nTypically this will mean keeping synchronization-related code constrained within\nthe scope of a function and factoring out the logic into\n[synchronous functions]. If the concurrency is still not obvious, it is\nimportant to document when and why the goroutines exit.\n\nCode that follows best practices around context usage often helps make this\nclear. It is conventionally managed with a [`context.Context`]:\n\n```go\n// Good:\nfunc (w *Worker) Run(ctx context.Context) error {\n    var wg sync.WaitGroup\n    // ...\n    for item := range w.q {\n        // process returns at latest when the context is cancelled.\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            process(ctx, item)\n        }()\n    }\n    // ...\n    wg.Wait()  // Prevent spawned goroutines from outliving this function.\n}\n```\n\nThere are other variants of the above that use raw signal channels like `chan\nstruct{}`, synchronized variables, [condition variables][rethinking-slides], and\nmore. The important part is that the goroutine's end is evident for subsequent\nmaintainers.\n\nIn contrast, the following code is careless about when its spawned goroutines\nfinish:\n\n```go\n// Bad:\nfunc (w *Worker) Run() {\n    // ...\n    for item := range w.q {\n        // process returns when it finishes, if ever, possibly not cleanly\n        // handling a state transition or termination of the Go program itself.\n        go process(item)\n    }\n    // ...\n}\n```\n\nThis code may look OK, but there are several underlying problems:\n\n*   The code probably has undefined behavior in production, and the program may\n    not terminate cleanly, even if the operating system releases the resources.\n\n*   The code is difficult to test meaningfully due to the code's indeterminate\n    lifecycle.\n\n*   The code may leak resources as described above.\n\nSee also:\n\n*   [Never start a goroutine without knowing how it will stop][cheney-stop]\n*   Rethinking Classical Concurrency Patterns: [slides][rethinking-slides],\n    [video][rethinking-video]\n*   [When Go programs end]\n*   [Documentation Conventions: Contexts]\n\n[synchronous functions]: #synchronous-functions\n[cheney-stop]: https://dave.cheney.net/2016/12/22/never-start-a-goroutine-without-knowing-how-it-will-stop\n[rethinking-slides]: https://drive.google.com/file/d/1nPdvhB0PutEJzdCq5ms6UI58dp50fcAN/view\n[rethinking-video]: https://www.youtube.com/watch?v=5zXAHh5tJqQ\n[When Go programs end]: https://changelog.com/gotime/165\n[Documentation Conventions: Contexts]: best-practices.md#documentation-conventions-contexts\n\n<a id=\"interfaces\"></a>\n\n### Interfaces\n\n<a id=\"TOC-Interfaces\"></a>\n\nAvoid creating interfaces until a [real need](guide#simplicity) exists. Focus on\nthe required behavior rather than just abstract named patterns like \"service\" or\n\"repository\" and the like.\n\n*   Do not wrap RPC clients in new manual interfaces just for the sake of\n    abstraction or testing.\n    [Use real transports](best-practices#use-real-transports) instead\n    ([testing RPC]).\n\n*   Do not define back doors or export [test double] implementations of an\n    interface solely for testing. Prefer testing via the [public API] of the\n    real implementation instead.\n\nDesign interfaces to be small for easier implementation and composition\n([GoTip #78: Minimal Viable Interfaces]). Document interfaces appropriately\nincluding their contract, edge cases, and expected errors. Keep interface types\nunexported if they are only used internally within a package.\n\nThe consumer of the interface should define it (not the package implementing the\ninterface), ensuring it includes only the methods they actually use. The\nproducer package may export the interface if the interface is the product (a\ncommon protocol) to prevent interface redefinition bloat.\n\nThere is an adage: Functions should take interfaces as arguments but return\nconcrete types ([GoTip #49: Accept Interfaces, Return Concrete Types]).\nReturning concrete types allows the caller to have access to every public method\nand field of that specific implementation, not just the subset of methods\ndefined in a pre-chosen interface. The caller can still pass that concrete\nresult into any other function that expects an interface. Sometimes returning an\ninterface is acceptable for encapsulation (e.g., `error` interface), and certain\nconstructs like command, chaining, factory, and\n[strategy](https://en.wikipedia.org/wiki/Strategy_pattern) patterns.\n\nDeeper discussion on interfaces exists in the\n[Best Practices' section on interfaces](best-practices#interfaces).\n\n[GoTip #78: Minimal Viable Interfaces]: https://google.github.io/styleguide/go/index.html#gotip\n[GoTip #49: Accept Interfaces, Return Concrete Types]: https://google.github.io/styleguide/go/index.html#gotip\n[testing RPC]: https://codelabs.developers.google.com/grpc/getting-started-grpc-go#3\n[test double]: https://abseil.io/resources/swe-book/html/ch13.html\n[public API]: https://abseil.io/resources/swe-book/html/ch12.html#test_via_public_apis\n\n<a id=\"generics\"></a>\n\n### Generics\n\nGenerics (formally called \"[Type Parameters]\") are allowed where they fulfill\nyour business requirements. In many applications, a conventional approach using\nexisting language features (slices, maps, interfaces, and so on) works just as\nwell without the added complexity, so be wary of premature use. See the\ndiscussion on [least mechanism](guide#least-mechanism).\n\nWhen introducing an exported API that uses generics, make sure it is suitably\ndocumented. It's highly encouraged to include motivating runnable [examples].\n\nDo not use generics just because you are implementing an algorithm or data\nstructure that does not care about the type of its member elements. If there is\nonly one type being instantiated in practice, start by making your code work on\nthat type without using generics at all. Adding polymorphism later will be\nstraightforward compared to removing abstraction that is found to be\nunnecessary.\n\nDo not use generics to invent domain-specific languages (DSLs). In particular,\nrefrain from introducing error-handling frameworks that might put a significant\nburden on readers. Instead prefer established [error handling](#errors)\npractices. For testing, be especially wary of introducing\n[assertion libraries](#assert) or frameworks that result in less useful\n[test failures](#useful-test-failures).\n\nIn general:\n\n*   [Write code, don't design types]. From a GopherCon talk by Robert Griesemer\n    and Ian Lance Taylor.\n*   If you have several types that share a useful unifying interface, consider\n    modeling the solution using that interface. Generics may not be needed.\n*   Otherwise, instead of relying on the `any` type and excessive\n    [type switching](https://tour.golang.org/methods/16), consider generics.\n\nSee also:\n\n*   [Using Generics in Go], talk by Ian Lance Taylor\n\n*   [Generics tutorial] on Go's webpage\n\n[Generics tutorial]: https://go.dev/doc/tutorial/generics\n[Type Parameters]: https://go.dev/design/43651-type-parameters\n[Using Generics in Go]: https://www.youtube.com/watch?v=nr8EpUO9jhw\n[Write code, don't design types]: https://www.youtube.com/watch?v=Pa_e9EeCdy8&t=1250s\n\n<a id=\"pass-values\"></a>\n\n### Pass values\n\n<a id=\"TOC-PassValues\"></a>\n\nDo not pass pointers as function arguments just to save a few bytes. If a\nfunction reads its argument `x` only as `*x` throughout, then the argument\nshouldn't be a pointer. Common instances of this include passing a pointer to a\nstring (`*string`) or a pointer to an interface value (`*io.Reader`). In both\ncases, the value itself is a fixed size and can be passed directly.\n\nThis advice does not apply to large structs, or even small structs that may\nincrease in size. In particular, protocol buffer messages should generally be\nhandled by pointer rather than by value. The pointer type satisfies the\n`proto.Message` interface (accepted by `proto.Marshal`, `protocmp.Transform`,\netc.), and protocol buffer messages can be quite large and often grow larger\nover time.\n\n<a id=\"receiver-type\"></a>\n\n### Receiver type\n\n<a id=\"TOC-ReceiverType\"></a>\n\nA [method receiver] can be passed either as a value or a pointer, just as if it\nwere a regular function parameter. The choice between the two is based on which\n[method set(s)] the method should be a part of.\n\n[method receiver]: https://golang.org/ref/spec#Method_declarations\n[method set(s)]: https://golang.org/ref/spec#Method_sets\n\n**Correctness wins over speed or simplicity.** There are cases where you must\nuse a pointer value. In other cases, pick pointers for large types or as\nfuture-proofing if you don't have a good sense of how the code will grow, and\nuse values for simple [plain old data].\n\nThe list below spells out each case in further detail:\n\n*   If the receiver is a slice and the method doesn't reslice or reallocate the\n    slice, use a value rather than a pointer.\n\n    ```go\n    // Good:\n    type Buffer []byte\n\n    func (b Buffer) Len() int { return len(b) }\n    ```\n\n*   If the method needs to mutate the receiver, the receiver must be a pointer.\n\n    ```go\n    // Good:\n    type Counter int\n\n    func (c *Counter) Inc() { *c++ }\n\n    // See https://pkg.go.dev/container/heap.\n    type Queue []Item\n\n    func (q *Queue) Push(x Item) { *q = append([]Item{x}, *q...) }\n    ```\n\n*   If the receiver is a struct containing fields that\n    [cannot safely be copied](#copying), use a pointer receiver. Common examples\n    are [`sync.Mutex`] and other synchronization types.\n\n    ```go\n    // Good:\n    type Counter struct {\n        mu    sync.Mutex\n        total int\n    }\n\n    func (c *Counter) Inc() {\n        c.mu.Lock()\n        defer c.mu.Unlock()\n        c.total++\n    }\n    ```\n\n    **Tip:** Check the type's [Godoc] for information about whether it is safe\n    or unsafe to copy.\n\n*   If the receiver is a \"large\" struct or array, a pointer receiver may be more\n    efficient. Passing a struct is equivalent to passing all of its fields or\n    elements as arguments to the method. If that seems too large to\n    [pass by value](#pass-values), a pointer is a good choice.\n\n*   For methods that will call or run concurrently with other functions that\n    modify the receiver, use a value if those modifications should not be\n    visible to your method; otherwise use a pointer.\n\n*   If the receiver is a struct or array, any of whose elements is a pointer to\n    something that may be mutated, prefer a pointer receiver to make the\n    intention of mutability clear to the reader.\n\n    ```go\n    // Good:\n    type Counter struct {\n        m *Metric\n    }\n\n    func (c *Counter) Inc() {\n        c.m.Add(1)\n    }\n    ```\n\n*   If the receiver is a [built-in type], such as an integer or a string, that\n    does not need to be modified, use a value.\n\n    ```go\n    // Good:\n    type User string\n\n    func (u User) String() { return string(u) }\n    ```\n\n*   If the receiver is a map, function, or channel, use a value rather than a\n    pointer.\n\n    ```go\n    // Good:\n    // See https://pkg.go.dev/net/http#Header.\n    type Header map[string][]string\n\n    func (h Header) Add(key, value string) { /* omitted */ }\n    ```\n\n*   If the receiver is a \"small\" array or struct that is naturally a value type\n    with no mutable fields and no pointers, a value receiver is usually the\n    right choice.\n\n    ```go\n    // Good:\n    // See https://pkg.go.dev/time#Time.\n    type Time struct { /* omitted */ }\n\n    func (t Time) Add(d Duration) Time { /* omitted */ }\n    ```\n\n*   When in doubt, use a pointer receiver.\n\nAs a general guideline, prefer to make the methods for a type either all pointer\nmethods or all value methods.\n\n**Note:** There is a lot of misinformation about whether passing a value or a\npointer to a function can affect performance. The compiler can choose to pass\npointers to values on the stack as well as copying values on the stack, but\nthese considerations should not outweigh the readability and correctness of the\ncode in most circumstances. When the performance does matter, it is important to\nprofile both approaches with a realistic benchmark before deciding that one\napproach outperforms the other.\n\n[plain old data]: https://en.wikipedia.org/wiki/Passive_data_structure\n[`sync.Mutex`]: https://pkg.go.dev/sync#Mutex\n[built-in type]: https://pkg.go.dev/builtin\n\n<a id=\"switch-break\"></a>\n\n### `switch` and `break`\n\n<a id=\"TOC-SwitchBreak\"></a>\n\nDo not use `break` statements without target labels at the ends of `switch`\nclauses; they are redundant. Unlike in C and Java, `switch` clauses in Go\nautomatically break, and a `fallthrough` statement is needed to achieve the\nC-style behavior. Use a comment rather than `break` if you want to clarify the\npurpose of an empty clause.\n\n```go\n// Good:\nswitch x {\ncase \"A\", \"B\":\n    buf.WriteString(x)\ncase \"C\":\n    // handled outside of the switch statement\ndefault:\n    return fmt.Errorf(\"unknown value: %q\", x)\n}\n```\n\n```go\n// Bad:\nswitch x {\ncase \"A\", \"B\":\n    buf.WriteString(x)\n    break // this break is redundant\ncase \"C\":\n    break // this break is redundant\ndefault:\n    return fmt.Errorf(\"unknown value: %q\", x)\n}\n```\n\n> **Note:** If a `switch` clause is within a `for` loop, using `break` within\n> `switch` does not exit the enclosing `for` loop.\n>\n> ```go\n> for {\n>   switch x {\n>   case \"A\":\n>      break // exits the switch, not the loop\n>   }\n> }\n> ```\n>\n> To escape the enclosing loop, use a label on the `for` statement:\n>\n> ```go\n> loop:\n>   for {\n>     switch x {\n>     case \"A\":\n>        break loop // exits the loop\n>     }\n>   }\n> ```\n\n<a id=\"synchronous-functions\"></a>\n\n### Synchronous functions\n\n<a id=\"TOC-SynchronousFunctions\"></a>\n\nSynchronous functions return their results directly and finish any callbacks or\nchannel operations before returning. Prefer synchronous functions over\nasynchronous functions.\n\nSynchronous functions keep goroutines localized within a call. This helps to\nreason about their lifetimes, and avoid leaks and data races. Synchronous\nfunctions are also easier to test, since the caller can pass an input and check\nthe output without the need for polling or synchronization.\n\nIf necessary, the caller can add concurrency by calling the function in a\nseparate goroutine. However, it is quite difficult (sometimes impossible) to\nremove unnecessary concurrency at the caller side.\n\nSee also:\n\n*   \"Rethinking Classical Concurrency Patterns\", talk by Bryan Mills:\n    [slides][rethinking-slides], [video][rethinking-video]\n\n<a id=\"type-aliases\"></a>\n\n### Type aliases\n\n<a id=\"TOC-TypeAliases\"></a>\n\nUse a *type definition*, `type T1 T2`, to define a new type. Use a\n[*type alias*], `type T1 = T2`, to refer to an existing type without defining a\nnew type. Type aliases are rare; their primary use is to aid migrating packages\nto new source code locations. Don't use type aliasing when it is not needed.\n\n[*type alias*]: http://golang.org/ref/spec#Type_declarations\n\n<a id=\"use-percent-q\"></a>\n\n### Use %q\n\n<a id=\"TOC-UsePercentQ\"></a>\n\nGo's format functions (`fmt.Printf` etc.) have a `%q` verb which prints strings\ninside double-quotation marks.\n\n```go\n// Good:\nfmt.Printf(\"value %q looks like English text\", someText)\n```\n\nPrefer using `%q` over doing the equivalent manually, using `%s`:\n\n```go\n// Bad:\nfmt.Printf(\"value \\\"%s\\\" looks like English text\", someText)\n// Avoid manually wrapping strings with single-quotes too:\nfmt.Printf(\"value '%s' looks like English text\", someText)\n```\n\nUsing `%q` is recommended in output intended for humans where the input value\ncould possibly be empty or contain control characters. It can be very hard to\nnotice a silent empty string, but `\"\"` stands out clearly as such.\n\n<a id=\"use-any\"></a>\n\n### Use any\n\nGo 1.18 introduces an `any` type as an [alias] to `interface{}`. Because it is\nan alias, `any` is equivalent to `interface{}` in many situations and in others\nit is easily interchangeable via an explicit conversion. Prefer to use `any` in\nnew code.\n\n[alias]: https://go.googlesource.com/proposal/+/master/design/18130-type-alias.md\n\n## Common libraries\n\n<a id=\"flags\"></a>\n\n### Flags\n\n<a id=\"TOC-Flags\"></a>\n\nGo programs in the Google codebase use an internal variant of the\n[standard `flag` package]. It has a similar interface but interoperates well\nwith internal Google systems. Flag names in Go binaries should prefer to use\nunderscores to separate words, though the variables that hold a flag's value\nshould follow the standard Go name style ([mixed caps]). Specifically, the flag\nname should be in snake case, and the variable name should be the equivalent\nname in camel case.\n\n```go\n// Good:\nvar (\n    pollInterval = flag.Duration(\"poll_interval\", time.Minute, \"Interval to use for polling.\")\n)\n```\n\n```go\n// Bad:\nvar (\n    poll_interval = flag.Int(\"pollIntervalSeconds\", 60, \"Interval to use for polling in seconds.\")\n)\n```\n\nFlags must only be defined in `package main` or equivalent.\n\nGeneral-purpose packages should be configured using Go APIs, not by punching\nthrough to the command-line interface; don't let importing a library export new\nflags as a side effect. That is, prefer explicit function arguments or struct\nfield assignment or much less frequently and under the strictest of scrutiny\nexported global variables. In the extremely rare case that it is necessary to\nbreak this rule, the flag name must clearly indicate the package that it\nconfigures.\n\nIf your flags are global variables, place them in their own `var` group,\nfollowing the imports section.\n\nThere is additional discussion around best practices for creating [complex CLIs]\nwith subcommands.\n\nSee also:\n\n*   [Tip of the Week #45: Avoid Flags, Especially in Library Code][totw-45]\n*   [Go Tip #10: Configuration Structs and Flags](https://google.github.io/styleguide/go/index.html#gotip)\n*   [Go Tip #80: Dependency Injection Principles](https://google.github.io/styleguide/go/index.html#gotip)\n\n[standard `flag` package]: https://golang.org/pkg/flag/\n[mixed caps]: guide#mixed-caps\n[complex CLIs]: best-practices#complex-clis\n[totw-45]: https://abseil.io/tips/45\n\n<a id=\"logging\"></a>\n\n### Logging\n\nGo programs in the Google codebase use a variant of the standard [`log`]\npackage. It has a similar but more powerful interface and interoperates well\nwith internal Google systems. An open source version of this library is\navailable as [package `glog`], and open source Google projects may use that, but\nthis guide refers to it as `log` throughout.\n\n**Note:** For abnormal program exits, this library uses `log.Fatal` to abort\nwith a stacktrace, and `log.Exit` to stop without one. There is no `log.Panic`\nfunction as in the standard library.\n\n**Tip:** `log.Info(v)` is equivalent `log.Infof(\"%v\", v)`, and the same goes for\nother logging levels. Prefer the non-formatting version when you have no\nformatting to do.\n\nSee also:\n\n*   Best practices on [logging errors](best-practices#error-logging) and\n    [custom verbosity levels](best-practices#vlog)\n*   When and how to use the log package to\n    [stop the program](best-practices#checks-and-panics)\n\n[`log`]: https://pkg.go.dev/log\n[`log/slog`]: https://pkg.go.dev/log/slog\n[package `glog`]: https://pkg.go.dev/github.com/golang/glog\n[`log.Exit`]: https://pkg.go.dev/github.com/golang/glog#Exit\n[`log.Fatal`]: https://pkg.go.dev/github.com/golang/glog#Fatal\n\n<a id=\"contexts\"></a>\n\n### Contexts\n\n<a id=\"TOC-Contexts\"></a>\n\nValues of the [`context.Context`] type carry security credentials, tracing\ninformation, deadlines, and cancellation signals across API and process\nboundaries. Unlike C++ and Java, which in the Google codebase use thread-local\nstorage, Go programs pass contexts explicitly along the entire function call\nchain from incoming RPCs and HTTP requests to outgoing requests.\n\n[`context.Context`]: https://pkg.go.dev/context\n\nWhen passed to a function or method, [`context.Context`] is always the first\nparameter.\n\n```go\nfunc F(ctx context.Context /* other arguments */) {}\n```\n\nExceptions are:\n\n*   In an HTTP handler, where the context comes from\n    [`req.Context()`](https://pkg.go.dev/net/http#Request.Context).\n*   In streaming RPC methods, where the context comes from the stream.\n\n    Code using gRPC streaming accesses a context from a `Context()` method in\n    the generated server type, which implements `grpc.ServerStream`. See\n    [gRPC Generated Code documentation](https://grpc.io/docs/languages/go/generated-code/).\n\n*   In test functions (e.g. `TestXXX`, `BenchmarkXXX`, `FuzzXXX`), where the\n    context comes from\n    [`(testing.TB).Context()`](https://pkg.go.dev/testing#TB.Context).\n\n*   In other entrypoint functions (see below for examples of such functions),\n    use [`context.Background()`].\n\n    *   In binary targets: `main`\n    *   In general purpose code and libraries: `init`\n\n> **Note**: It is very rare for code in the middle of a callchain to require\n> creating a base context of its own using [`context.Background()`]. Always\n> prefer taking a context from your caller, unless it's the wrong context.\n>\n> You may come across server libraries (the implementation of Stubby, gRPC, or\n> HTTP in Google's server framework for Go) that construct a fresh context\n> object per request. These contexts are immediately filled with information\n> from the incoming request, so that when passed to the request handler, the\n> context's attached values have been propagated to it across the network\n> boundary from the client caller. Moreover, these contexts' lifetimes are\n> scoped to that of the request: when the request is finished, the context is\n> cancelled.\n>\n> Unless you are implementing a server framework, you shouldn't create contexts\n> with [`context.Background()`] in library code. Instead, prefer using context\n> detachment, which is mentioned below, if there is an existing context\n> available. If you think you do need [`context.Background()`] outside of\n> entrypoint functions, discuss it with the Google Go style mailing list before\n> committing to an implementation.\n\nThe convention that [`context.Context`] comes first in functions also applies to\ntest helpers.\n\n```go\n// Good:\nfunc readTestFile(ctx context.Context, t *testing.T, path string) string {}\n```\n\nDo not add a context member to a struct type. Instead, add a context parameter\nto each method on the type that needs to pass it along. The one exception is for\nmethods whose signature must match an interface in the standard library or in a\nthird party library outside Google's control. Such cases are very rare, and\nshould be discussed with the Google Go style mailing list before implementation\nand readability review.\n\n**Note:** Go 1.24 added a [`(testing.TB).Context()`] method. In tests, prefer\nusing [`(testing.TB).Context()`] over [`context.Background()`] to provide the\ninitial [`context.Context`] used by the test. Helper functions, environment or\ntest double setup, and other functions called from the test function body that\nrequire a context should have one explicitly passed.\n\n[`(testing.TB).Context()`]: https://pkg.go.dev/testing#TB.Context\n\nCode in the Google codebase that must spawn background operations which can run\nafter the parent context has been cancelled can use an internal package for\ndetachment. Follow [issue #40221](https://github.com/golang/go/issues/40221) for\ndiscussions on an open source alternative.\n\nSince contexts are immutable, it is fine to pass the same context to multiple\ncalls that share the same deadline, cancellation signal, credentials, parent\ntrace, and so on.\n\nSee also:\n\n*   [Contexts and structs]\n\n[`context.Background()`]: https://pkg.go.dev/context/#Background\n[Contexts and structs]: https://go.dev/blog/context-and-structs\n\n<a id=\"custom-contexts\"></a>\n\n#### Custom contexts\n\nDo not create custom context types or use interfaces other than\n[`context.Context`] in function signatures. There are no exceptions to this\nrule.\n\nImagine if every team had a custom context. Every function call from package `p`\nto package `q` would have to determine how to convert a `p.Context` to a\n`q.Context`, for all pairs of packages `p` and `q`. This is impractical and\nerror-prone for humans, and it makes automated refactorings that add context\nparameters nearly impossible.\n\nIf you have application data to pass around, put it in a parameter, in the\nreceiver, in globals, or in a `Context` value if it truly belongs there.\nCreating your own context type is not acceptable since it undermines the ability\nof the Go team to make Go programs work properly in production.\n\n<a id=\"crypto-rand\"></a>\n\n### crypto/rand\n\n<a id=\"TOC-CryptoRand\"></a>\n\nDo not use package `math/rand` to generate keys, even throwaway ones. If\nunseeded, the generator is completely predictable. Seeded with\n`time.Nanoseconds()`, there are just a few bits of entropy. Instead, use\n`crypto/rand`'s Reader, and if you need text, print to hexadecimal or base64.\n\n```go\n// Good:\nimport (\n    \"crypto/rand\"\n    // \"encoding/base64\"\n    // \"encoding/hex\"\n    \"fmt\"\n\n    // ...\n)\n\nfunc Key() string {\n    buf := make([]byte, 16)\n    if _, err := rand.Read(buf); err != nil {\n        log.Fatalf(\"Out of randomness, should never happen: %v\", err)\n    }\n    return fmt.Sprintf(\"%x\", buf)\n    // or hex.EncodeToString(buf)\n    // or base64.StdEncoding.EncodeToString(buf)\n}\n```\n\n**Note:** `log.Fatalf` is not the standard library log. See [#logging].\n\n<a id=\"useful-test-failures\"></a>\n\n## Useful test failures\n\n<a id=\"TOC-UsefulTestFailures\"></a>\n\nIt should be possible to diagnose a test's failure without reading the test's\nsource. Tests should fail with helpful messages detailing:\n\n*   What caused the failure\n*   What inputs resulted in an error\n*   The actual result\n*   What was expected\n\nSpecific conventions for achieving this goal are outlined below.\n\n<a id=\"assert\"></a>\n\n### Assertion libraries\n\n<a id=\"TOC-Assert\"></a>\n\nDo not create \"assertion libraries\" as helpers for testing.\n\nAssertion libraries are libraries that attempt to combine the validation and\nproduction of failure messages within a test (though the same pitfalls can apply\nto other test helpers as well). For more on the distinction between test helpers\nand assertion libraries, see [best practices](best-practices#test-functions).\n\n```go\n// Bad:\nvar obj BlogPost\n\nassert.IsNotNil(t, \"obj\", obj)\nassert.StringEq(t, \"obj.Type\", obj.Type, \"blogPost\")\nassert.IntEq(t, \"obj.Comments\", obj.Comments, 2)\nassert.StringNotEq(t, \"obj.Body\", obj.Body, \"\")\n```\n\nAssertion libraries tend to either stop the test early (if `assert` calls\n`t.Fatalf` or `panic`) or omit relevant information about what the test got\nright:\n\n```go\n// Bad:\npackage assert\n\nfunc IsNotNil(t *testing.T, name string, val any) {\n    if val == nil {\n        t.Fatalf(\"Data %s = nil, want not nil\", name)\n    }\n}\n\nfunc StringEq(t *testing.T, name, got, want string) {\n    if got != want {\n        t.Fatalf(\"Data %s = %q, want %q\", name, got, want)\n    }\n}\n```\n\nComplex assertion functions often do not provide [useful failure messages] and\ncontext that exists within the test function. Too many assertion functions and\nlibraries lead to a fragmented developer experience: which assertion library\nshould I use, what style of output format should it emit, etc.? Fragmentation\nproduces unnecessary confusion, especially for library maintainers and authors\nof large-scale changes, who are responsible for fixing potential downstream\nbreakages. Instead of creating a domain-specific language for testing, use Go\nitself.\n\nAssertion libraries often factor out comparisons and equality checks. Prefer\nusing standard libraries such as [`cmp`] and [`fmt`] instead:\n\n```go\n// Good:\nvar got BlogPost\n\nwant := BlogPost{\n    Comments: 2,\n    Body:     \"Hello, world!\",\n}\n\nif !cmp.Equal(got, want) {\n    t.Errorf(\"Blog post = %v, want = %v\", got, want)\n}\n```\n\nFor more domain-specific comparison helpers, prefer returning a value or an\nerror that can be used in the test's failure message instead of passing\n`*testing.T` and calling its error reporting methods:\n\n```go\n// Good:\nfunc postLength(p BlogPost) int { return len(p.Body) }\n\nfunc TestBlogPost_VeritableRant(t *testing.T) {\n    post := BlogPost{Body: \"I am Gunnery Sergeant Hartman, your senior drill instructor.\"}\n\n    if got, want := postLength(post), 60; got != want {\n        t.Errorf(\"Length of post = %v, want %v\", got, want)\n    }\n}\n```\n\n**Best Practice:** Were `postLength` non-trivial, it would make sense to test it\ndirectly, independently of any tests that use it.\n\nSee also:\n\n*   [Equality comparison and diffs](#types-of-equality)\n*   [Print diffs](#print-diffs)\n*   For more on the distinction between test helpers and assertion helpers, see\n    [best practices](best-practices#test-functions)\n*   [Go FAQ] section on [testing frameworks] and their opinionated absence\n\n[useful failure messages]: #useful-test-failures\n[`fmt`]: https://golang.org/pkg/fmt/\n[marking test helpers]: #mark-test-helpers\n[Go FAQ]: https://go.dev/doc/faq\n[testing frameworks]: https://go.dev/doc/faq#testing_framework\n\n<a id=\"identify-the-function\"></a>\n\n### Identify the function\n\nIn most tests, failure messages should include the name of the function that\nfailed, even though it seems obvious from the name of the test function.\nSpecifically, your failure message should be `YourFunc(%v) = %v, want %v`\ninstead of just `got %v, want %v`.\n\n<a id=\"identify-the-input\"></a>\n\n### Identify the input\n\nIn most tests, failure messages should include the function inputs if they are\nshort. If the relevant properties of the inputs are not obvious (for example,\nbecause the inputs are large or opaque), you should name your test cases with a\ndescription of what's being tested and print the description as part of your\nerror message.\n\n<a id=\"got-before-want\"></a>\n\n### Got before want\n\nTest outputs should include the actual value that the function returned before\nprinting the value that was expected. A standard format for printing test\noutputs is `YourFunc(%v) = %v, want %v`. Where you would write \"actual\" and\n\"expected\", prefer using the words \"got\" and \"want\", respectively.\n\nFor diffs, directionality is less apparent, and as such it is important to\ninclude a key to aid in interpreting the failure. See the\n[section on printing diffs]. Whichever diff order you use in your failure\nmessages, you should explicitly indicate it as a part of the failure message,\nbecause existing code is inconsistent about the ordering.\n\n[section on printing diffs]: #print-diffs\n\n<a id=\"compare-full-structures\"></a>\n\n### Full structure comparisons\n\nIf your function returns a struct (or any data type with multiple fields such as\nslices, arrays, and maps), avoid writing test code that performs a hand-coded\nfield-by-field comparison of the struct. Instead, construct the data that you're\nexpecting your function to return, and compare directly using a\n[deep comparison].\n\n**Note:** This does not apply if your data contains irrelevant fields that\nobscure the intention of the test.\n\nIf your struct needs to be compared for approximate (or equivalent kind of\nsemantic) equality or it contains fields that cannot be compared for equality\n(e.g., if one of the fields is an `io.Reader`), tweaking a [`cmp.Diff`] or\n[`cmp.Equal`] comparison with [`cmpopts`] options such as\n[`cmpopts.IgnoreInterfaces`] may meet your needs\n([example](https://play.golang.org/p/vrCUNVfxsvF)).\n\nIf your function returns multiple return values, you don't need to wrap those in\na struct before comparing them. Just compare the return values individually and\nprint them.\n\n```go\n// Good:\nval, multi, tail, err := strconv.UnquoteChar(`\\\"Fran & Freddie's Diner\\\"`, '\"')\nif err != nil {\n  t.Fatalf(...)\n}\nif val != `\"` {\n  t.Errorf(...)\n}\nif multi {\n  t.Errorf(...)\n}\nif tail != `Fran & Freddie's Diner\"` {\n  t.Errorf(...)\n}\n```\n\n[deep comparison]: #types-of-equality\n[`cmpopts`]: https://pkg.go.dev/github.com/google/go-cmp/cmp/cmpopts\n[`cmpopts.IgnoreInterfaces`]: https://pkg.go.dev/github.com/google/go-cmp/cmp/cmpopts#IgnoreInterfaces\n\n<a id=\"compare-stable-results\"></a>\n\n### Compare stable results\n\nAvoid comparing results that may depend on output stability of a package that\nyou do not own. Instead, the test should compare on semantically relevant\ninformation that is stable and resistant to changes in dependencies. For\nfunctionality that returns a formatted string or serialized bytes, it is\ngenerally not safe to assume that the output is stable.\n\nFor example, [`json.Marshal`] can change (and has changed in the past) the\nspecific bytes that it emits. Tests that perform string equality on the JSON\nstring may break if the `json` package changes how it serializes the bytes.\nInstead, a more robust test would parse the contents of the JSON string and\nensure that it is semantically equivalent to some expected data structure.\n\n[`json.Marshal`]: https://golang.org/pkg/encoding/json/#Marshal\n\n<a id=\"keep-going\"></a>\n\n### Keep going\n\nTests should keep going for as long as possible, even after a failure, in order\nto print out all of the failed checks in a single run. This way, a developer who\nis fixing the failing test doesn't have to re-run the test after fixing each bug\nto find the next bug.\n\nPrefer calling `t.Error` over `t.Fatal` for reporting a mismatch. When comparing\nseveral different properties of a function's output, use `t.Error` for each of\nthose comparisons.\n\n```go\n// Good:\ngotMean, gotVariance, err := MyDistribution(input)\nif err != nil {\n  t.Fatalf(\"MyDistribution(%v) returned unexpected error: %v\", input, err)\n}\nif diff := cmp.Diff(wantMean, gotMean); diff != \"\" {\n  t.Errorf(\"MyDistribution(%v) returned unexpected difference in mean value (-want +got):\\n%s\", input, diff)\n}\nif diff := cmp.Diff(wantVariance, gotVariance); diff != \"\" {\n  t.Errorf(\"MyDistribution(%v) returned unexpected difference in variance value (-want +got):\\n%s\", input, diff)\n}\n```\n\nCalling `t.Fatal` is primarily useful for reporting an unexpected condition\n(such as an error or output mismatch) when subsequent failures would be\nmeaningless or even mislead the investigator. Note how the code below calls\n`t.Fatalf` and *then* `t.Errorf`:\n\n```go\n// Good:\ngotEncoded := Encode(input)\nif gotEncoded != wantEncoded {\n  t.Fatalf(\"Encode(%q) = %q, want %q\", input, gotEncoded, wantEncoded)\n  // It doesn't make sense to decode from unexpected encoded input.\n}\ngotDecoded, err := Decode(gotEncoded)\nif err != nil {\n  t.Fatalf(\"Decode(%q) returned unexpected error: %v\", gotEncoded, err)\n}\nif gotDecoded != input {\n  t.Errorf(\"Decode(%q) = %q, want %q\", gotEncoded, gotDecoded, input)\n}\n```\n\nFor table-driven test, consider using subtests and use `t.Fatal` rather than\n`t.Error` and `continue`. See also\n[GoTip #25: Subtests: Making Your Tests Lean](https://google.github.io/styleguide/go/index.html#gotip).\n\n**Best practice:** For more discussion about when `t.Fatal` should be used, see\n[best practices](best-practices#t-fatal).\n\n<a id=\"types-of-equality\"></a>\n\n### Equality comparison and diffs\n\nThe `==` operator evaluates equality using [language-defined comparisons].\nScalar values (numbers, booleans, etc) are compared based on their values, but\nonly some structs and interfaces can be compared in this way. Pointers are\ncompared based on whether they point to the same variable, rather than based on\nthe equality of the values to which they point.\n\nThe [`cmp`] package can compare more complex data structures not appropriately\nhandled by `==`, such as slices. Use [`cmp.Equal`] for equality comparison and\n[`cmp.Diff`] to obtain a human-readable diff between objects.\n\n```go\n// Good:\nwant := &Doc{\n    Type:     \"blogPost\",\n    Comments: 2,\n    Body:     \"This is the post body.\",\n    Authors:  []string{\"isaac\", \"albert\", \"emmy\"},\n}\nif !cmp.Equal(got, want) {\n    t.Errorf(\"AddPost() = %+v, want %+v\", got, want)\n}\n```\n\nAs a general-purpose comparison library, `cmp` may not know how to compare\ncertain types. For example, it can only compare protocol buffer messages if\npassed the [`protocmp.Transform`] option.\n\n<!-- The order of want and got here is deliberate. See comment in #print-diffs. -->\n\n```go\n// Good:\nif diff := cmp.Diff(want, got, protocmp.Transform()); diff != \"\" {\n    t.Errorf(\"Foo() returned unexpected difference in protobuf messages (-want +got):\\n%s\", diff)\n}\n```\n\nAlthough the `cmp` package is not part of the Go standard library, it is\nmaintained by the Go team and should produce stable equality results over time.\nIt is user-configurable and should serve most comparison needs.\n\n[language-defined comparisons]: http://golang.org/ref/spec#Comparison_operators\n[`cmp`]: https://pkg.go.dev/github.com/google/go-cmp/cmp\n[`cmp.Equal`]: https://pkg.go.dev/github.com/google/go-cmp/cmp#Equal\n[`cmp.Diff`]: https://pkg.go.dev/github.com/google/go-cmp/cmp#Diff\n[`protocmp.Transform`]: https://pkg.go.dev/google.golang.org/protobuf/testing/protocmp#Transform\n\nExisting code may make use of the following older libraries, and may continue\nusing them for consistency:\n\n*   [`pretty`] produces aesthetically pleasing difference reports. However, it\n    quite deliberately considers values that have the same visual representation\n    as equal. In particular, `pretty` does not catch differences between nil\n    slices and empty ones, is not sensitive to different interface\n    implementations with identical fields, and it is possible to use a nested\n    map as the basis for comparison with a struct value. It also serializes the\n    entire value into a string before producing a diff, and as such is not a\n    good choice for comparing large values. By default, it compares unexported\n    fields, which makes it sensitive to changes in implementation details in\n    your dependencies. For this reason, it is not appropriate to use `pretty` on\n    protobuf messages.\n\n[`pretty`]: https://pkg.go.dev/github.com/kylelemons/godebug/pretty\n\nPrefer using `cmp` for new code, and it is worth considering updating older code\nto use `cmp` where and when it is practical to do so.\n\nOlder code may use the standard library `reflect.DeepEqual` function to compare\ncomplex structures. `reflect.DeepEqual` should not be used for checking\nequality, as it is sensitive to changes in unexported fields and other\nimplementation details. Code that is using `reflect.DeepEqual` should be updated\nto one of the above libraries.\n\n**Note:** The `cmp` package is designed for testing, rather than production use.\nAs such, it may panic when it suspects that a comparison is performed\nincorrectly to provide instruction to users on how to improve the test to be\nless brittle. Given cmp's propensity towards panicking, it makes it unsuitable\nfor code that is used in production as a spurious panic may be fatal.\n\n<a id=\"level-of-detail\"></a>\n\n### Level of detail\n\nThe conventional failure message, which is suitable for most Go tests, is\n`YourFunc(%v) = %v, want %v`. However, there are cases that may call for more or\nless detail:\n\n*   Tests performing complex interactions should describe the interactions too.\n    For example, if the same `YourFunc` is called several times, identify which\n    call failed the test. If it's important to know any extra state of the\n    system, include that in the failure output (or at least in the logs).\n*   If the data is a complex struct with significant boilerplate, it is\n    acceptable to describe only the important parts in the message, but do not\n    overly obscure the data.\n*   Setup failures do not require the same level of detail. If a test helper\n    populates a Spanner table but Spanner was down, you probably don't need to\n    include which test input you were going to store in the database.\n    `t.Fatalf(\"Setup: Failed to set up test database: %s\", err)` is usually\n    helpful enough to resolve the issue.\n\n**Tip:** Make your failure mode trigger during development. Review what the\nfailure message looks like and whether a maintainer can effectively deal with\nthe failure.\n\nThere are some techniques for reproducing test inputs and outputs clearly:\n\n*   When printing string data, [`%q` is often useful](#use-percent-q) to\n    emphasize that the value is important and to more easily spot bad values.\n*   When printing (small) structs, `%+v` can be more useful than `%v`.\n*   When validation of larger values fails, [printing a diff](#print-diffs) can\n    make it easier to understand the failure.\n\n<a id=\"print-diffs\"></a>\n\n### Print diffs\n\nIf your function returns large output then it can be hard for someone reading\nthe failure message to find the differences when your test fails. Instead of\nprinting both the returned value and the wanted value, make a diff.\n\nTo compute diffs for such values, `cmp.Diff` is preferred, particularly for new\ntests and new code, but other tools may be used. See [types of equality] for\nguidance regarding the strengths and weaknesses of each function.\n\n*   [`cmp.Diff`]\n\n*   [`pretty.Compare`]\n\nYou can use the [`diff`] package to compare multi-line strings or lists of\nstrings. You can use this as a building block for other kinds of diffs.\n\n[types of equality]: #types-of-equality\n[`diff`]: https://pkg.go.dev/github.com/kylelemons/godebug/diff\n[`pretty.Compare`]: https://pkg.go.dev/github.com/kylelemons/godebug/pretty#Compare\n\nAdd some text to your failure message explaining the direction of the diff.\n\n<!--\nThe reversed order of want and got in these examples is intentional, as this is\nthe prevailing order across the Google codebase. The lack of a stance on which\norder to use is also intentional, as there is no consensus which is\n\"most readable.\"\n\n\n-->\n\n*   Something like `diff (-want +got)` is good when you're using the `cmp`,\n    `pretty`, and `diff` packages (if you pass `(want, got)` to the function),\n    because the `-` and `+` that you add to your format string will match the\n    `-` and `+` that actually appear at the beginning of the diff lines. If you\n    pass `(got, want)` to your function, the correct key would be `(-got +want)`\n    instead.\n\n*   The `messagediff` package uses a different output format, so the message\n    `diff (want -> got)` is appropriate when you're using it (if you pass\n    `(want, got)` to the function), because the direction of the arrow will\n    match the direction of the arrow in the \"modified\" lines.\n\nThe diff will span multiple lines, so you should print a newline before you\nprint the diff.\n\n<a id=\"test-error-semantics\"></a>\n\n### Test error semantics\n\nWhen a unit test performs string comparisons or uses a vanilla `cmp` to check\nthat particular kinds of errors are returned for particular inputs, you may find\nthat your tests are brittle if any of those error messages are reworded in the\nfuture. Since this has the potential to turn your unit test into a change\ndetector (see [TotT: Change-Detector Tests Considered Harmful][tott-350] ),\ndon't use string comparison to check what type of error your function returns.\nHowever, it is permissible to use string comparisons to check that error\nmessages coming from the package under test satisfy certain properties, for\nexample, that it includes the parameter name.\n\nError values in Go typically have a component intended for human eyes and a\ncomponent intended for semantic control flow. Tests should seek to only test\nsemantic information that can be reliably observed, rather than display\ninformation that is intended for human debugging, as this is often subject to\nfuture changes. For guidance on constructing errors with semantic meaning see\n[best-practices regarding errors](best-practices#error-handling). If an error\nwith insufficient semantic information is coming from a dependency outside your\ncontrol, consider filing a bug against the owner to help improve the API, rather\nthan relying on parsing the error message.\n\nWithin unit tests, it is common to only care whether an error occurred or not.\nIf so, then it is sufficient to only test whether the error was non-nil when you\nexpected an error. If you would like to test that the error semantically matches\nsome other error, then consider using [`errors.Is`] or `cmp` with\n[`cmpopts.EquateErrors`].\n\n> **Note:** If a test uses [`cmpopts.EquateErrors`] but all of its `wantErr`\n> values are either `nil` or `cmpopts.AnyError`, then using `cmp` is\n> [unnecessary mechanism](guide#least-mechanism). Simplify the code by making\n> the want field a `bool`. You can then use a simple comparison with `!=`.\n>\n> ```go\n> // Good:\n> err := f(test.input)\n> if gotErr := err != nil; gotErr != test.wantErr {\n>     t.Errorf(\"f(%q) = %v, want error presence = %v\", test.input, err, test.wantErr)\n> }\n> ```\n\nSee also\n[GoTip #13: Designing Errors for Checking](https://google.github.io/styleguide/go/index.html#gotip).\n\n[tott-350]: https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html\n[`cmpopts.EquateErrors`]: https://pkg.go.dev/github.com/google/go-cmp/cmp/cmpopts#EquateErrors\n[`errors.Is`]: https://pkg.go.dev/errors#Is\n\n<a id=\"test-structure\"></a>\n\n## Test structure\n\n<a id=\"subtests\"></a>\n\n### Subtests\n\nThe standard Go testing library offers a facility to [define subtests]. This\nallows flexibility in setup and cleanup, controlling parallelism, and test\nfiltering. Subtests can be useful (particularly for table-driven tests), but\nusing them is not mandatory. See also the\n[Go blog post about subtests](https://blog.golang.org/subtests).\n\nSubtests should not depend on the execution of other cases for success or\ninitial state, because subtests are expected to be able to be run individually\nwith using `go test -run` flags or with Bazel [test filter] expressions.\n\n[define subtests]: https://pkg.go.dev/testing#hdr-Subtests_and_Sub_benchmarks\n[test filter]: https://bazel.build/docs/user-manual#test-filter\n\n<a id=\"subtest-names\"></a>\n\n#### Subtest names\n\nName your subtest such that it is readable in test output and useful on the\ncommand line for users of test filtering. When you use `t.Run` to create a\nsubtest, the first argument is used as a descriptive name for the test. To\nensure that test results are legible to humans reading the logs, choose subtest\nnames that will remain useful and readable after escaping. Think of subtest\nnames more like a function identifier than a prose description.\n\nThe test runner replaces spaces with underscores, and escapes non-printing\ncharacters. To ensure accurate correlation between test logs and source code, it\nis recommended to avoid using these characters in subtest names.\n\nIf your test data benefits from a longer description, consider putting the\ndescription in a separate field (perhaps to be printed using `t.Log` or\nalongside failure messages).\n\nSubtests may be run individually using flags to the [Go test runner] or Bazel\n[test filter], so choose descriptive names that are also easy to type.\n\n> **Warning:** Slash characters are particularly unfriendly in subtest names,\n> since they have [special meaning for test filters].\n>\n> > ```sh\n> > # Bad:\n> > # Assuming TestTime and t.Run(\"America/New_York\", ...)\n> > bazel test :mytest --test_filter=\"Time/New_York\"    # Runs nothing!\n> > bazel test :mytest --test_filter=\"Time//New_York\"   # Correct, but awkward.\n> > ```\n\nTo [identify the inputs] of the function, include them in the test's failure\nmessages, where they won't be escaped by the test runner.\n\n```go\n// Good:\nfunc TestTranslate(t *testing.T) {\n    data := []struct {\n        name, desc, srcLang, dstLang, srcText, wantDstText string\n    }{\n        {\n            name:        \"hu=en_bug-1234\",\n            desc:        \"regression test following bug 1234. contact: cleese\",\n            srcLang:     \"hu\",\n            srcText:     \"cigarettát és egy öngyújtót kérek\",\n            dstLang:     \"en\",\n            wantDstText: \"cigarettes and a lighter please\",\n        }, // ...\n    }\n    for _, d := range data {\n        t.Run(d.name, func(t *testing.T) {\n            got := Translate(d.srcLang, d.dstLang, d.srcText)\n            if got != d.wantDstText {\n                t.Errorf(\"%s\\nTranslate(%q, %q, %q) = %q, want %q\",\n                    d.desc, d.srcLang, d.dstLang, d.srcText, got, d.wantDstText)\n            }\n        })\n    }\n}\n```\n\nHere are a few examples of things to avoid:\n\n```go\n// Bad:\n// Too wordy.\nt.Run(\"check that there is no mention of scratched records or hovercrafts\", ...)\n// Slashes cause problems on the command line.\nt.Run(\"AM/PM confusion\", ...)\n```\n\nSee also\n[Go Tip #117: Subtest Names](https://google.github.io/styleguide/go/index.html#gotip).\n\n[Go test runner]: https://golang.org/cmd/go/#hdr-Testing_flags\n[identify the inputs]: #identify-the-input\n[special meaning for test filters]: https://blog.golang.org/subtests#:~:text=Perhaps%20a%20bit,match%20any%20tests\n\n<a id=\"table-driven-tests\"></a>\n\n### Table-driven tests\n\nUse table-driven tests when many different test cases can be tested using\nsimilar testing logic.\n\n*   When testing whether the actual output of a function is equal to the\n    expected output. For example, the many [tests of `fmt.Sprintf`] or the\n    minimal snippet below.\n*   When testing whether the outputs of a function always conform to the same\n    set of invariants. For example, [tests for `net.Dial`].\n\n[tests of `fmt.Sprintf`]: https://cs.opensource.google/go/go/+/master:src/fmt/fmt_test.go\n[tests for `net.Dial`]: https://cs.opensource.google/go/go/+/master:src/net/dial_test.go;l=318;drc=5b606a9d2b7649532fe25794fa6b99bd24e7697c\n\nHere is the minimal structure of a table-driven test. If needed, you may use\ndifferent names or add extra facilities such as subtests or setup and cleanup\nfunctions. Always keep [useful test failures](#useful-test-failures) in mind.\n\n```go\n// Good:\nfunc TestCompare(t *testing.T) {\n    compareTests := []struct {\n        a, b string\n        want int\n    }{\n        {\"\", \"\", 0},\n        {\"a\", \"\", 1},\n        {\"\", \"a\", -1},\n        {\"abc\", \"abc\", 0},\n        {\"ab\", \"abc\", -1},\n        {\"abc\", \"ab\", 1},\n        {\"x\", \"ab\", 1},\n        {\"ab\", \"x\", -1},\n        {\"x\", \"a\", 1},\n        {\"b\", \"x\", -1},\n        // test runtime·memeq's chunked implementation\n        {\"abcdefgh\", \"abcdefgh\", 0},\n        {\"abcdefghi\", \"abcdefghi\", 0},\n        {\"abcdefghi\", \"abcdefghj\", -1},\n    }\n\n    for _, test := range compareTests {\n        got := Compare(test.a, test.b)\n        if got != test.want {\n            t.Errorf(\"Compare(%q, %q) = %v, want %v\", test.a, test.b, got, test.want)\n        }\n    }\n}\n```\n\n**Note**: The failure messages in this example above fulfill the guidance to\n[identify the function](#identify-the-function) and\n[identify the input](#identify-the-input). There's no need to\n[identify the row numerically](#table-tests-identifying-the-row).\n\nWhen some test cases need to be checked using different logic from other test\ncases, it is appropriate to write multiple test functions, as explained in\n[GoTip #50: Disjoint Table Tests].\n\nWhen the additional test cases are simple (e.g., basic error checking) and don't\nintroduce conditionalized code flow in the table test's loop body, it's\npermissible to include that case in the existing test, though be careful using\nlogic like this. What starts simple today can organically grow into something\nunmaintainable.\n\nFor example:\n\n```go\nfunc TestDivide(t *testing.T) {\n    tests := []struct {\n        dividend, divisor int\n        want              int\n        wantErr           bool\n    }{\n        {\n            dividend: 4,\n            divisor:  2,\n            want:     2,\n        },\n        {\n            dividend: 10,\n            divisor:  2,\n            want:     5,\n        },\n        {\n            dividend: 1,\n            divisor:  0,\n            wantErr:  true,\n        },\n    }\n\n    for _, test := range tests {\n        got, err := Divide(test.dividend, test.divisor)\n        if (err != nil) != test.wantErr {\n            t.Errorf(\"Divide(%d, %d) error = %v, want error presence = %t\", test.dividend, test.divisor, err, test.wantErr)\n        }\n\n        // In this example, we're only testing the value result when the tested function didn't fail.\n        if err != nil {\n            continue\n        }\n\n        if got != test.want {\n            t.Errorf(\"Divide(%d, %d) = %d, want %d\", test.dividend, test.divisor, got, test.want)\n        }\n    }\n}\n```\n\nMore complicated logic in your test code, like complex error checking based on\nconditional differences in test setup (often based on table test input\nparameters), can be [difficult to understand](guide#maintainability) when each\nentry in a table has specialized logic based on the inputs. If test cases have\ndifferent logic but identical setup, a sequence of [subtests](#subtests) within\na single test function might be more readable. A test helper may also be useful\nfor simplifying test setup in order to maintain the readability of a test body.\n\nYou can combine table-driven tests with multiple test functions. For example,\nwhen testing that a function's output exactly matches the expected output and\nthat the function returns a non-nil error for an invalid input, then writing two\nseparate table-driven test functions is the best approach: one for normal\nnon-error outputs, and one for error outputs.\n\n[GoTip #50: Disjoint Table Tests]: https://google.github.io/styleguide/go/index.html#gotip\n\n<a id=\"table-tests-data-driven\"></a>\n\n#### Data-driven test cases\n\nTable test rows can sometimes become complicated, with the row values dictating\nconditional behavior inside the test case. The extra clarity from the\nduplication between the test cases is necessary for readability.\n\n```go\n// Good:\ntype decodeCase struct {\n    name   string\n    input  string\n    output string\n    err    error\n}\n\nfunc TestDecode(t *testing.T) {\n    // setupCodex is slow as it creates a real Codex for the test.\n    codex := setupCodex(t)\n\n    var tests []decodeCase // rows omitted for brevity\n\n    for _, test := range tests {\n        t.Run(test.name, func(t *testing.T) {\n            output, err := Decode(test.input, codex)\n            if got, want := output, test.output; got != want {\n                t.Errorf(\"Decode(%q) = %v, want %v\", test.input, got, want)\n            }\n            if got, want := err, test.err; !cmp.Equal(got, want) {\n                t.Errorf(\"Decode(%q) err %q, want %q\", test.input, got, want)\n            }\n        })\n    }\n}\n\nfunc TestDecodeWithFake(t *testing.T) {\n    // A fakeCodex is a fast approximation of a real Codex.\n    codex := newFakeCodex()\n\n    var tests []decodeCase // rows omitted for brevity\n\n    for _, test := range tests {\n        t.Run(test.name, func(t *testing.T) {\n            output, err := Decode(test.input, codex)\n            if got, want := output, test.output; got != want {\n                t.Errorf(\"Decode(%q) = %v, want %v\", test.input, got, want)\n            }\n            if got, want := err, test.err; !cmp.Equal(got, want) {\n                t.Errorf(\"Decode(%q) err %q, want %q\", test.input, got, want)\n            }\n        })\n    }\n}\n```\n\nIn the counterexample below, note how hard it is to distinguish between which\ntype of `Codex` is used per test case in the case setup. (The highlighted parts\nrun afoul of the advice from [TotT: Data Driven Traps!][tott-97] .)\n\n```go\n// Bad:\ntype decodeCase struct {\n  name   string\n  input  string\n  codex  testCodex\n  output string\n  err    error\n}\n\ntype testCodex int\n\nconst (\n  fake testCodex = iota\n  prod\n)\n\nfunc TestDecode(t *testing.T) {\n  var tests []decodeCase // rows omitted for brevity\n\n  for _, test := tests {\n    t.Run(test.name, func(t *testing.T) {\n      var codex Codex\n      switch test.codex {\n      case fake:\n        codex = newFakeCodex()\n      case prod:\n        codex = setupCodex(t)\n      default:\n        t.Fatalf(\"Unknown codex type: %v\", codex)\n      }\n      output, err := Decode(test.input, codex)\n      if got, want := output, test.output; got != want {\n        t.Errorf(\"Decode(%q) = %q, want %q\", test.input, got, want)\n      }\n      if got, want := err, test.err; !cmp.Equal(got, want) {\n        t.Errorf(\"Decode(%q) err %q, want %q\", test.input, got, want)\n      }\n    })\n  }\n}\n```\n\n[tott-97]: https://testing.googleblog.com/2008/09/tott-data-driven-traps.html\n\n<a id=\"table-tests-identifying-the-row\"></a>\n\n#### Identifying the row\n\nDo not use the index of the test in the test table as a substitute for naming\nyour tests or printing the inputs. Nobody wants to go through your test table\nand count the entries in order to figure out which test case is failing.\n\n```go\n// Bad:\ntests := []struct {\n    input, want string\n}{\n    {\"hello\", \"HELLO\"},\n    {\"wORld\", \"WORLD\"},\n}\nfor i, d := range tests {\n    if strings.ToUpper(d.input) != d.want {\n        t.Errorf(\"Failed on case #%d\", i)\n    }\n}\n```\n\nAdd a test description to your test struct and print it along failure messages.\nWhen using subtests, your subtest name should be effective in identifying the\nrow.\n\n**Important:** Even though `t.Run` scopes the output and execution, you must\nalways [identify the input]. The table test row names must follow the\n[subtest naming] guidance.\n\n[identify the input]: #identify-the-input\n[subtest naming]: #subtest-names\n\n<a id=\"mark-test-helpers\"></a>\n\n### Test helpers\n\nA test helper is a function that performs a setup or cleanup task. All failures\nthat occur in test helpers are expected to be failures of the environment (not\nfrom the code under test) — for example when a test database cannot be started\nbecause there are no more free ports on this machine.\n\nIf you pass a `*testing.T`, call [`t.Helper`] to attribute failures in the test\nhelper to the line where the helper is called. This parameter should come after\na [context](#contexts) parameter, if present, and before any remaining\nparameters.\n\n```go\n// Good:\nfunc TestSomeFunction(t *testing.T) {\n    golden := readFile(t, \"testdata/golden-result.txt\")\n    // ... tests against golden ...\n}\n\n// readFile returns the contents of a data file.\n// It must only be called from the same goroutine as started the test.\nfunc readFile(t *testing.T, filename string) string {\n    t.Helper()\n    contents, err := runfiles.ReadFile(filename)\n    if err != nil {\n        t.Fatal(err)\n    }\n    return string(contents)\n}\n```\n\nDo not use this pattern when it obscures the connection between a test failure\nand the conditions that led to it. Specifically, the guidance about\n[assert libraries](#assert) still applies, and [`t.Helper`] should not be used\nto implement such libraries.\n\n**Tip:** For more on the distinction between test helpers and assertion helpers,\nsee [best practices](best-practices#test-functions).\n\nAlthough the above refers to `*testing.T`, much of the advice stays the same for\nbenchmark and fuzz helpers.\n\n[`t.Helper`]: https://pkg.go.dev/testing#T.Helper\n\n<a id=\"test-package\"></a>\n\n### Test package\n\n<a id=\"TOC-TestPackage\"></a>\n\n<a id=\"test-same-package\"></a>\n\n#### Tests in the same package\n\nTests may be defined in the same package as the code being tested.\n\nTo write a test in the same package:\n\n*   Place the tests in a `foo_test.go` file\n*   Use `package foo` for the test file\n*   Do not explicitly import the package to be tested\n\n```build\n# Good:\ngo_library(\n    name = \"foo\",\n    srcs = [\"foo.go\"],\n    deps = [\n        ...\n    ],\n)\n\ngo_test(\n    name = \"foo_test\",\n    size = \"small\",\n    srcs = [\"foo_test.go\"],\n    library = \":foo\",\n    deps = [\n        ...\n    ],\n)\n```\n\nA test in the same package can access unexported identifiers in the package.\nThis may enable better test coverage and more concise tests. Be aware that any\n[examples] declared in the test will not have the package names that a user will\nneed in their code.\n\n[`library`]: https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/rules.md#go_library\n[examples]: #examples\n\n<a id=\"test-different-package\"></a>\n\n#### Tests in a different package\n\nIt is not always appropriate or even possible to define a test in the same\npackage as the code being tested. In these cases, use a package name with the\n`_test` suffix. This is an exception to the \"no underscores\" rule to\n[package names](#package-names). For example:\n\n*   If an integration test does not have an obvious library that it belongs to\n\n    ```go\n    // Good:\n    package gmailintegration_test\n\n    import \"testing\"\n    ```\n\n*   If defining the tests in the same package results in circular dependencies\n\n    ```go\n    // Good:\n    package fireworks_test\n\n    import (\n      \"fireworks\"\n      \"fireworkstestutil\" // fireworkstestutil also imports fireworks\n    )\n    ```\n\n<a id=\"use-package-testing\"></a>\n\n### Use package `testing`\n\nThe Go standard library provides the [`testing` package]. This is the only\ntesting framework permitted for Go code in the Google codebase. In particular,\n[assertion libraries](#assert) and third-party testing frameworks are not\nallowed.\n\nThe `testing` package provides a minimal but complete set of functionality for\nwriting good tests:\n\n*   Top-level tests\n*   Benchmarks\n*   [Runnable examples](https://blog.golang.org/examples)\n*   Subtests\n*   Logging\n*   Failures and fatal failures\n\nThese are designed to work cohesively with core language features like\n[composite literal] and [if-with-initializer] syntax to enable test authors to\nwrite [clear, readable, and maintainable tests].\n\n[`testing` package]: https://pkg.go.dev/testing\n[composite literal]: https://go.dev/ref/spec#Composite_literals\n[if-with-initializer]: https://go.dev/ref/spec#If_statements\n\n<a id=\"non-decisions\"></a>\n\n## Non-decisions\n\nA style guide cannot enumerate positive prescriptions for all matters, nor can\nit enumerate all matters about which it does not offer an opinion. That said,\nhere are a few things where the readability community has previously debated and\nhas not achieved consensus about.\n\n*   **Local variable initialization with zero value**. `var i int` and `i := 0`\n    are equivalent. See also [initialization best practices].\n*   **Empty composite literal vs. `new` or `make`**. `&File{}` and `new(File)`\n    are equivalent. So are `map[string]bool{}` and `make(map[string]bool)`. See\n    also [composite declaration best practices].\n*   **got, want argument ordering in cmp.Diff calls**. Be locally consistent,\n    and [include a legend](#print-diffs) in your failure message.\n*   **`errors.New` vs `fmt.Errorf` on non-formatted strings**.\n    `errors.New(\"foo\")` and `fmt.Errorf(\"foo\")` may be used interchangeably.\n\nIf there are special circumstances where they come up again, the readability\nmentor might make an optional comment, but in general the author is free to pick\nthe style they prefer in the given situation.\n\nNaturally, if anything not covered by the style guide does need more discussion,\nauthors are welcome to ask -- either in the specific review, or on internal\nmessage boards.\n\n[composite declaration best practices]: https://google.github.io/styleguide/go/best-practices#vardeclcomposite\n[initialization best practices]: https://google.github.io/styleguide/go/best-practices#vardeclinitialization\n\n<!--\n\n-->\n\n{% endraw %}\n"
  },
  {
    "path": "go/guide.md",
    "content": "<!--* toc_depth: 3 *-->\n\n# Go Style Guide\n\nhttps://google.github.io/styleguide/go/guide\n\n[Overview](index) | [Guide](guide) | [Decisions](decisions) |\n[Best practices](best-practices)\n\n<!--\n\n-->\n\n{% raw %}\n\n**Note:** This is part of a series of documents that outline [Go Style](index)\nat Google. This document is **[normative](index#normative) and\n[canonical](index#canonical)**. See [the overview](index#about) for more\ninformation.\n\n<a id=\"principles\"></a>\n\n## Style principles\n\nThere are a few overarching principles that summarize how to think about writing\nreadable Go code. The following are attributes of readable code, in order of\nimportance:\n\n1.  **[Clarity]**: The code's purpose and rationale is clear to the reader.\n1.  **[Simplicity]**: The code accomplishes its goal in the simplest way\n    possible.\n1.  **[Concision]**: The code has a high signal-to-noise ratio.\n1.  **[Maintainability]**: The code is written such that it can be easily\n    maintained.\n1.  **[Consistency]**: The code is consistent with the broader Google codebase.\n\n[Clarity]: #clarity\n[Simplicity]: #simplicity\n[Concision]: #concision\n[Maintainability]: #maintainability\n[Consistency]: #consistency\n\n<a id=\"clarity\"></a>\n\n### Clarity\n\nThe core goal of readability is to produce code that is clear to the reader.\n\nClarity is primarily achieved with effective naming, helpful commentary, and\nefficient code organization.\n\nClarity is to be viewed through the lens of the reader, not the author of the\ncode. It is more important that code be easy to read than easy to write. Clarity\nin code has two distinct facets:\n\n*   [What is the code actually doing?](#clarity-purpose)\n*   [Why is the code doing what it does?](#clarity-rationale)\n\n<a id=\"clarity-purpose\"></a>\n\n#### What is the code actually doing?\n\nGo is designed such that it should be relatively straightforward to see what the\ncode is doing. In cases of uncertainty or where a reader may require prior\nknowledge in order to understand the code, it is worth investing time in order\nto make the code's purpose clearer for future readers. For example, it may help\nto:\n\n*   Use more descriptive variable names\n*   Add additional commentary\n*   Break up the code with whitespace and comments\n*   Refactor the code into separate functions/methods to make it more modular\n\nThere is no one-size-fits-all approach here, but it is important to prioritize\nclarity when developing Go code.\n\n<a id=\"clarity-rationale\"></a>\n\n#### Why is the code doing what it does?\n\nThe code's rationale is often sufficiently communicated by the names of\nvariables, functions, methods, or packages. Where it is not, it is important to\nadd commentary. The \"Why?\" is especially important when the code contains\nnuances that a reader may not be familiar with, such as:\n\n*   A nuance in the language, e.g., a closure will be capturing a loop variable,\n    but the closure is many lines away\n*   A nuance of the business logic, e.g., an access control check that needs to\n    distinguish between the actual user and someone impersonating a user\n\nAn API might require care to use correctly. For example, a piece of code may be\nintricate and difficult to follow for performance reasons, or a complex sequence\nof mathematical operations may use type conversions in an unexpected way. In\nthese cases and many more, it is important that accompanying commentary and\ndocumentation explain these aspects so that future maintainers don't make a\nmistake and so that readers can understand the code without needing to\nreverse-engineer it.\n\nIt is also important to be aware that some attempts to provide clarity (such as\nadding extra commentary) can actually obscure the code's purpose by adding\nclutter, restating what the code already says, contradicting the code, or adding\nmaintenance burden to keep the comments up-to-date. Allow the code to speak for\nitself (e.g., by making the symbol names themselves self-describing) rather than\nadding redundant comments. It is often better for comments to explain why\nsomething is done, not what the code is doing.\n\nThe Google codebase is largely uniform and consistent. It is often the case that\ncode that stands out (e.g., by using an unfamiliar pattern) is doing so for a\ngood reason, typically for performance. Maintaining this property is important\nto make it clear to readers where they should focus their attention when reading\na new piece of code.\n\nThe standard library contains many examples of this principle in action. Among\nthem:\n\n*   Maintainer comments in\n    [`package sort`](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/sort/sort.go).\n*   Good\n    [runnable examples in the same package](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/sort/example_search_test.go),\n    which benefit both users (they\n    [show up in godoc](https://pkg.go.dev/sort#pkg-examples)) and maintainers\n    (they [run as part of tests](decisions#examples)).\n*   [`strings.Cut`](https://pkg.go.dev/strings#Cut) is only four lines of code,\n    but they improve the\n    [clarity and correctness of callsites](https://github.com/golang/go/issues/46336).\n\n<a id=\"simplicity\"></a>\n\n### Simplicity\n\nYour Go code should be simple for those using, reading, and maintaining it.\n\nGo code should be written in the simplest way that accomplishes its goals, both\nin terms of behavior and performance. Within the Google Go codebase, simple\ncode:\n\n*   Is easy to read from top to bottom\n*   Does not assume that you already know what it is doing\n*   Does not assume that you can memorize all of the preceding code\n*   Does not have unnecessary levels of abstraction\n*   Does not have names that call attention to something mundane\n*   Makes the propagation of values and decisions clear to the reader\n*   Has comments that explain why, not what, the code is doing to avoid future\n    deviation\n*   Has documentation that stands on its own\n*   Has useful errors and useful test failures\n*   May often be mutually exclusive with \"clever\" code\n\nTradeoffs can arise between code simplicity and API usage simplicity. For\nexample, it may be worthwhile to have the code be more complex so that the end\nuser of the API may more easily call the API correctly. In contrast, it may also\nbe worthwhile to leave a bit of extra work to the end user of the API so that\nthe code remains simple and easy to understand.\n\nWhen code needs complexity, the complexity should be added deliberately. This is\ntypically necessary if additional performance is required or where there are\nmultiple disparate customers of a particular library or service. Complexity may\nbe justified, but it should come with accompanying documentation so that clients\nand future maintainers are able to understand and navigate the complexity. This\nshould be supplemented with tests and examples that demonstrate its correct\nusage, especially if there is both a \"simple\" and a \"complex\" way to use the\ncode.\n\nThis principle does not imply that complex code cannot or should not be written\nin Go or that Go code is not allowed to be complex. We strive for a codebase\nthat avoids unnecessary complexity so that when complexity does appear, it\nindicates that the code in question requires care to understand and maintain.\nIdeally, there should be accompanying commentary that explains the rationale and\nidentifies the care that should be taken. This often arises when optimizing code\nfor performance; doing so often requires a more complex approach, like\npreallocating a buffer and reusing it throughout a goroutine lifetime. When a\nmaintainer sees this, it should be a clue that the code in question is\nperformance-critical, and that should influence the care that is taken when\nmaking future changes. If employed unnecessarily, on the other hand, this\ncomplexity is a burden on those who need to read or change the code in the\nfuture.\n\nIf code turns out to be very complex when its purpose should be simple, this is\noften a signal to revisit the implementation to see if there is a simpler way to\naccomplish the same thing.\n\n<a id=\"least-mechanism\"></a>\n\n#### Least mechanism\n\nWhere there are several ways to express the same idea, prefer the one that uses\nthe most standard tools. Sophisticated machinery often exists, but should not be\nemployed without reason. It is easy to add complexity to code as needed, whereas\nit is much harder to remove existing complexity after it has been found to be\nunnecessary.\n\n1.  Aim to use a core language construct (for example a channel, slice, map,\n    loop, or struct) when sufficient for your use case.\n2.  If there isn't one, look for a tool within the standard library (like an\n    HTTP client or a template engine).\n3.  Finally, consider whether there is a core library in the Google codebase\n    that is sufficient before introducing a new dependency or creating your own.\n\nAs an example, consider production code that contains a flag bound to a variable\nwith a default value which must be overridden in tests. Unless intending to test\nthe program's command-line interface itself (say, with `os/exec`), it is simpler\nand therefore preferable to override the bound value directly rather than by\nusing `flag.Set`.\n\nSimilarly, if a piece of code requires a set membership check, a boolean-valued\nmap (e.g., `map[string]bool`) often suffices. Libraries that provide set-like\ntypes and functionality should only be used if more complicated operations are\nrequired that are impossible or overly complicated with a map.\n\n<a id=\"concision\"></a>\n\n### Concision\n\nConcise Go code has a high signal-to-noise ratio. It is easy to discern the\nrelevant details, and the naming and structure guide the reader through these\ndetails.\n\nThere are many things that can get in the way of surfacing the most salient\ndetails at any given time:\n\n*   Repetitive code\n*   Extraneous syntax\n*   [Opaque names](#naming)\n*   Unnecessary abstraction\n*   Whitespace\n\nRepetitive code especially obscures the differences between each\nnearly-identical section, and requires a reader to visually compare similar\nlines of code to find the changes. [Table-driven testing] is a good example of a\nmechanism that can concisely factor out the common code from the important\ndetails of each repetition, but the choice of which pieces to include in the\ntable will have an impact on how easy the table is to understand.\n\nWhen considering multiple ways to structure code, it is worth considering which\nway makes important details the most apparent.\n\nUnderstanding and using common code constructions and idioms are also important\nfor maintaining a high signal-to-noise ratio. For example, the following code\nblock is very common in [error handling], and the reader can quickly understand\nthe purpose of this block.\n\n```go\n// Good:\nif err := doSomething(); err != nil {\n    // ...\n}\n```\n\nIf code looks very similar to this but is subtly different, a reader may not\nnotice the change. In cases like this, it is worth intentionally [\"boosting\"]\nthe signal of the error check by adding a comment to call attention to it.\n\n```go\n// Good:\nif err := doSomething(); err == nil { // if NO error\n    // ...\n}\n```\n\n[Table-driven testing]: https://go.dev/wiki/TableDrivenTests\n[error handling]: https://go.dev/blog/errors-are-values\n[\"boosting\"]: best-practices#signal-boost\n\n<a id=\"maintainability\"></a>\n\n### Maintainability\n\nCode is edited many more times than it is written. Readable code not only makes\nsense to a reader who is trying to understand how it works, but also to the\nprogrammer who needs to change it. Clarity is key.\n\nMaintainable code:\n\n*   Is easy for a future programmer to modify correctly\n*   Has APIs that are structured so that they can grow gracefully\n*   Is clear about the assumptions that it makes and chooses abstractions that\n    map to the structure of the problem, not to the structure of the code\n*   Avoids unnecessary coupling and doesn't include features that are not used\n*   Has a comprehensive test suite to ensure promised behaviors are maintained\n    and important logic is correct, and the tests provide clear, actionable\n    diagnostics in case of failure\n\nWhen using abstractions like interfaces and types which by definition remove\ninformation from the context in which they are used, it is important to ensure\nthat they provide sufficient benefit. Editors and IDEs can connect directly to a\nmethod definition and show the corresponding documentation when a concrete type\nis used, but can only refer to an interface definition otherwise. Interfaces are\na powerful tool, but come with a cost, since the maintainer may need to\nunderstand the specifics of the underlying implementation in order to correctly\nuse the interface, which must be explained within the interface documentation or\nat the call-site.\n\nMaintainable code also avoids hiding important details in places that are easy\nto overlook. For example, in each of the following lines of code, the presence\nor lack of a single character is critical to understand the line:\n\n```go\n// Bad:\n// The use of = instead of := can change this line completely.\nif user, err = db.UserByID(userID); err != nil {\n    // ...\n}\n```\n\n```go\n// Bad:\n// The ! in the middle of this line is very easy to miss.\nleap := (year%4 == 0) && (!(year%100 == 0) || (year%400 == 0))\n```\n\nNeither of these are incorrect, but both could be written in a more explicit\nfashion, or could have an accompanying comment that calls attention to the\nimportant behavior:\n\n```go\n// Good:\nu, err := db.UserByID(userID)\nif err != nil {\n    return fmt.Errorf(\"invalid origin user: %s\", err)\n}\nuser = u\n```\n\n```go\n// Good:\n// Gregorian leap years aren't just year%4 == 0.\n// See https://en.wikipedia.org/wiki/Leap_year#Algorithm.\nvar (\n    leap4   = year%4 == 0\n    leap100 = year%100 == 0\n    leap400 = year%400 == 0\n)\nleap := leap4 && (!leap100 || leap400)\n```\n\nIn the same way, a helper function that hides critical logic or an important\nedge-case could make it easy for a future change to fail to account for it\nproperly.\n\nPredictable names are another feature of maintainable code. A user of a package\nor a maintainer of a piece of code should be able to predict the name of a\nvariable, method, or function in a given context. Function parameters and\nreceiver names for identical concepts should typically share the same name, both\nto keep documentation understandable and to facilitate refactoring code with\nminimal overhead.\n\nMaintainable code minimizes its dependencies (both implicit and explicit).\nDepending on fewer packages means fewer lines of code that can affect behavior.\nAvoiding dependencies on internal or undocumented behavior makes code less\nlikely to impose a maintenance burden when those behaviors change in the future.\n\nWhen considering how to structure or write code, it is worth taking the time to\nthink through ways in which the code may evolve over time. If a given approach\nis more conducive to easier and safer future changes, that is often a good\ntrade-off, even if it means a slightly more complicated design.\n\n<a id=\"consistency\"></a>\n\n### Consistency\n\nConsistent code is code that looks, feels, and behaves like similar code\nthroughout the broader codebase, within the context of a team or package, and\neven within a single file.\n\nConsistency concerns do not override any of the principles above, but if a tie\nmust be broken, it is often beneficial to break it in favor of consistency.\n\nConsistency within a package is often the most immediately important level of\nconsistency. It can be very jarring if the same problem is approached in\nmultiple ways throughout a package, or if the same concept has many names within\na file. However, even this should not override documented style principles or\nglobal consistency.\n\n<a id=\"core\"></a>\n\n## Core guidelines\n\nThese guidelines collect the most important aspects of Go style that all Go code\nis expected to follow. We expect that these principles be learned and followed\nby the time readability is granted. These are not expected to change frequently,\nand new additions will have to clear a high bar.\n\nThe guidelines below expand on the recommendations in [Effective Go], which\nprovide a common baseline for Go code across the entire community.\n\n[Effective Go]: https://go.dev/doc/effective_go\n\n<a id=\"formatting\"></a>\n\n### Formatting\n\nAll Go source files must conform to the format outputted by the `gofmt` tool.\nThis format is enforced by a presubmit check in the Google codebase.\n[Generated code] should generally also be formatted (e.g., by using\n[`format.Source`]), as it is also browsable in Code Search.\n\n[Generated code]: https://docs.bazel.build/versions/main/be/general.html#genrule\n[`format.Source`]: https://pkg.go.dev/go/format#Source\n\n<a id=\"mixed-caps\"></a>\n\n### MixedCaps\n\nGo source code uses `MixedCaps` or `mixedCaps` (camel case) rather than\nunderscores (snake case) when writing multi-word names.\n\nThis applies even when it breaks conventions in other languages. For example, a\nconstant is `MaxLength` (not `MAX_LENGTH`) if exported and `maxLength` (not\n`max_length`) if unexported.\n\nLocal variables are considered [unexported] for the purpose of choosing the\ninitial capitalization.\n\n<!--#include file=\"/go/g3doc/style/includes/special-name-exception.md\"-->\n\n[unexported]: https://go.dev/ref/spec#Exported_identifiers\n\n<a id=\"line-length\"></a>\n\n### Line length\n\nThere is no fixed line length for Go source code. If a line feels too long,\nprefer refactoring instead of splitting it. If it is already as short as it is\npractical for it to be, the line should be allowed to remain long.\n\nDo not split a line:\n\n*   Before an [indentation change](decisions#indentation-confusion) (e.g.,\n    function declaration, conditional)\n*   To make a long string (e.g., a URL) fit into multiple shorter lines\n\n<a id=\"naming\"></a>\n\n### Naming\n\nNaming is more art than science. In Go, names tend to be somewhat shorter than\nin many other languages, but the same [general guidelines] apply. Names should:\n\n*   Not feel [repetitive](decisions#repetition) when they are used\n*   Take the context into consideration\n*   Not repeat concepts that are already clear\n\nYou can find more specific guidance on naming in [decisions](decisions#naming).\n\n[general guidelines]: https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html\n\n<a id=\"local-consistency\"></a>\n\n### Local consistency\n\nWhere the style guide has nothing to say about a particular point of style,\nauthors are free to choose the style that they prefer, unless the code in close\nproximity (usually within the same file or package, but sometimes within a team\nor project directory) has taken a consistent stance on the issue.\n\nExamples of **valid** local style considerations:\n\n*   Use of `%s` or `%v` for formatted printing of errors\n*   Usage of buffered channels in lieu of mutexes\n\nExamples of **invalid** local style considerations:\n\n*   Line length restrictions for code\n*   Use of assertion-based testing libraries\n\nIf the local style disagrees with the style guide but the readability impact is\nlimited to one file, it will generally be surfaced in a code review for which a\nconsistent fix would be outside the scope of the CL in question. At that point,\nit is appropriate to file a bug to track the fix.\n\nIf a change would worsen an existing style deviation, expose it in more API\nsurfaces, expand the number of files in which the deviation is present, or\nintroduce an actual bug, then local consistency is no longer a valid\njustification for violating the style guide for new code. In these cases, it is\nappropriate for the author to clean up the existing codebase in the same CL,\nperform a refactor in advance of the current CL, or find an alternative that at\nleast does not make the local problem worse.\n\n<!--\n\n-->\n\n{% endraw %}\n"
  },
  {
    "path": "go/index.md",
    "content": "# Go Style\n\nhttps://google.github.io/styleguide/go\n\n[Overview](index) | [Guide](guide) | [Decisions](decisions) |\n[Best practices](best-practices)\n\n<!--\n\n-->\n\n{% raw %}\n\n<a id=\"about\"></a>\n\n## About\n\nThe Go Style Guide and accompanying documents codify the current best approaches\nfor writing readable and idiomatic Go. Adherence to the Style Guide is not\nintended to be absolute, and these documents will never be exhaustive. Our\nintention is to minimize the guesswork of writing readable Go so that newcomers\nto the language can avoid common mistakes. The Style Guide also serves to unify\nthe style guidance given by anyone reviewing Go code at Google.\n\nDocument            | Link                                                  | Primary Audience    | [Normative] | [Canonical]\n------------------- | ----------------------------------------------------- | ------------------- | ----------- | -----------\n**Style Guide**     | https://google.github.io/styleguide/go/guide          | Everyone            | Yes         | Yes\n**Style Decisions** | https://google.github.io/styleguide/go/decisions      | Readability Mentors | Yes         | No\n**Best Practices**  | https://google.github.io/styleguide/go/best-practices | Anyone interested   | No          | No\n\n[Normative]: #normative\n[Canonical]: #canonical\n\n<a id=\"docs\"></a>\n\n### Documents\n\n1.  The **[Style Guide](https://google.github.io/styleguide/go/guide)** outlines\n    the foundation of Go style at Google. This document is definitive and is\n    used as the basis for the recommendations in Style Decisions and Best\n    Practices.\n\n1.  **[Style Decisions](https://google.github.io/styleguide/go/decisions)** is a\n    more verbose document that summarizes decisions on specific style points and\n    discusses the reasoning behind the decisions where appropriate.\n\n    These decisions may occasionally change based on new data, new language\n    features, new libraries, or emerging patterns, but it is not expected that\n    individual Go programmers at Google should keep up-to-date with this\n    document.\n\n1.  **[Best Practices](https://google.github.io/styleguide/go/best-practices)**\n    documents some of the patterns that have evolved over time that solve common\n    problems, read well, and are robust to code maintenance needs.\n\n    These best practices are not canonical, but Go programmers at Google are\n    encouraged to use them where possible to keep the codebase uniform and\n    consistent.\n\nThese documents intend to:\n\n*   Agree on a set of principles for weighing alternate styles\n*   Codify settled matters of Go style\n*   Document and provide canonical examples for Go idioms\n*   Document the pros and cons of various style decisions\n*   Help minimize surprises in Go readability reviews\n*   Help readability mentors use consistent terminology and guidance\n\nThese documents do **not** intend to:\n\n*   Be an exhaustive list of comments that can be given in a readability review\n*   List all of the rules everyone is expected to remember and follow at all\n    times\n*   Replace good judgment in the use of language features and style\n*   Justify large-scale changes to get rid of style differences\n\nThere will always be differences from one Go programmer to another and from one\nteam's codebase to another. However, it is in the best interest of Google and\nAlphabet that our codebase be as consistent as possible. (See\n[guide](guide#consistency) for more on consistency.) To that end, feel free to\nmake style improvements as you see fit, but you do not need to nit-pick every\nviolation of the Style Guide that you find. In particular, these documents may\nchange over time, and that is no reason to cause extra churn in existing\ncodebases; it suffices to write new code using the latest best practices and\naddress nearby issues over time.\n\nIt is important to recognize that issues of style are inherently personal and\nthat there are always inherent trade-offs. Much of the guidance in these\ndocuments is subjective, but just like with `gofmt`, there is significant value\nin the uniformity they provide. As such, style recommendations will not be\nchanged without due discourse, Go programmers at Google are encouraged to follow\nthe style guide even where they might disagree.\n\n<a id=\"definitions\"></a>\n\n## Definitions\n\nThe following words, which are used throughout the style documents, are defined\nbelow:\n\n*   **Canonical**: Establishes prescriptive and enduring rules\n    <a id=\"canonical\"></a>\n\n    Within these documents, \"canonical\" is used to describe something that is\n    considered a standard that all code (old and new) should follow and that is\n    not expected to change substantially over time. Principles in the canonical\n    documents should be understood by authors and reviewers alike, so everything\n    included within a canonical document must meet a high bar. As such,\n    canonical documents are generally shorter and prescribe fewer elements of\n    style than non-canonical documents.\n\n    https://google.github.io/styleguide/go#canonical\n\n*   **Normative**: Intended to establish consistency <a id=\"normative\"></a>\n\n    Within these documents, \"normative\" is used to describe something that is an\n    agreed-upon element of style for use by Go code reviewers, in order that the\n    suggestions, terminology, and justifications are consistent. These elements\n    may change over time, and these documents will reflect such changes so that\n    reviewers can remain consistent and up-to-date. Authors of Go code are not\n    expected to be familiar with the normative documents, but the documents will\n    frequently be used as a reference by reviewers in readability reviews.\n\n    https://google.github.io/styleguide/go#normative\n\n*   **Idiomatic**: Common and familiar <a id=\"idiomatic\"></a>\n\n    Within these documents, \"idiomatic\" is used to refer to something that is\n    prevalent in Go code and has become a familiar pattern that is easy to\n    recognize. In general, an idiomatic pattern should be preferred to something\n    unidiomatic if both serve the same purpose in context, as this is what will\n    be the most familiar to readers.\n\n    https://google.github.io/styleguide/go#idiomatic\n\n<a id=\"references\"></a>\n\n## Additional references\n\nThis guide assumes the reader is familiar with [Effective Go], as it provides a\ncommon baseline for Go code across the entire Go community.\n\nBelow are some additional resources for those looking to self-educate about Go\nstyle and for reviewers looking to provide further linkable context in their\nreviews. Participants in the Go readability process are not expected to be\nfamiliar with these resources, but they may arise as context in readability\nreviews.\n\n[Effective Go]: https://go.dev/doc/effective_go\n\n**External References**\n\n*   [Go Language Specification](https://go.dev/ref/spec)\n*   [Go FAQ](https://go.dev/doc/faq)\n*   [Go Memory Model](https://go.dev/ref/mem)\n*   [Go Data Structures](https://research.swtch.com/godata)\n*   [Go Interfaces](https://research.swtch.com/interfaces)\n*   [Go Proverbs](https://go-proverbs.github.io/)\n\n*   <a id=\"gotip\"></a> Go Tip Episodes - stay tuned.\n\n*   <a id=\"unit-testing-practices\"></a> Unit Testing Practices - stay tuned.\n\n**Relevant Testing-on-the-Toilet articles**\n\n*   [TotT: Identifier Naming][tott-431]\n*   [TotT: Testing State vs. Testing Interactions][tott-281]\n*   [TotT: Effective Testing][tott-324]\n*   [TotT: Risk-driven Testing][tott-329]\n*   [TotT: Change-detector Tests Considered Harmful][tott-350]\n\n[tott-431]: https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html\n[tott-281]: https://testing.googleblog.com/2013/03/testing-on-toilet-testing-state-vs.html\n[tott-324]: https://testing.googleblog.com/2014/05/testing-on-toilet-effective-testing.html\n[tott-329]: https://testing.googleblog.com/2014/05/testing-on-toilet-risk-driven-testing.html\n[tott-350]: https://testing.googleblog.com/2015/01/testing-on-toilet-change-detector-tests.html\n\n**Additional External Writings**\n\n*   [Go and Dogma](https://research.swtch.com/dogma)\n*   [Less is exponentially more](https://commandcenter.blogspot.com/2012/06/less-is-exponentially-more.html)\n*   [Esmerelda's Imagination](https://commandcenter.blogspot.com/2011/12/esmereldas-imagination.html)\n*   [Regular expressions for parsing](https://commandcenter.blogspot.com/2011/08/regular-expressions-in-lexing-and.html)\n*   [Gofmt's style is no one's favorite, yet Gofmt is everyone's favorite](https://www.youtube.com/watch?v=PAAkCSZUG1c&t=8m43s)\n    (YouTube)\n\n<!--\n\n-->\n\n{% endraw %}\n"
  },
  {
    "path": "google-c-style.el",
    "content": ";;; google-c-style.el --- Google's C/C++ style for c-mode\n\n;; Keywords: c, tools\n\n;; google-c-style.el is Copyright (C) 2008 Google Inc. All Rights Reserved.\n;;\n;; It is free software; you can redistribute it and/or modify it under the\n;; terms of either:\n;;\n;; a) the GNU General Public License as published by the Free Software\n;; Foundation; either version 1, or (at your option) any later version, or\n;;\n;; b) the \"Artistic License\".\n\n;;; Commentary:\n\n;; Provides the google C/C++ coding style. You may wish to add\n;; `google-set-c-style' to your `c-mode-common-hook' after requiring this\n;; file. For example:\n;;\n;;    (add-hook 'c-mode-common-hook 'google-set-c-style)\n;;\n;; If you want the RETURN key to go to the next line and space over\n;; to the right place, add this to your .emacs right after the load-file:\n;;\n;;    (add-hook 'c-mode-common-hook 'google-make-newline-indent)\n\n;;; Code:\n\n;; For some reason 1) c-backward-syntactic-ws is a macro and 2)  under Emacs 22\n;; bytecode cannot call (unexpanded) macros at run time:\n(eval-when-compile (require 'cc-defs))\n\n;; Wrapper function needed for Emacs 21 and XEmacs (Emacs 22 offers the more\n;; elegant solution of composing a list of lineup functions or quantities with\n;; operators such as \"add\")\n(defun google-c-lineup-expression-plus-4 (langelem)\n  \"Indents to the beginning of the current C expression plus 4 spaces.\n\nThis implements title \\\"Function Declarations and Definitions\\\"\nof the Google C++ Style Guide for the case where the previous\nline ends with an open parenthesis.\n\n\\\"Current C expression\\\", as per the Google Style Guide and as\nclarified by subsequent discussions, means the whole expression\nregardless of the number of nested parentheses, but excluding\nnon-expression material such as \\\"if(\\\" and \\\"for(\\\" control\nstructures.\n\nSuitable for inclusion in `c-offsets-alist'.\"\n  (save-excursion\n    (back-to-indentation)\n    ;; Go to beginning of *previous* line:\n    (c-backward-syntactic-ws)\n    (back-to-indentation)\n    (cond\n     ;; We are making a reasonable assumption that if there is a control\n     ;; structure to indent past, it has to be at the beginning of the line.\n     ((looking-at \"\\\\(\\\\(if\\\\|for\\\\|while\\\\)\\\\s *(\\\\)\")\n      (goto-char (match-end 1)))\n     ;; For constructor initializer lists, the reference point for line-up is\n     ;; the token after the initial colon.\n     ((looking-at \":\\\\s *\")\n      (goto-char (match-end 0))))\n    (vector (+ 4 (current-column)))))\n\n;;;###autoload\n(defconst google-c-style\n  `((c-recognize-knr-p . nil)\n    (c-enable-xemacs-performance-kludge-p . t) ; speed up indentation in XEmacs\n    (c-basic-offset . 2)\n    (indent-tabs-mode . nil)\n    (c-comment-only-line-offset . 0)\n    (c-hanging-braces-alist . ((defun-open after)\n                               (defun-close before after)\n                               (class-open after)\n                               (class-close before after)\n                               (inexpr-class-open after)\n                               (inexpr-class-close before)\n                               (namespace-open after)\n                               (inline-open after)\n                               (inline-close before after)\n                               (block-open after)\n                               (block-close . c-snug-do-while)\n                               (extern-lang-open after)\n                               (extern-lang-close after)\n                               (statement-case-open after)\n                               (substatement-open after)))\n    (c-hanging-colons-alist . ((case-label)\n                               (label after)\n                               (access-label after)\n                               (member-init-intro before)\n                               (inher-intro)))\n    (c-hanging-semi&comma-criteria\n     . (c-semi&comma-no-newlines-for-oneline-inliners\n        c-semi&comma-inside-parenlist\n        c-semi&comma-no-newlines-before-nonblanks))\n    (c-indent-comments-syntactically-p . t)\n    (comment-column . 40)\n    (c-indent-comment-alist . ((other . (space . 2))))\n    (c-cleanup-list . (brace-else-brace\n                       brace-elseif-brace\n                       brace-catch-brace\n                       empty-defun-braces\n                       defun-close-semi\n                       list-close-comma\n                       scope-operator))\n    (c-offsets-alist . ((arglist-intro google-c-lineup-expression-plus-4)\n                        (func-decl-cont . ++)\n                        (member-init-intro . ++)\n                        (inher-intro . ++)\n                        (comment-intro . 0)\n                        (arglist-close . c-lineup-arglist)\n                        (topmost-intro . 0)\n                        (block-open . 0)\n                        (inline-open . 0)\n                        (substatement-open . 0)\n                        (statement-cont\n                         .\n                         (,(when (fboundp 'c-no-indent-after-java-annotations)\n                             'c-no-indent-after-java-annotations)\n                          ,(when (fboundp 'c-lineup-assignments)\n                             'c-lineup-assignments)\n                          ++))\n                        (label . /)\n                        (case-label . +)\n                        (statement-case-open . +)\n                        (statement-case-intro . +) ; case w/o {\n                        (access-label . /)\n                        (innamespace . 0))))\n  \"Google C/C++ Programming Style.\")\n\n;;;###autoload\n(defun google-set-c-style ()\n  \"Set the current buffer's c-style to Google C/C++ Programming\n  Style. Meant to be added to `c-mode-common-hook'.\"\n  (interactive)\n  (make-local-variable 'c-tab-always-indent)\n  (setq c-tab-always-indent t)\n  (c-add-style \"Google\" google-c-style t))\n\n;;;###autoload\n(defun google-make-newline-indent ()\n  \"Sets up preferred newline behavior. Not set by default. Meant\n  to be added to `c-mode-common-hook'.\"\n  (interactive)\n  (define-key c-mode-base-map \"\\C-m\" 'newline-and-indent)\n  (define-key c-mode-base-map [ret] 'newline-and-indent))\n\n(provide 'google-c-style)\n;;; google-c-style.el ends here\n"
  },
  {
    "path": "google-r-style.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <meta charset=\"utf-8\">\n  <meta http-equiv=\"refresh\" content=\"1; url=Rguide.html\">\n  <title>Redirecting</title>\n</head>\n<!-- The BODY onLoad redirect is the best: it preserves #fragments and\n     ?queries.  But it requires javascript.  If that fails, the\n     meta-refresh kicks in; it works more generally, but loses fragments\n     and queries, takes a second, and pollutes the browser history.\n     If they both fail, we let the user manually click on the new link.\n-->\n<body onload=\"location.replace(location.href.replace('google-r-style.html', 'Rguide.html'))\">\n  Redirecting you to <a href=\"Rguide.html\">Rguide.html</a>.\n</body>\n</html>\n"
  },
  {
    "path": "google_python_style.vim",
    "content": "\" Copyright 2019 Google LLC\n\"\n\" Licensed under the Apache License, Version 2.0 (the \"License\");\n\" you may not use this file except in compliance with the License.\n\" You may obtain a copy of the License at\n\"\n\"    https://www.apache.org/licenses/LICENSE-2.0\n\"\n\" Unless required by applicable law or agreed to in writing, software\n\" distributed under the License is distributed on an \"AS IS\" BASIS,\n\" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\" See the License for the specific language governing permissions and\n\" limitations under the License.\n\n\" Indent Python in the Google way.\n\nsetlocal indentexpr=GetGooglePythonIndent(v:lnum)\n\nlet s:maxoff = 50 \" maximum number of lines to look backwards.\n\nfunction GetGooglePythonIndent(lnum)\n\n  \" Indent inside parens.\n  \" Align with the open paren unless it is at the end of the line.\n  \" E.g.\n  \"   open_paren_not_at_EOL(100,\n  \"                         (200,\n  \"                          300),\n  \"                         400)\n  \"   open_paren_at_EOL(\n  \"       100, 200, 300, 400)\n  call cursor(a:lnum, 1)\n  let [par_line, par_col] = searchpairpos('(\\|{\\|\\[', '', ')\\|}\\|\\]', 'bW',\n        \\ \"line('.') < \" . (a:lnum - s:maxoff) . \" ? dummy :\"\n        \\ . \" synIDattr(synID(line('.'), col('.'), 1), 'name')\"\n        \\ . \" =~ '\\\\(Comment\\\\|String\\\\)$'\")\n  if par_line > 0\n    call cursor(par_line, 1)\n    if par_col != col(\"$\") - 1\n      return par_col\n    endif\n  endif\n\n  \" Delegate the rest to the original function.\n  return GetPythonIndent(a:lnum)\n\nendfunction\n\nlet pyindent_nested_paren=\"&sw*2\"\nlet pyindent_open_paren=\"&sw*2\"\n"
  },
  {
    "path": "htmlcssguide.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Google HTML/CSS Style Guide</title>\n<link rel=\"stylesheet\" href=\"javaguide.css\">\n<script src=\"include/styleguide.js\"></script>\n<link rel=\"shortcut icon\" href=\"/styleguide/favicon.ico\">\n<script src=\"include/jsguide.js\"></script>\n</head>\n<body onload=\"initStyleGuide();\">\n<div id=\"content\">\n<h1>Google HTML/CSS Style Guide</h1>\n<h2 id=\"Background\" class=\"numbered\">Background</h2>\n\n<p>This document defines formatting and style rules for HTML and CSS. It aims at\nimproving collaboration, code quality, and enabling supporting infrastructure.\nIt applies to raw, working files that use HTML and CSS, including Sass and GSS\nfiles. Tools are free to obfuscate, minify, and compile as long as the general\ncode quality is maintained.</p>\n\n<h2 id=\"General\" class=\"numbered\">General</h2>\n\n<h3 id=\"General_Style_Rules\" class=\"numbered\">General Style Rules</h3>\n\n<h4 id=\"Protocol\" class=\"numbered\">Protocol</h4>\n\n<p>Use HTTPS for embedded resources where possible.</p>\n\n<p>Always use HTTPS (<code>https:</code>) for images and other media files, style sheets, and\nscripts, unless the respective files are not available over HTTPS.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended: omits the protocol --&gt;\n&lt;script src=\"//ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"&gt;&lt;/script&gt;\n\n&lt;!-- Not recommended: uses HTTP --&gt;\n&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<pre><code class=\"language-css bad\">/* Not recommended: omits the protocol */\n@import '//fonts.googleapis.com/css?family=Open+Sans';\n\n/* Not recommended: uses HTTP */\n@import 'http://fonts.googleapis.com/css?family=Open+Sans';\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n@import 'https://fonts.googleapis.com/css?family=Open+Sans';\n</code></pre>\n\n<h3 id=\"General_Formatting_Rules\" class=\"numbered\">General Formatting Rules</h3>\n\n<h4 id=\"Indentation\" class=\"numbered\">Indentation</h4>\n\n<p>Indent by 2 spaces at a time.</p>\n\n<p>Don’t use tabs or mix tabs and spaces for indentation.</p>\n\n<pre><code class=\"language-html good\">&lt;ul&gt;\n  &lt;li&gt;Fantastic\n  &lt;li&gt;Great\n&lt;/ul&gt;\n</code></pre>\n\n<pre><code class=\"language-css good\">.example {\n  color: blue;\n}\n</code></pre>\n\n<h4 id=\"Capitalization\" class=\"numbered\">Capitalization</h4>\n\n<p>Use only lowercase.</p>\n\n<p>All code has to be lowercase: This applies to HTML element names, attributes,\nattribute values (unless <code>text/CDATA</code>), CSS selectors, properties, and property\nvalues (with the exception of strings).</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;A HREF=\"/\"&gt;Home&lt;/A&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;img src=\"google.png\" alt=\"Google\"&gt;\n</code></pre>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\ncolor: #E5E5E5;\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\ncolor: #e5e5e5;\n</code></pre>\n\n<h4 id=\"Trailing_Whitespace\" class=\"numbered\">Trailing Whitespace</h4>\n\n<p>Remove trailing white spaces.</p>\n\n<p>Trailing white spaces are unnecessary and can complicate diffs.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;p&gt;What?_\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;p&gt;Yes please.\n</code></pre>\n\n<h3 id=\"General_Meta_Rules\" class=\"numbered\">General Meta Rules</h3>\n\n<h4 id=\"Encoding\" class=\"numbered\">Encoding</h4>\n\n<p>Use UTF-8 (no BOM).</p>\n\n<p>Make sure your editor uses UTF-8 as character encoding, without a byte order\nmark.</p>\n\n<p>Specify the encoding in HTML templates and documents via <code>&lt;meta\ncharset=\"utf-8\"&gt;</code>. Do not specify the encoding of style sheets as these assume\nUTF-8.</p>\n\n<p>(More on encodings and when and how to specify them can be found in\n<a href=\"https://www.w3.org/International/tutorials/tutorial-char-enc/\">Handling character encodings in HTML and CSS</a>.)</p>\n\n<h4 id=\"Comments\" class=\"numbered\">Comments</h4>\n\n<p>Explain code as needed, where possible.</p>\n\n<p>Use comments to explain code: What does it cover, what purpose does it serve,\nwhy is respective solution used or preferred?</p>\n\n<p>(This item is optional as it is not deemed a realistic expectation to always\ndemand fully documented code. Mileage may vary heavily for HTML and CSS code and\ndepends on the project’s complexity.)</p>\n\n<h4 id=\"Action_Items\" class=\"numbered\">Action Items</h4>\n\n<p>Mark todos and action items with <code>TODO</code>.</p>\n\n<p>Highlight todos by using the keyword <code>TODO</code> only, not other common formats like\n<code>@@</code>.</p>\n\n<p>Append action items after a colon as in <code>TODO: action\nitem</code>.</p>\n\n<pre><code class=\"language-django external good\">{# TODO: Revisit centering. #}\n&lt;center&gt;Test&lt;/center&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- TODO: Remove optional tags. --&gt;\n&lt;ul&gt;\n  &lt;li&gt;Apples&lt;/li&gt;\n  &lt;li&gt;Oranges&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<h2 id=\"HTML\" class=\"numbered\">HTML</h2>\n\n<h3 id=\"HTML_Style_Rules\" class=\"numbered\">HTML Style Rules</h3>\n\n<h4 id=\"Document_Type\" class=\"numbered\">Document Type</h4>\n\n<p>Use <code>&lt;!doctype html&gt;</code>.</p>\n\n<p>Always put your HTML in\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode\">no-quirks mode</a>\nby including <code>&lt;!doctype html&gt;</code> at the beginning of the document.</p>\n\n<p>A document without a doctype is rendered in “quirks mode”, and one with a\ndifferent doctype may be rendered in “limited-quirks mode”. These modes don’t\nfollow the widely-understood, widely-documented behavior for various core HTML\nand CSS constructs, and are likely to cause subtle failures and\nincompatibilities especially when re-using code that expects no-quirks mode.</p>\n\n<h4 id=\"HTML_Validity\" class=\"numbered\">HTML Validity</h4>\n\n<p>Use valid HTML where possible.</p>\n\n<p>Use valid HTML code unless that is not possible due to otherwise unattainable\nperformance goals regarding file size.</p>\n\n<p> Use tools such as the\n<a href=\"https://validator.w3.org/nu/\">W3C HTML validator</a>\nto test.</p>\n\n<p>Using valid HTML is a measurable baseline quality attribute that contributes to\nlearning about technical requirements and constraints, and that ensures proper\nHTML usage.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;title&gt;Test&lt;/title&gt;\n&lt;article&gt;This is only a test.\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;!doctype html&gt;\n&lt;meta charset=\"utf-8\"&gt;\n&lt;title&gt;Test&lt;/title&gt;\n&lt;article&gt;This is only a test.&lt;/article&gt;\n</code></pre>\n\n<h4 id=\"Semantics\" class=\"numbered\">Semantics</h4>\n\n<p>Use HTML according to its purpose.</p>\n\n<p>Use elements (sometimes incorrectly called “tags”) for what they have been\ncreated for. For example, use heading elements for headings, <code>p</code> elements for\nparagraphs, <code>a</code> elements for anchors, etc.</p>\n\n<p>Using HTML according to its purpose is important for accessibility, reuse, and\ncode efficiency reasons.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;div onclick=\"goToRecommendations();\"&gt;All recommendations&lt;/div&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;a href=\"recommendations/\"&gt;All recommendations&lt;/a&gt;\n</code></pre>\n\n<h4 id=\"Multimedia_Fallback\" class=\"numbered\">Multimedia Fallback</h4>\n\n<p>Provide alternative contents for multimedia.</p>\n\n<p>For multimedia, such as images, videos, animated objects via <code>canvas</code>, make sure\nto offer alternative access. For images that means use of meaningful alternative\ntext (<code>alt</code>) and for video and audio transcripts and captions, if available.</p>\n\n<p>Providing alternative contents is important for accessibility reasons: A blind\nuser has few cues to tell what an image is about without <code>@alt</code>, and other users\nmay have no way of understanding what video or audio contents are about either.</p>\n\n<p>(For images whose <code>alt</code> attributes would introduce redundancy, and for images\nwhose purpose is purely decorative which you cannot immediately use CSS for, use\nno alternative text, as in <code>alt=\"\"</code>.)</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;img src=\"spreadsheet.png\"&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;img src=\"spreadsheet.png\" alt=\"Spreadsheet screenshot.\"&gt;\n</code></pre>\n\n<h4 id=\"Separation_of_Concerns\" class=\"numbered\">Separation of Concerns</h4>\n\n<p>Separate structure from presentation from behavior.</p>\n\n<p>Strictly keep structure (markup), presentation (styling), and behavior\n(scripting) apart, and try to keep the interaction between the three to an\nabsolute minimum.</p>\n\n<p>That is, make sure documents and templates contain only HTML and HTML that is\nsolely serving structural purposes. Move everything presentational into style\nsheets, and everything behavioral into scripts.</p>\n\n<p>In addition, keep the contact area as small as possible by linking as few style\nsheets and scripts as possible from documents and templates.</p>\n\n<p>Separating structure from presentation from behavior is important for\nmaintenance reasons. It is always more expensive to change HTML documents and\ntemplates than it is to update style sheets and scripts.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;!doctype html&gt;\n&lt;title&gt;HTML sucks&lt;/title&gt;\n&lt;link rel=\"stylesheet\" href=\"base.css\" media=\"screen\"&gt;\n&lt;link rel=\"stylesheet\" href=\"grid.css\" media=\"screen\"&gt;\n&lt;link rel=\"stylesheet\" href=\"print.css\" media=\"print\"&gt;\n&lt;h1 style=\"font-size: 1em;\"&gt;HTML sucks&lt;/h1&gt;\n&lt;p&gt;I’ve read about this on a few sites but now I’m sure:\n  &lt;u&gt;HTML is stupid!!1&lt;/u&gt;\n&lt;center&gt;I can’t believe there’s no way to control the styling of\n  my website without doing everything all over again!&lt;/center&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;!doctype html&gt;\n&lt;title&gt;My first CSS-only redesign&lt;/title&gt;\n&lt;link rel=\"stylesheet\" href=\"default.css\"&gt;\n&lt;h1&gt;My first CSS-only redesign&lt;/h1&gt;\n&lt;p&gt;I’ve read about this on a few sites but today I’m actually\n  doing it: separating concerns and avoiding anything in the HTML of\n  my website that is presentational.\n&lt;p&gt;It’s awesome!\n</code></pre>\n\n<h4 id=\"Entity_References\" class=\"numbered\">Entity References</h4>\n\n<p>Do not use entity references.</p>\n\n<p>There is no need to use entity references like <code>&amp;mdash;</code>, <code>&amp;rdquo;</code>, or\n<code>&amp;#x263a;</code>, assuming the same encoding (UTF-8) is used for files and editors as\nwell as among teams.</p>\n\n<p>The only exceptions apply to characters with special meaning in HTML (like <code>&lt;</code>\nand <code>&amp;</code>) as well as control or “invisible” characters (like no-break spaces).</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\nThe currency symbol for the Euro is &amp;ldquo;&amp;eur;&amp;rdquo;.\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\nThe currency symbol for the Euro is “€”.\n</code></pre>\n\n<h4 id=\"Optional_Tags\" class=\"numbered\">Optional Tags</h4>\n\n<p>Omit optional tags (optional).</p>\n\n<p>For file size optimization and scannability purposes, consider omitting optional\ntags. The\n<a href=\"https://html.spec.whatwg.org/multipage/syntax.html#syntax-tag-omission\">HTML5 specification</a>\ndefines what tags can be omitted.</p>\n\n<p>(This approach may require a grace period to be established as a wider guideline\nas it’s significantly different from what web developers are typically taught.\nFor consistency and simplicity reasons it’s best served omitting all optional\ntags, not just a selection.)</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;!doctype html&gt;\n&lt;html&gt;\n  &lt;head&gt;\n    &lt;title&gt;Spending money, spending bytes&lt;/title&gt;\n  &lt;/head&gt;\n  &lt;body&gt;\n    &lt;p&gt;Sic.&lt;/p&gt;\n  &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;!doctype html&gt;\n&lt;title&gt;Saving money, saving bytes&lt;/title&gt;\n&lt;p&gt;Qed.\n</code></pre>\n\n<h4 id=\"type_Attributes\" class=\"numbered\"><code>type</code> Attributes</h4>\n\n<p>Omit <code>type</code> attributes for style sheets and scripts.</p>\n\n<p>Do not use <code>type</code> attributes for style sheets (unless not using CSS) and scripts\n(unless not using JavaScript).</p>\n\n<p>Specifying <code>type</code> attributes in these contexts is not necessary as HTML5 implies\n<a href=\"https://html.spec.whatwg.org/multipage/obsolete.html#attr-style-type\"><code>text/css</code></a>\nand\n<a href=\"https://html.spec.whatwg.org/multipage/scripting.html#attr-script-type\"><code>text/javascript</code></a>\nas defaults. This can be safely done even for older browsers.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;link rel=\"stylesheet\" href=\"https://www.google.com/css/maia.css\"\n    type=\"text/css\"&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;link rel=\"stylesheet\" href=\"https://www.google.com/css/maia.css\"&gt;\n</code></pre>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;script src=\"https://www.google.com/js/gweb/analytics/autotrack.js\"\n    type=\"text/javascript\"&gt;&lt;/script&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;script src=\"https://www.google.com/js/gweb/analytics/autotrack.js\"&gt;&lt;/script&gt;\n</code></pre>\n\n<h4 id=\"id_Attributes\" class=\"numbered\"><code>id</code> Attributes</h4>\n\n<p>Avoid unnecessary <code>id</code> attributes.</p>\n\n<p>Prefer <code>class</code> attributes for styling and <code>data</code> attributes for scripting.</p>\n\n<p>Where <code>id</code> attributes are strictly required, always include a hyphen in the\nvalue to ensure it does not match the JavaScript identifier syntax, e.g. use\n<code>user-profile</code> rather than just <code>profile</code> or <code>userProfile</code>.</p>\n\n<p>When an element has an <code>id</code> attribute, browsers will make that available as a\n<a href=\"https://html.spec.whatwg.org/multipage/window-object.html#named-access-on-the-window-object\">named property on the global <code>window</code> prototype</a>,\nwhich may cause unexpected behavior. While <code>id</code> attribute values containing a\nhyphen are still available as property names, these cannot be referenced as\nglobal JavaScript variables.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended: `window.userProfile` will resolve to reference the &lt;div&gt; node --&gt;\n&lt;div id=\"userProfile\"&gt;&lt;/div&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended: `id` attribute is required and its value includes a hyphen --&gt;\n&lt;div aria-describedby=\"user-profile\"&gt;\n  …\n  &lt;div id=\"user-profile\"&gt;&lt;/div&gt;\n  …\n&lt;/div&gt;\n</code></pre>\n\n<h3 id=\"HTML_Formatting_Rules\" class=\"numbered\">HTML Formatting Rules</h3>\n\n<h4 id=\"General_Formatting\" class=\"numbered\">General Formatting</h4>\n\n<p>Use a new line for every block, list, or table element, and indent every such\nchild element.</p>\n\n<p>Independent of the styling of an element (as CSS allows elements to assume a\ndifferent role per <code>display</code> property), put every block, list, or table element\non a new line.</p>\n\n<p>Also, indent them if they are child elements of a block, list, or table element.</p>\n\n<p>(If you run into issues around whitespace between list items it’s acceptable to\nput all <code>li</code> elements in one line. A linter is encouraged to throw a warning\ninstead of an error.)</p>\n\n<pre><code class=\"language-html good\">&lt;blockquote&gt;\n  &lt;p&gt;&lt;em&gt;Space&lt;/em&gt;, the final frontier.&lt;/p&gt;\n&lt;/blockquote&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;ul&gt;\n  &lt;li&gt;Moe\n  &lt;li&gt;Larry\n  &lt;li&gt;Curly\n&lt;/ul&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;table&gt;\n  &lt;thead&gt;\n    &lt;tr&gt;\n      &lt;th scope=\"col\"&gt;Income\n      &lt;th scope=\"col\"&gt;Taxes\n  &lt;tbody&gt;\n    &lt;tr&gt;\n      &lt;td&gt;$ 5.00\n      &lt;td&gt;$ 4.50\n&lt;/table&gt;\n</code></pre>\n\n<h4 id=\"HTML_Line-Wrapping\" class=\"numbered\">HTML Line-Wrapping</h4>\n\n<p>Break long lines (optional).</p>\n\n<p>While there is no column limit recommendation for HTML, you may consider\nwrapping long lines if it significantly improves readability.</p>\n\n<p>When line-wrapping, each continuation line should be indented to distinguish\nwrapped attributes from child elements. Lines should be wrapped consistently\nwithin a project, ideally enforced by automated code formatting tools.</p>\n\n<pre><code class=\"language-html good\">&lt;button\n  mat-icon-button\n  color=\"primary\"\n  class=\"menu-button\"\n  (click)=\"openMenu()\"\n&gt;\n  &lt;mat-icon&gt;menu&lt;/mat-icon&gt;\n&lt;/button&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;button mat-icon-button color=\"primary\" class=\"menu-button\"\n    (click)=\"openMenu()\"&gt;\n  &lt;mat-icon&gt;menu&lt;/mat-icon&gt;\n&lt;/button&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;button\n    mat-icon-button\n    color=\"primary\"\n    class=\"menu-button\"\n    (click)=\"openMenu()\"&gt;\n  &lt;mat-icon&gt;menu&lt;/mat-icon&gt;\n&lt;/button&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;button mat-icon-button\n        color=\"primary\"\n        class=\"menu-button\"\n        (click)=\"openMenu()\"&gt;\n  &lt;mat-icon&gt;menu&lt;/mat-icon&gt;\n&lt;/button&gt;\n</code></pre>\n\n<h4 id=\"HTML_Quotation_Marks\" class=\"numbered\">HTML Quotation Marks</h4>\n\n<p>When quoting attributes values, use double quotation marks.</p>\n\n<p>Use double (<code>\"\"</code>) rather than single quotation marks (<code>''</code>) around attribute\nvalues.</p>\n\n<pre><code class=\"language-html bad\">&lt;!-- Not recommended --&gt;\n&lt;a class='maia-button maia-button-secondary'&gt;Sign in&lt;/a&gt;\n</code></pre>\n\n<pre><code class=\"language-html good\">&lt;!-- Recommended --&gt;\n&lt;a class=\"maia-button maia-button-secondary\"&gt;Sign in&lt;/a&gt;\n</code></pre>\n\n<h2 id=\"CSS\" class=\"numbered\">CSS</h2>\n\n<h3 id=\"CSS_Style_Rules\" class=\"numbered\">CSS Style Rules</h3>\n\n<h4 id=\"CSS_Validity\" class=\"numbered\">CSS Validity</h4>\n\n<p>Use valid CSS where possible.</p>\n\n<p>Unless dealing with CSS validator bugs or requiring proprietary syntax, use\nvalid CSS code.</p>\n\n<p> Use tools such as the\n<a href=\"https://jigsaw.w3.org/css-validator/\">W3C CSS validator</a>\nto test.</p>\n\n<p>Using valid CSS is a measurable baseline quality attribute that allows to spot\nCSS code that may not have any effect and can be removed, and that ensures\nproper CSS usage.</p>\n\n<h4 id=\"ID_and_Class_Naming\" class=\"numbered\">Class Naming</h4>\n\n<p>Use meaningful or generic class names.</p>\n\n<p>Instead of presentational or cryptic names, always use class names that reflect\nthe purpose of the element in question, or that are otherwise generic.</p>\n\n<p>Names that are specific and reflect the purpose of the element should be\npreferred as these are most understandable and the least likely to change.</p>\n\n<p>Generic names are simply a fallback for elements that have no particular or no\nmeaning different from their siblings. They are typically needed as “helpers.”</p>\n\n<p>Using functional or generic names reduces the probability of unnecessary\ndocument or template changes.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended: meaningless */\n.yee-1901 {}\n\n/* Not recommended: presentational */\n.button-green {}\n.clear {}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended: specific */\n.gallery {}\n.login {}\n.video {}\n\n/* Recommended: generic */\n.aux {}\n.alt {}\n</code></pre>\n\n<h4 id=\"ID_and_Class_Name_Style\" class=\"numbered\">Class Name Style</h4>\n\n<p>Use class names that are as short as possible but as long as necessary.</p>\n\n<p>Try to convey what a class is about while being as brief as possible.</p>\n\n<p>Using class names this way contributes to acceptable levels of understandability\nand code efficiency.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\n.navigation {}\n.atr {}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.nav {}\n.author {}\n</code></pre>\n\n<h4 id=\"ID_and_Class_Name_Delimiters\" class=\"numbered\">Class Name Delimiters</h4>\n\n<p>Separate words in class names by a hyphen.</p>\n\n<p>Do not concatenate words and abbreviations in selectors by any characters\n(including none at all) other than hyphens, in order to improve understanding\nand scannability.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended: does not separate the words “demo” and “image” */\n.demoimage {}\n\n/* Not recommended: uses underscore instead of hyphen */\n.error_status {}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.video-id {}\n.ads-sample {}\n</code></pre>\n\n<h4 id=\"Prefixes\" class=\"numbered\">Prefixes</h4>\n\n<p>Prefix selectors with an application-specific prefix (optional).</p>\n\n<p>In large projects as well as for code that gets embedded in other projects or on\nexternal sites use prefixes (as namespaces) for class names. Use short, unique\nidentifiers followed by a dash.</p>\n\n<p>Using namespaces helps preventing naming conflicts and can make maintenance\neasier, for example in search and replace operations.</p>\n\n<pre><code class=\"language-css good\">.adw-help {} /* AdWords */\n.maia-note {} /* Maia */\n</code></pre>\n\n<h4 id=\"Type_Selectors\" class=\"numbered\">Type Selectors</h4>\n\n<p>Avoid qualifying class names with type selectors.</p>\n\n<p>Unless necessary (for example with helper classes), do not use element names in\nconjunction with classes.</p>\n\n<p>Avoiding unnecessary ancestor selectors is useful for\n<a href=\"http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/\">performance reasons</a>.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\nul.example {}\ndiv.error {}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.example {}\n.error {}\n</code></pre>\n\n<h4 id=\"ID_Selectors\" class=\"numbered\">ID Selectors</h4>\n\n<p>Avoid ID selectors.</p>\n\n<p>ID attributes are expected to be unique across an entire page, which is\ndifficult to guarantee when a page contains many components worked on by many\ndifferent engineers. Class selectors should be preferred in all situations.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\n#example {}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.example {}\n</code></pre>\n\n<h4 id=\"Shorthand_Properties\" class=\"numbered\">Shorthand Properties</h4>\n\n<p>Use shorthand properties where possible.</p>\n\n<p>CSS offers a variety of\n<a href=\"https://www.w3.org/TR/CSS21/about.html#shorthand\">shorthand</a>\nproperties (like <code>font</code>) that should be used whenever possible, even in cases\nwhere only one value is explicitly set.</p>\n\n<p>Using shorthand properties is useful for code efficiency and understandability.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\nborder-top-style: none;\nfont-family: palatino, georgia, serif;\nfont-size: 100%;\nline-height: 1.6;\npadding-bottom: 2em;\npadding-left: 1em;\npadding-right: 1em;\npadding-top: 0;\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\nborder-top: 0;\nfont: 100%/1.6 palatino, georgia, serif;\npadding: 0 1em 2em;\n</code></pre>\n\n<h4 id=\"0_and_Units\" class=\"numbered\">0 and Units</h4>\n\n<p>Omit unit specification after “0” values, unless required.</p>\n\n<p>Do not use units after <code>0</code> values unless they are required.</p>\n\n<pre><code class=\"language-css good\">flex: 0px; /* This flex-basis component requires a unit. */\nflex: 1 1 0px; /* Not ambiguous without the unit, but needed in IE11. */\nmargin: 0;\npadding: 0;\n</code></pre>\n\n<h4 id=\"Leading_0s\" class=\"numbered\">Leading 0s</h4>\n\n<p>Always include leading “0”s in values.</p>\n\n<p>Put <code>0</code>s in front of values or lengths between -1 and 1.</p>\n\n<pre><code class=\"language-css good\">font-size: 0.8em;\n</code></pre>\n\n<h4 id=\"Hexadecimal_Notation\" class=\"numbered\">Hexadecimal Notation</h4>\n\n<p>Use 3 character hexadecimal notation where possible.</p>\n\n<p>For color values that permit it, 3 character hexadecimal notation is shorter and\nmore succinct.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\ncolor: #eebbcc;\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\ncolor: #ebc;\n</code></pre>\n\n<h4 id=\"Important_Declarations\" class=\"numbered\">Important Declarations</h4>\n\n<p>Avoid using <code>!important</code> declarations.</p>\n\n<p>These declarations break the natural cascade of CSS and make it difficult to\nreason about and compose styles. Use\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity\">selector specificity</a>\nto override properties instead.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\n.example {\n  font-weight: bold !important;\n}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.example {\n  font-weight: bold;\n}\n</code></pre>\n\n<h4 id=\"Hacks\" class=\"numbered\">Hacks</h4>\n\n<p>Avoid user agent detection as well as CSS “hacks”—try a different approach\nfirst.</p>\n\n<p>It’s tempting to address styling differences over user agent detection or\nspecial CSS filters, workarounds, and hacks. Both approaches should be\nconsidered last resort in order to achieve and maintain an efficient and\nmanageable code base. Put another way, giving detection and hacks a free pass\nwill hurt projects in the long run as projects tend to take the way of least\nresistance. That is, allowing and making it easy to use detection and hacks\nmeans using detection and hacks more frequently—and more frequently is too\nfrequently.</p>\n\n<h3 id=\"CSS_Formatting_Rules\" class=\"numbered\">CSS Formatting Rules</h3>\n\n<h4 id=\"Declaration_Order\" class=\"numbered\">Declaration Order</h4>\n\n<p>Alphabetize declarations (optional).</p>\n\n<p>Sort declarations consistently within a project. In the absence of tooling to\nautomate and enforce a consistent sort order, consider putting declarations in\nalphabetical order in order to achieve consistent code in a way that is easy to\nlearn, remember, and manually maintain.</p>\n\n<p>Ignore vendor-specific prefixes for sorting purposes. However, multiple\nvendor-specific prefixes for a certain CSS property should be kept sorted (e.g.\n-moz prefix comes before -webkit).</p>\n\n<pre><code class=\"language-css good\">background: fuchsia;\nborder: 1px solid;\n-moz-border-radius: 4px;\n-webkit-border-radius: 4px;\nborder-radius: 4px;\ncolor: black;\ntext-align: center;\ntext-indent: 2em;\n</code></pre>\n\n<h4 id=\"Block_Content_Indentation\" class=\"numbered\">Block Content Indentation</h4>\n\n<p>Indent all block content.</p>\n\n<p>Indent all\n<a href=\"https://www.w3.org/TR/CSS21/syndata.html#block\">block content</a>,\nthat is rules within rules as well as declarations, so to reflect hierarchy and\nimprove understanding.</p>\n\n<pre><code class=\"language-css good\">@media screen, projection {\n\n  html {\n    background: #fff;\n    color: #444;\n  }\n\n}\n</code></pre>\n\n<h4 id=\"Declaration_Stops\" class=\"numbered\">Declaration Stops</h4>\n\n<p>Use a semicolon after every declaration.</p>\n\n<p>End every declaration with a semicolon for consistency and extensibility\nreasons.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\n.test {\n  display: block;\n  height: 100px\n}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.test {\n  display: block;\n  height: 100px;\n}\n</code></pre>\n\n<h4 id=\"Property_Name_Stops\" class=\"numbered\">Property Name Stops</h4>\n\n<p>Use a space after a property name’s colon.</p>\n\n<p>Always use a single space between property and value (but no space between\nproperty and colon) for consistency reasons.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\nh3 {\n  font-weight:bold;\n}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\nh3 {\n  font-weight: bold;\n}\n</code></pre>\n\n<h4 id=\"Declaration_Block_Separation\" class=\"numbered\">Declaration Block Separation</h4>\n\n<p>Use a space between the last selector and the declaration block.</p>\n\n<p>Always use a single space between the last selector and the opening brace that\nbegins the\n<a href=\"https://www.w3.org/TR/CSS21/syndata.html#rule-sets\">declaration block</a>.</p>\n\n<p>The opening brace should be on the same line as the last selector in a given\nrule.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended: missing space */\n.video{\n  margin-top: 1em;\n}\n\n/* Not recommended: unnecessary line break */\n.video\n{\n  margin-top: 1em;\n}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n.video {\n  margin-top: 1em;\n}\n</code></pre>\n\n<h4 id=\"Selector_and_Declaration_Separation\" class=\"numbered\">Selector and Declaration Separation</h4>\n\n<p>Separate selectors and declarations by new lines.</p>\n\n<p>Always start a new line for each selector and declaration.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\na:focus, a:active {\n  position: relative; top: 1px;\n}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\nh1,\nh2,\nh3 {\n  font-weight: normal;\n  line-height: 1.2;\n}\n</code></pre>\n\n<h4 id=\"Rule_Separation\" class=\"numbered\">Rule Separation</h4>\n\n<p>Separate rules by new lines.</p>\n\n<p>Always put a blank line (two line breaks) between rules.</p>\n\n<pre><code class=\"language-css good\">html {\n  background: #fff;\n}\n\nbody {\n  margin: auto;\n  width: 50%;\n}\n</code></pre>\n\n<h4 id=\"CSS_Quotation_Marks\" class=\"numbered\">CSS Quotation Marks</h4>\n\n<p>Use single (<code>''</code>) rather than double (<code>\"\"</code>) quotation marks for attribute\nselectors and property values.</p>\n\n<p>Do not use quotation marks in URI values (<code>url()</code>).</p>\n\n<p>Exception: If you do need to use the <code>@charset</code> rule, use double quotation\nmarks—<a href=\"https://www.w3.org/TR/CSS21/syndata.html#charset\">single quotation marks are not permitted</a>.</p>\n\n<pre><code class=\"language-css bad\">/* Not recommended */\n@import url(\"https://www.google.com/css/maia.css\");\n\nhtml {\n  font-family: \"open sans\", arial, sans-serif;\n}\n</code></pre>\n\n<pre><code class=\"language-css good\">/* Recommended */\n@import url(https://www.google.com/css/maia.css);\n\nhtml {\n  font-family: 'open sans', arial, sans-serif;\n}\n</code></pre>\n\n<h3 id=\"CSS_Meta_Rules\" class=\"numbered\">CSS Meta Rules</h3>\n\n<h4 id=\"Section_Comments\" class=\"numbered\">Section Comments</h4>\n\n<p>Group sections by a section comment (optional).</p>\n\n<p>If possible, group style sheet sections together by using comments. Separate\nsections with new lines.</p>\n\n<pre><code class=\"language-css good\">/* Header */\n\n.adw-header {}\n\n/* Footer */\n\n.adw-footer {}\n\n/* Gallery */\n\n.adw-gallery {}\n</code></pre>\n\n<h2 id=\"Parting_Words\">Parting Words</h2>\n\n<p><em>Be consistent.</em></p>\n\n<p>If you’re editing code, take a few minutes to look at the code around you and\ndetermine its style. If they use spaces around all their arithmetic operators,\nyou should too. If their comments have little boxes of hash marks around them,\nmake your comments have little boxes of hash marks around them too.</p>\n\n<p>The point of having style guidelines is to have a common vocabulary of coding so\npeople can concentrate on what you’re saying rather than on how you’re saying\nit. We present global style rules here so people know the vocabulary, but local\nstyle is also important. If code you add to a file looks drastically different\nfrom the existing code around it, it throws readers out of their rhythm when\nthey go to read it. Avoid this.</p>\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "htmlcssguide.xml",
    "content": "<?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google HTML/CSS Style Guide\">\n  <p>\n    The style guide has moved to\n    <a href=\"htmlcssguide.html\">htmlcssguide.html</a>\n  </p>\n</GUIDE>\n"
  },
  {
    "path": "include/jsguide.js",
    "content": "window.initStyleGuide = function(init) {\n  // Runs the callback on every element matched by the query selector.\n  function find(querySelector, callback) {\n    var elements = [].slice.call(document.querySelectorAll(querySelector));\n    for (var i = 0; i < elements.length; i++) {\n      callback(elements[i]);\n    }\n  }\n  // Add the tocDiv at the top.\n  var title = document.getElementsByTagName('h1')[0];\n  var toc = document.createElement('div');\n  toc.id = 'tocDiv';\n  toc.className = 'vertical_toc';\n  title.parentNode.insertBefore(toc, title.nextSibling);\n\n  // If a paragraph starts with (e.g.) \"Note:\" or \"Tip:\" then add\n  // that \"callout class\" to its element.\n  find('p', function(paragraph) {\n    var match = /^([a-z]+):/i.exec(paragraph.textContent);\n    if (match) {\n      paragraph.classList.add(match[1].toLowerCase());\n    }\n  });\n\n  // Fill in text for intra-document links, ensuring that links\n  // remain up-to-date even if sections are moved or renumbered.\n  // This triggers on any link with \"??\" as its text and a URL\n  // starting with \"#\", and the filled-in text is exactly the same\n  // as the text of the referenced section heading.\n  find('a[href^=\"#\"]', function(link) {\n    var href = link.getAttribute('href');\n    var heading = document.getElementById(href.substring(1));\n    // Fill in link text with heading title\n    if (heading && link.textContent == '??') {\n      link.textContent = heading.textContent;\n    }\n  });\n\n  // Hoedown renders fenced code blocks incompatibly with what\n  // prettify expects. As a result, prettify doesn't handle them\n  // properly. Fix it by moving the code directly into the pre.\n  find('pre > code', function(code) {\n    var pre = code.parentElement;\n    // Internal HTML/CSS & TS style guides do not use prettyprint.\n    if (code.classList.contains('language-css') ||\n        code.classList.contains('language-django') ||\n        code.classList.contains('language-html') ||\n        code.classList.contains('language-ts')) {\n      code.classList.add('prettyprint');\n    }\n    pre.className = code.className;\n    pre.innerHTML = code.innerHTML;\n  });\n\n  // Run the normal init function.\n  init();\n\n  // Call the pretty-printer after we've fixed up the code blocks.\n  var pretty = document.createElement('script');\n  pretty.src = 'https://cdn.jsdelivr.net/gh/google/code-prettify@master/' +\n      'loader/run_prettify.js';\n  document.body.appendChild(pretty);\n}.bind(null, window.initStyleGuide);\n"
  },
  {
    "path": "include/styleguide.css",
    "content": "/* General CSS */\n\nbody {\n  background-color: #fff;\n  color: #333;\n  font-family: sans-serif;\n  font-size: 10pt;\n  margin-right: 100px;\n  margin-left: 100px;\n}\n\nh1 {\n  text-align: center;\n  font-size: 18pt;\n}\n\nh1, h2, h3, h4, h5, h6 {\n  color: #06c;\n  margin-top: 2em;\n  margin-bottom: 1em;\n  padding: 25px;\n  font-weight:bold;\n}\n\nh2,\nh3,\nh4,\nh5,\nh6 {\n  margin-top:1.5em;\n  margin-bottom:.75em;\n}\n\nh1 {font-size:200%;}\nh2 {font-size:167%;}\nh3 {font-size:133%;}\nh4 {font-size:120%;}\nh5 {font-size:110%;}\n\n\ntable {\n  border: 1px solid #bbb;\n  border-spacing: 0;\n  border-collapse: collapse;\n  margin: 0 0 1.5em;\n  vertical-align: middle;\n  width: 100%\n}\n\ntd, th {\n  border: 1px solid #ccc;\n  padding: 2px 12px;\n  font-size: 10pt;\n}\n\ncode, samp, var {\n  background-color:#FAFAFA;\n  white-space: nowrap\n}\n\npre {\n  background-color: #e9e9e9;\n  color: #333;\n  border-color: #f9f9f9;\n  border-style: solid;\n  border-width: 1px 1px 1px 5px;\n  overflow: auto;\n  padding: 6px 12px;\n}\n\npre.prettyprint {\n  padding:6px 10px !important;\n  border:1px solid #bbb !important;\n}\n\npre.bad, pre.badcode {\n  background-color: #ffe6d8;\n  border-color: #fff0f0;\n  color: #c00;\n}\n\npre.good, pre.goodcode {\n  background-color: #e8fff6;\n  color: #060;\n  border-color: #f0fff0;\n}\n\nhr {\n  margin-top: 3.5em;\n  border-width: 1px;\n  color: #fff;\n}\n\n/* TOC CSS */\n\ntable.columns {\n  border: none;\n}\n\ntd.two_columns {\n  -webkit-column-count: 2;\n  column-count: 2;\n}\n\n.toc_category {\n  font-size: 10pt;\n  padding-top: 1em;\n  padding-bottom: 1em;\n  border-left-width: 2px;\n  border-right-width: 2px;\n  border-color: grey;\n}\n\n.toc_stylepoint {\n  font-size: 10pt;\n  padding-top: 1em;\n  padding-bottom: 1em;\n}\n\nli.toc_entry {\n  padding-right: 1em;\n  display: inline;\n  list-style-type: none;\n}\n\n/*\n * This space is required to trigger the linewrap on the links\n * at href boundaries\n */\nli.toc_entry::after {\n    content: \" \";\n  }\n\nli.toc_entry a {\n  white-space: nowrap;\n}\n\n/* Horizontal TOC */\n.toc td, .toc th {\n  border-width: 1px 5px;\n  overflow: hidden;\n}\n\n/* Vertical TOC */\n\n.toc td.two_columns {\n  border-width: 0px;\n}\n\n/* Special Sections */\n\naddress {\n  text-align: right;\n}\n\n.revision {\n  text-align: right;\n}\n\n.headerbox {\n  margin-left: 50%;\n  font-size: 75%;\n}\n\n.legend {\n  padding-top: 1em;\n  margin-left: 50%;\n  font-size: 10pt;\n}\n\n.link_button {\n  float: left;\n  display: none;\n  background-color: #f8f8ff;\n  border-color: #f0f0ff;\n  border-style: solid;\n  border-width: 1px;\n  font-size: 75%;\n  margin-top: 0;\n  margin-left: -50px;\n  padding: 24px;\n  border-radius: 3px;\n  -webkit-border-radius: 3px;\n  -moz-border-radius: 3px;\n}\n\n.ignoreLink {\n  padding: 0px;\n}\n\n.divider{\n    width:5px;\n    height:auto;\n    display:inline-block;\n}\n\n/* Style Guide semantic CSS */\n\n.summary {\n  margin-top: 1em;\n  margin-bottom: 1em;\n}\n\n.stylebody {\n  margin-top: 1em;\n  margin-bottom: 1em;\n}\n\n.stylepoint_section {\n  display: block;\n  margin-bottom: 1em;\n  font-family: sans-serif;\n  font-weight: bold;\n}\n\n.stylepoint_subsection {\n  display: block;\n  margin-bottom: 1em;\n}\n\n.stylepoint_subsubsection {\n  display: block;\n  margin-bottom: 1em;\n}\n\n.definition:before {\n  content: \"Definition: \";\n  font-weight: bold;\n  display: block;\n  margin-bottom: 1em;\n}\n\n.pros:before {\n  content: \"Pros: \";\n  font-weight: bold;\n  display: block;\n  margin-bottom: 1em;\n}\n\n.cons:before {\n  content: \"Cons: \";\n  font-weight: bold;\n  display: block;\n  margin-bottom: 1em;\n}\n\n.decision:before {\n  content: \"Decision: \";\n  font-weight: bold;\n  display: block;\n  margin-bottom: 1em;\n}\n\n.exception:before {\n  content: \"Exception: \";\n  font-weight: bold;\n  display: block;\n  margin-bottom: 1em;\n}\n\n.note:before {\n  content: \"Note: \";\n  font-weight: bold;\n  display: block;\n  margin-bottom: 1em;\n}\n"
  },
  {
    "path": "include/styleguide.js",
    "content": "TocTypeEnum = {\n  VERTICAL: 1,\n  HORIZONTAL: 2\n};\n\nfunction CreateTOC(tocElement) {\n\n  // Find the toc element DIV. We'll place our TOC there.\n  var toc = document.getElementById(tocElement);\n\n  var tocTypeClass = toc.className;\n  var tocType;\n\n  switch (tocTypeClass) {\n      case 'horizontal_toc':\n        tocType = TocTypeEnum.HORIZONTAL;\n        break;\n      case 'vertical_toc':\n        tocType = TocTypeEnum.VERTICAL;\n        break;\n      default:\n        tocType = TocTypeEnum.VERTICAL;\n        break;\n  }\n\n  // If toc_levels is defined, set headingLevels to it.\n  // Otherwise, use default value of \"h2,h3\"\n  var headingLevels;\n  if (typeof toc_levels === 'undefined') {\n    headingLevels = 'h2,h3';\n  } else {\n\n  }\n\n  // Collect all section heading elements in an array\n  var headings = document.querySelectorAll(headingLevels);\n\n  // Add TOC title elements\n  var tocHeadingDiv = document.createElement('div');\n  toc.appendChild(tocHeadingDiv);\n  tocHeadingDiv.className = 'toc_title';\n  var tocHeading = document.createElement('h3');\n  toc.appendChild(tocHeading);\n  tocHeading.className = 'ignoreLink';\n  tocHeading.id = 'toc';\n  var tocText = document.createTextNode('Table of Contents');\n  tocHeading.appendChild(tocText);\n\n  // Add table and tbody\n  var tocTable = document.createElement('table');\n  if (tocType == TocTypeEnum.VERTICAL) {\n    tocTable.className = 'columns';\n  }\n  toc.appendChild(tocTable);\n\n  var tbody_element = document.createElement('tbody');\n  tbody_element.setAttribute('valign', 'top');\n  tbody_element.className = 'toc';\n  tocTable.appendChild(tbody_element);\n\n  // Get the highest level heading\n  var firstHeading = headings[0];\n  var masterLevel = parseInt(headingLevels.charAt(1));\n\n  // Get the lowest heading level\n  var lowestLevel = parseInt(headingLevels.charAt(headingLevels - 1));\n\n  switch (tocType) {\n    case TocTypeEnum.HORIZONTAL:\n        CreateHorizontalTOC(headings, masterLevel, lowestLevel, tbody_element);\n        break;\n    case TocTypeEnum.VERTICAL:\n        CreateVerticalTOC(headings, masterLevel, lowestLevel, tbody_element);\n        break;\n    default:\n   }\n}\n\nfunction CreateHorizontalTOC(\n             headings, masterLevel, lowestLevel, tbody_element) {\n\n  // Initialize the header counter\n  var h = 0;\n  var ignoreChildren = false;\n\n  while (h < headings.length) {\n    // Get current heading\n    var heading = headings[h];\n\n    // Get the current heading level\n    var level = parseInt(heading.tagName.charAt(1));\n\n    if (isNaN(level) || level < 1 || level > lowestLevel) continue;\n\n    // If level is a masterLevel, make it a TOC parent category\n    if ((level == masterLevel) && (!hasClass(heading, 'ignoreLink'))) {\n      toc_current_row = AddTOCMaster(tbody_element, heading);\n      ignoreChildren = false;\n    }\n\n    if ((level == masterLevel) && (hasClass(heading, 'ignoreLink'))) {\n      ignoreChildren = true;\n    }\n\n    if ((level != masterLevel) && (!ignoreChildren)) {\n      AddTOCElements(toc_current_row, heading);\n    }\n\n    // Advance the header counter\n    h++;\n  }\n}\n\n// Adds a master Table of Content heading\nfunction AddTOCMaster(tocTable, heading) {\n\n  // Add the table row scaffolding\n  var toc_tr = document.createElement('tr');\n  tocTable.appendChild(toc_tr);\n  toc_tr.setAttribute('valign', 'top');\n  var toc_tr_td = document.createElement('td');\n  toc_tr.appendChild(toc_tr_td);\n  var toc_category = document.createElement('div');\n  toc_tr_td.appendChild(toc_category);\n  toc_category.className = 'toc_category';\n\n  // Create the link to this header\n  var link = document.createElement('a');\n  link.href = '#' + heading.id;       // Create the anchor link\n  link.textContent = heading.textContent; // Link text is same as heading\n  toc_category.appendChild(link);\n\n  // Add the container table cell for its children\n  var toc_td = document.createElement('td');\n  toc_tr.appendChild(toc_td);\n  var toc_td_div = document.createElement('div');\n  toc_td_div.className = 'toc_stylepoint';\n  toc_td.appendChild(toc_td_div);\n\n  return (toc_td_div);\n}\n\n// Adds Table of Contents element to a master heading as children\nfunction AddTOCElements(toc_div, heading) {\n\n  if (heading.offsetParent === null) {\n    // The element is currently hidden, so don't create a TOC entry\n  } else {\n    // Create the list item element\n    var toc_list_element = document.createElement('li');\n    toc_list_element.className = 'toc_entry';\n    toc_div.appendChild(toc_list_element);\n\n    // Create the link to this header\n    var link = document.createElement('a');\n    link.href = '#' + heading.id;       // Create the anchor link\n    link.textContent = heading.textContent; // Link text is same as heading\n    toc_list_element.appendChild(link);\n  }\n}\n\nfunction CreateVerticalTOC(headings, masterLevel, lowestLevel, tbody_element) {\n\n  // Create the Column scaffolding\n  var toc_tr = document.createElement('tr');\n  tbody_element.appendChild(toc_tr);\n  var toc_tr_td = document.createElement('td');\n  toc_tr_td.className = 'two_columns';\n  toc_tr.appendChild(toc_tr_td);\n\n\n  // Initialize the header counter and the current row\n  var h = 0;\n  var toc_current_col = null;\n  var ignoreChildren = false;\n\n  while (h < headings.length) {\n    // Get current heading\n    var heading = headings[h];\n\n    // Get the current heading level\n    var level = parseInt(heading.tagName.charAt(1));\n\n    if (isNaN(level) || level < 1 || level > lowestLevel) continue;\n\n    // If level is a masterLevel, make it a TOC parent category\n    if ((level == masterLevel) && (!hasClass(heading, 'ignoreLink'))) {\n      if (heading.offsetParent === null) {\n        // The element is currently hidden, so don't create a TOC entry\n      } else {\n        var td_dl = document.createElement('dl');\n        toc_tr_td.appendChild(td_dl);\n        var td_dt = document.createElement('dt');\n        td_dl.appendChild(td_dt);\n        toc_current_col = td_dl;\n\n        // Create the link to this header\n        var link = document.createElement('a');\n        link.href = '#' + heading.id;       // Create the anchor link\n        link.textContent = heading.textContent; // Link text is same as heading\n        td_dt.appendChild(link);\n        ignoreChildren = false;\n      }\n    }\n\n    // If level is a masterLevel but it's specified to ignore links, skip it\n    // and its children.\n    if ((level == masterLevel) && (hasClass(heading, 'ignoreLink'))) {\n      ignoreChildren = true;\n    }\n\n    if ((level != masterLevel) && (!ignoreChildren)) {\n      if (heading.offsetParent === null) {\n        // The element is currently hidden, so don't create a TOC entry\n      } else {\n        var td_dd = document.createElement('dd');\n        toc_current_col.appendChild(td_dd);\n        // Create the link to this header\n        var link = document.createElement('a');\n        link.href = '#' + heading.id;       // Create the anchor link\n        link.textContent = heading.textContent; // Link text is same as heading\n        td_dd.appendChild(link);\n      }\n    }\n\n    // Advance the header counter\n    h++;\n  }\n}\n\n/*\n * Utility function for finding elements with a given\n * class.\n */\nfunction hasClass(element, cls) {\n    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;\n}\n\n/*\n * Linkify all h2 through h4 headers, except for those marked\n * \"ignoreLink\"\n */\n\n// Add the link image to the element.\nfunction LinkifyHeader(header, fileName, sizePixels) {\n  var link = document.createElement('a');\n  link.href = '#' + header.id;\n  link.setAttribute('alt', 'link to ' + header.id);\n  link.innerHTML =\n      '<img src=\"include/' + fileName + '\"' +\n      ' width=' + sizePixels +\n      ' height=' + sizePixels +\n      ' style=\"float:left;position:relative;bottom:5px;\">';\n  header.appendChild(link);\n}\n\n// Find all elements of the given tag and linkify if\n// they don't have 'ignoreLink' in their class.\nfunction LinkifyHeadersForTag(tagName) {\n  var headers = document.getElementsByTagName(tagName);\n  var header;\n  for (var j = 0; j != headers.length; j++) {\n    header = headers[j];\n    if (!hasClass(header, 'ignoreLink') && ('id' in header)) {\n      if (header.id != '') {\n        LinkifyHeader(header, 'link.png', 21);\n        header.style.left = '-46px';\n        header.style.position = 'relative';\n      }\n    }\n  }\n}\n\n// Linkify all h2, h3, and h4s. h1s are titles.\nfunction LinkifyHeaders() {\n  LinkifyHeadersForTag('h2');\n  LinkifyHeadersForTag('h3');\n  LinkifyHeadersForTag('h4');\n}\n\n/*\n * Initialize the style guide by showing all internal\n * elements and then linkifying the headers.\n */\n\nfunction initStyleGuide() {\n  LinkifyHeaders();\n  CreateTOC('tocDiv');\n}\n"
  },
  {
    "path": "intellij-java-google-style.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<code_scheme name=\"GoogleStyle\">\n  <option name=\"OTHER_INDENT_OPTIONS\">\n    <value>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n      <option name=\"USE_TAB_CHARACTER\" value=\"false\" />\n      <option name=\"SMART_TABS\" value=\"false\" />\n      <option name=\"LABEL_INDENT_SIZE\" value=\"0\" />\n      <option name=\"LABEL_INDENT_ABSOLUTE\" value=\"false\" />\n      <option name=\"USE_RELATIVE_INDENTS\" value=\"false\" />\n    </value>\n  </option>\n  <option name=\"INSERT_INNER_CLASS_IMPORTS\" value=\"true\" />\n  <option name=\"CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND\" value=\"999\" />\n  <option name=\"NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND\" value=\"999\" />\n  <option name=\"PACKAGES_TO_USE_IMPORT_ON_DEMAND\">\n    <value />\n  </option>\n  <option name=\"IMPORT_LAYOUT_TABLE\">\n    <value>\n      <package name=\"\" withSubpackages=\"true\" static=\"true\" />\n      <emptyLine />\n      <package name=\"\" withSubpackages=\"true\" static=\"false\" />\n    </value>\n  </option>\n  <option name=\"RIGHT_MARGIN\" value=\"100\" />\n  <option name=\"JD_ALIGN_PARAM_COMMENTS\" value=\"false\" />\n  <option name=\"JD_ALIGN_EXCEPTION_COMMENTS\" value=\"false\" />\n  <option name=\"JD_P_AT_EMPTY_LINES\" value=\"false\" />\n  <option name=\"JD_KEEP_EMPTY_PARAMETER\" value=\"false\" />\n  <option name=\"JD_KEEP_EMPTY_EXCEPTION\" value=\"false\" />\n  <option name=\"JD_KEEP_EMPTY_RETURN\" value=\"false\" />\n  <option name=\"KEEP_CONTROL_STATEMENT_IN_ONE_LINE\" value=\"false\" />\n  <option name=\"KEEP_BLANK_LINES_BEFORE_RBRACE\" value=\"0\" />\n  <option name=\"KEEP_BLANK_LINES_IN_CODE\" value=\"1\" />\n  <option name=\"BLANK_LINES_AFTER_CLASS_HEADER\" value=\"0\" />\n  <option name=\"ALIGN_MULTILINE_PARAMETERS\" value=\"false\" />\n  <option name=\"ALIGN_MULTILINE_FOR\" value=\"false\" />\n  <option name=\"CALL_PARAMETERS_WRAP\" value=\"1\" />\n  <option name=\"METHOD_PARAMETERS_WRAP\" value=\"1\" />\n  <option name=\"EXTENDS_LIST_WRAP\" value=\"1\" />\n  <option name=\"THROWS_KEYWORD_WRAP\" value=\"1\" />\n  <option name=\"METHOD_CALL_CHAIN_WRAP\" value=\"1\" />\n  <option name=\"BINARY_OPERATION_WRAP\" value=\"1\" />\n  <option name=\"BINARY_OPERATION_SIGN_ON_NEXT_LINE\" value=\"true\" />\n  <option name=\"TERNARY_OPERATION_WRAP\" value=\"1\" />\n  <option name=\"TERNARY_OPERATION_SIGNS_ON_NEXT_LINE\" value=\"true\" />\n  <option name=\"FOR_STATEMENT_WRAP\" value=\"1\" />\n  <option name=\"ARRAY_INITIALIZER_WRAP\" value=\"1\" />\n  <option name=\"WRAP_COMMENTS\" value=\"true\" />\n  <option name=\"IF_BRACE_FORCE\" value=\"3\" />\n  <option name=\"DOWHILE_BRACE_FORCE\" value=\"3\" />\n  <option name=\"WHILE_BRACE_FORCE\" value=\"3\" />\n  <option name=\"FOR_BRACE_FORCE\" value=\"3\" />\n  <option name=\"SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE\" value=\"true\" />\n  <AndroidXmlCodeStyleSettings>\n    <option name=\"USE_CUSTOM_SETTINGS\" value=\"true\" />\n    <option name=\"LAYOUT_SETTINGS\">\n      <value>\n        <option name=\"INSERT_BLANK_LINE_BEFORE_TAG\" value=\"false\" />\n      </value>\n    </option>\n  </AndroidXmlCodeStyleSettings>\n  <JSCodeStyleSettings>\n    <option name=\"INDENT_CHAINED_CALLS\" value=\"false\" />\n  </JSCodeStyleSettings>\n  <Python>\n    <option name=\"USE_CONTINUATION_INDENT_FOR_ARGUMENTS\" value=\"true\" />\n  </Python>\n  <TypeScriptCodeStyleSettings>\n    <option name=\"INDENT_CHAINED_CALLS\" value=\"false\" />\n  </TypeScriptCodeStyleSettings>\n  <XML>\n    <option name=\"XML_ALIGN_ATTRIBUTES\" value=\"false\" />\n    <option name=\"XML_LEGACY_SETTINGS_IMPORTED\" value=\"true\" />\n  </XML>\n  <codeStyleSettings language=\"CSS\">\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"ECMA Script Level 4\">\n    <option name=\"KEEP_BLANK_LINES_IN_CODE\" value=\"1\" />\n    <option name=\"ALIGN_MULTILINE_PARAMETERS\" value=\"false\" />\n    <option name=\"ALIGN_MULTILINE_FOR\" value=\"false\" />\n    <option name=\"CALL_PARAMETERS_WRAP\" value=\"1\" />\n    <option name=\"METHOD_PARAMETERS_WRAP\" value=\"1\" />\n    <option name=\"EXTENDS_LIST_WRAP\" value=\"1\" />\n    <option name=\"BINARY_OPERATION_WRAP\" value=\"1\" />\n    <option name=\"BINARY_OPERATION_SIGN_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"TERNARY_OPERATION_WRAP\" value=\"1\" />\n    <option name=\"TERNARY_OPERATION_SIGNS_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"FOR_STATEMENT_WRAP\" value=\"1\" />\n    <option name=\"ARRAY_INITIALIZER_WRAP\" value=\"1\" />\n    <option name=\"IF_BRACE_FORCE\" value=\"3\" />\n    <option name=\"DOWHILE_BRACE_FORCE\" value=\"3\" />\n    <option name=\"WHILE_BRACE_FORCE\" value=\"3\" />\n    <option name=\"FOR_BRACE_FORCE\" value=\"3\" />\n    <option name=\"PARENT_SETTINGS_INSTALLED\" value=\"true\" />\n  </codeStyleSettings>\n  <codeStyleSettings language=\"HTML\">\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"JAVA\">\n    <option name=\"KEEP_CONTROL_STATEMENT_IN_ONE_LINE\" value=\"false\" />\n    <option name=\"KEEP_BLANK_LINES_IN_CODE\" value=\"1\" />\n    <option name=\"BLANK_LINES_AFTER_CLASS_HEADER\" value=\"1\" />\n    <option name=\"ALIGN_MULTILINE_PARAMETERS\" value=\"false\" />\n    <option name=\"ALIGN_MULTILINE_RESOURCES\" value=\"false\" />\n    <option name=\"ALIGN_MULTILINE_FOR\" value=\"false\" />\n    <option name=\"CALL_PARAMETERS_WRAP\" value=\"1\" />\n    <option name=\"METHOD_PARAMETERS_WRAP\" value=\"1\" />\n    <option name=\"EXTENDS_LIST_WRAP\" value=\"1\" />\n    <option name=\"THROWS_KEYWORD_WRAP\" value=\"1\" />\n    <option name=\"METHOD_CALL_CHAIN_WRAP\" value=\"1\" />\n    <option name=\"BINARY_OPERATION_WRAP\" value=\"1\" />\n    <option name=\"BINARY_OPERATION_SIGN_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"TERNARY_OPERATION_WRAP\" value=\"1\" />\n    <option name=\"TERNARY_OPERATION_SIGNS_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"FOR_STATEMENT_WRAP\" value=\"1\" />\n    <option name=\"ARRAY_INITIALIZER_WRAP\" value=\"1\" />\n    <option name=\"WRAP_COMMENTS\" value=\"true\" />\n    <option name=\"IF_BRACE_FORCE\" value=\"3\" />\n    <option name=\"DOWHILE_BRACE_FORCE\" value=\"3\" />\n    <option name=\"WHILE_BRACE_FORCE\" value=\"3\" />\n    <option name=\"FOR_BRACE_FORCE\" value=\"3\" />\n    <option name=\"PARENT_SETTINGS_INSTALLED\" value=\"true\" />\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"JSON\">\n    <indentOptions>\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"JavaScript\">\n    <option name=\"RIGHT_MARGIN\" value=\"80\" />\n    <option name=\"KEEP_BLANK_LINES_IN_CODE\" value=\"1\" />\n    <option name=\"ALIGN_MULTILINE_PARAMETERS\" value=\"false\" />\n    <option name=\"ALIGN_MULTILINE_FOR\" value=\"false\" />\n    <option name=\"CALL_PARAMETERS_WRAP\" value=\"1\" />\n    <option name=\"METHOD_PARAMETERS_WRAP\" value=\"1\" />\n    <option name=\"BINARY_OPERATION_WRAP\" value=\"1\" />\n    <option name=\"BINARY_OPERATION_SIGN_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"TERNARY_OPERATION_WRAP\" value=\"1\" />\n    <option name=\"TERNARY_OPERATION_SIGNS_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"FOR_STATEMENT_WRAP\" value=\"1\" />\n    <option name=\"ARRAY_INITIALIZER_WRAP\" value=\"1\" />\n    <option name=\"IF_BRACE_FORCE\" value=\"3\" />\n    <option name=\"DOWHILE_BRACE_FORCE\" value=\"3\" />\n    <option name=\"WHILE_BRACE_FORCE\" value=\"3\" />\n    <option name=\"FOR_BRACE_FORCE\" value=\"3\" />\n    <option name=\"PARENT_SETTINGS_INSTALLED\" value=\"true\" />\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"PROTO\">\n    <option name=\"RIGHT_MARGIN\" value=\"80\" />\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"2\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"protobuf\">\n    <option name=\"RIGHT_MARGIN\" value=\"80\" />\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"2\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"Python\">\n    <option name=\"KEEP_BLANK_LINES_IN_CODE\" value=\"1\" />\n    <option name=\"RIGHT_MARGIN\" value=\"80\" />\n    <option name=\"ALIGN_MULTILINE_PARAMETERS\" value=\"false\" />\n    <option name=\"PARENT_SETTINGS_INSTALLED\" value=\"true\" />\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"SASS\">\n    <indentOptions>\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"SCSS\">\n    <indentOptions>\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"TypeScript\">\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n  </codeStyleSettings>\n  <codeStyleSettings language=\"XML\">\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"2\" />\n      <option name=\"TAB_SIZE\" value=\"2\" />\n    </indentOptions>\n    <arrangement>\n      <rules>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>xmlns:android</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>^$</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>xmlns:.*</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>^$</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:id</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>style</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>^$</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>^$</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:.*Style</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_width</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_height</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_weight</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_margin</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_marginTop</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_marginBottom</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_marginStart</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_marginEnd</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_marginLeft</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_marginRight</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:layout_.*</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:padding</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:paddingTop</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:paddingBottom</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:paddingStart</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:paddingEnd</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:paddingLeft</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*:paddingRight</NAME>\n                <XML_ATTRIBUTE />\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*</NAME>\n                <XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*</NAME>\n                <XML_NAMESPACE>http://schemas.android.com/apk/res-auto</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*</NAME>\n                <XML_NAMESPACE>http://schemas.android.com/tools</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n        <section>\n          <rule>\n            <match>\n              <AND>\n                <NAME>.*</NAME>\n                <XML_NAMESPACE>.*</XML_NAMESPACE>\n              </AND>\n            </match>\n            <order>BY_NAME</order>\n          </rule>\n        </section>\n      </rules>\n    </arrangement>\n  </codeStyleSettings>\n  <Objective-C>\n    <option name=\"INDENT_NAMESPACE_MEMBERS\" value=\"0\" />\n    <option name=\"INDENT_C_STRUCT_MEMBERS\" value=\"2\" />\n    <option name=\"INDENT_CLASS_MEMBERS\" value=\"2\" />\n    <option name=\"INDENT_VISIBILITY_KEYWORDS\" value=\"1\" />\n    <option name=\"INDENT_INSIDE_CODE_BLOCK\" value=\"2\" />\n    <option name=\"KEEP_STRUCTURES_IN_ONE_LINE\" value=\"true\" />\n    <option name=\"FUNCTION_PARAMETERS_WRAP\" value=\"5\" />\n    <option name=\"FUNCTION_CALL_ARGUMENTS_WRAP\" value=\"5\" />\n    <option name=\"TEMPLATE_CALL_ARGUMENTS_WRAP\" value=\"5\" />\n    <option name=\"TEMPLATE_CALL_ARGUMENTS_ALIGN_MULTILINE\" value=\"true\" />\n    <option name=\"ALIGN_INIT_LIST_IN_COLUMNS\" value=\"false\" />\n    <option name=\"SPACE_BEFORE_SUPERCLASS_COLON\" value=\"false\" />\n  </Objective-C>\n  <Objective-C-extensions>\n    <option name=\"GENERATE_INSTANCE_VARIABLES_FOR_PROPERTIES\" value=\"ASK\" />\n    <option name=\"RELEASE_STYLE\" value=\"IVAR\" />\n    <option name=\"TYPE_QUALIFIERS_PLACEMENT\" value=\"BEFORE\" />\n    <file>\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Import\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Macro\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Typedef\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Enum\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Constant\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Global\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Struct\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"FunctionPredecl\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Function\" />\n    </file>\n    <class>\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Property\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"Synthesize\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"InitMethod\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"StaticMethod\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"InstanceMethod\" />\n      <option name=\"com.jetbrains.cidr.lang.util.OCDeclarationKind\" value=\"DeallocMethod\" />\n    </class>\n    <extensions>\n      <pair source=\"cc\" header=\"h\" />\n      <pair source=\"c\" header=\"h\" />\n    </extensions>\n  </Objective-C-extensions>\n  <codeStyleSettings language=\"ObjectiveC\">\n    <option name=\"RIGHT_MARGIN\" value=\"80\" />\n    <option name=\"KEEP_BLANK_LINES_BEFORE_RBRACE\" value=\"1\" />\n    <option name=\"BLANK_LINES_BEFORE_IMPORTS\" value=\"0\" />\n    <option name=\"BLANK_LINES_AFTER_IMPORTS\" value=\"0\" />\n    <option name=\"BLANK_LINES_AROUND_CLASS\" value=\"0\" />\n    <option name=\"BLANK_LINES_AROUND_METHOD\" value=\"0\" />\n    <option name=\"BLANK_LINES_AROUND_METHOD_IN_INTERFACE\" value=\"0\" />\n    <option name=\"ALIGN_MULTILINE_BINARY_OPERATION\" value=\"false\" />\n    <option name=\"BINARY_OPERATION_SIGN_ON_NEXT_LINE\" value=\"true\" />\n    <option name=\"FOR_STATEMENT_WRAP\" value=\"1\" />\n    <option name=\"ASSIGNMENT_WRAP\" value=\"1\" />\n    <indentOptions>\n      <option name=\"INDENT_SIZE\" value=\"2\" />\n      <option name=\"CONTINUATION_INDENT_SIZE\" value=\"4\" />\n    </indentOptions>\n  </codeStyleSettings>\n</code_scheme>\n"
  },
  {
    "path": "javaguide.css",
    "content": "table {\n  border-collapse: collapse;\n}\n\ntd,\nth {\n  border: 1px solid #ccc;\n  padding: 2px 12px;\n  font-size: 10pt;\n}\n\ncode,\nsamp,\nvar {\n  color: #060;\n}\n\npre {\n  font-size: 10pt;\n  display: block;\n  color: #060;\n  background-color: #e8fff6;\n  border: 1px solid #f0fff0;\n  border-left-width: 5px;\n  padding: 4px 12px;\n}\n\npre.badcode {\n  color: #c00;\n  background-color: #ffe6d8;\n  border-color: #fff0f0;\n}\n\nhr {\n  margin-top: 3.5em;\n  border-width: 1px;\n  color: #fff;\n}\n\nhtml {\n  margin: 2em 10% 0;\n  padding: 0;\n}\n\n.bp-reset-element,\nbody,\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nmenu,\nnav,\nsection,\nsummary,\nblockquote,\nq,\nth,\ntd,\ncaption,\ntable,\ndiv,\nspan,\nobject,\niframe,\np,\npre,\na,\nabbr,\nacronym,\naddress,\ncode,\ndel,\ndfn,\nem,\nimg,\ndl,\ndt,\ndd,\nol,\nul,\nli,\nfieldset,\nform,\nlabel,\nlegend,\ncaption,\ntbody,\ntfoot,\nthead,\ntr {\n  margin: 0;\n  padding: 0;\n  border: 0;\n  font-weight: inherit;\n  font-style: inherit;\n  font-size: 100%;\n  font-family: inherit;\n  vertical-align: baseline;\n}\n\nbody {\n  font-family: 'Arial', sans-serif;\n  font-size: 81.25%;\n  color: #222;\n  background-color: #fff;\n  line-height: 1.67;\n  overflow: auto;\n}\n\n.change {\n  text-align: right;\n  margin-bottom: 1em;\n}\n\nem {\n  font-style: italic;\n}\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n  font-weight: bold;\n}\n\nh1 {\n  margin-bottom: 0.5em;\n  text-align: center;\n}\n\nh2,\nh3,\nh4,\nh5,\nh6 {\n  margin-top: 1.5em;\n  margin-bottom: 0.75em;\n}\n\nh1 {\n  font-size: 200%;\n}\n\nh2 {\n  font-size: 167%;\n}\n\nh3 {\n  font-size: 133%;\n}\n\nh4 {\n  font-size: 120%;\n}\n\nh5 {\n  font-size: 110%;\n}\n\np {\n  margin: 0 0 1.5em;\n}\n\na[href=''] {\n  cursor: default;\n}\n\nh1 img,\nh2 img,\nh3 img,\nh4 img,\nh5 img,\nh6 img {\n  margin: 0;\n}\n\na img {\n  border: none;\n}\n\npre {\n  margin: 1.5em 0;\n  white-space: pre;\n}\n\npre,\ncode,\nkbd,\ntt {\n  font: 1em 'Droid Sans Mono', monospace;\n  line-height: 1.5;\n}\n\ndl {\n  margin: 0 0 1.5em;\n}\n\ndl dt {\n  font-weight: bold;\n}\n\ndd {\n  margin-left: 1.5em;\n}\n\ndd.toc3 {\n  margin-left: 3em;\n}\n\nhr {\n  height: 0;\n  border: 0;\n  border-top: 1px solid #ccc;\n  background-color: #ccc;\n}\n\ntable {\n  border: 1px solid #bbb;\n  border-spacing: 0;\n  border-collapse: collapse;\n  margin: 0 0 1.5em;\n  vertical-align: middle;\n  width: 100%;\n}\n\ntable.unlined,\ntable.unlined th,\ntable.unlined tr,\ntable.unlined td {\n  border: 0;\n}\n\nth,\ntd,\ncaption {\n  float: none !important;\n  text-align: left;\n  font-weight: normal;\n  vertical-align: middle;\n  padding: 4px;\n}\n\ncaption {\n  padding: 0;\n}\n\ntd {\n  border: 1px solid #bbb;\n  vertical-align: top;\n}\n\nth {\n  border: 0;\n  border-bottom: 1px solid black;\n  font-weight: bold;\n  background: rgb(229, 236, 249);\n}\n\ntable th code {\n  background-color: inherit;\n  color: inherit;\n}\n\ntable tfoot th {\n  border: 1px solid #bbb;\n}\n\ntfoot {\n  font-style: italic;\n}\n\ncaption {\n  background: #eee;\n}\n\ntable[border='0'] {\n  border: none;\n}\n\ntable[border='0'] > tbody > tr > td,\ntable[border='0'] > tr > td {\n  border: none;\n}\n\ntr.alt td,\ntd.alt {\n  background-color: #efefef;\n}\n\ntable.striped tr:nth-child(even) td,\ntable tr.even td {\n  background: #efefef;\n}\n\ntable.columns {\n  border: none;\n}\n\ntable.columns > tbody > tr > td,\ntable.columns > tr > td {\n  border: none;\n  padding: 0 3em 0 0;\n}\n\ntable.columns > tbody > tr > td:last-child,\ntable.columns > tr > td:last-child {\n  border: none;\n  padding: 0;\n}\n\nul,\nol {\n  margin: 0 1.5em 1.5em 0;\n  padding-left: 2em;\n}\n\nli ul,\nli ol {\n  margin: 0;\n}\n\nul {\n  list-style-type: disc;\n}\n\nol {\n  list-style-type: decimal;\n}\n\nul {\n  list-style-type: disc;\n}\n\nul ul {\n  list-style-type: circle;\n}\n\nul ul ul {\n  list-style-type: square;\n}\n\nul.disc {\n  list-style-type: disc;\n}\n\nul.circle {\n  list-style-type: circle;\n}\n\nul.square {\n  list-style-type: square;\n}\n\nol {\n  list-style-type: decimal;\n}\n\nol ol {\n  list-style-type: lower-alpha;\n}\n\nol ol ol {\n  list-style-type: lower-roman;\n}\n\nol ul {\n  list-style-type: circle;\n}\n\nol.decimal {\n  list-style-type: decimal;\n}\n\nol.upper-alpha {\n  list-style-type: upper-alpha;\n}\n\nol.lower-alpha {\n  list-style-type: lower-alpha;\n}\n\nol.upper-roman {\n  list-style-type: upper-roman;\n}\n\nol.lower-roman {\n  list-style-type: lower-roman;\n}\n\nol.nolist,\nul.nolist {\n  padding-left: 0;\n  list-style-image: none;\n  list-style-type: none;\n  margin-left: 0;\n}\n\n.center {\n  text-align: center;\n}\n\ncode,\nkbd,\npre {\n  color: #090;\n}\n\nkbd {\n  font-weight: bold;\n}\n\ntable.striped code {\n  background-color: inherit;\n}\n\npre {\n  padding: 6px 10px;\n  background-color: #fafafa;\n  border: 1px solid #bbb;\n  overflow: auto;\n}\n\npre.prettyprint {\n  padding: 6px 10px !important;\n  border: 1px solid #bbb !important;\n}\n\ncode.bad,\ncode.badcode {\n  color: magenta;\n}\n\npre.bad,\npre.badcode {\n  background-color: #ffe6d8;\n  border-top: 1px inset #a03;\n  border-left: 1px inset #a03;\n}\n\n.tip {\n  background-color: #fffbd9;\n  padding: 6px 8px 6px 10px;\n  border-left: 6px solid #ffef70;\n}\n\n.note {\n  background-color: #e5ecf9;\n  padding: 6px 8px 6px 10px;\n  border-left: 6px solid #36c;\n}\n\n@media print {\n  .str {\n    color: #060;\n  }\n\n  .kwd {\n    color: #006;\n    font-weight: bold;\n  }\n\n  .com {\n    color: #600;\n    font-style: italic;\n  }\n\n  .typ {\n    color: #404;\n    font-weight: bold;\n  }\n\n  .lit {\n    color: #044;\n  }\n\n  .pun,\n  .opn,\n  .clo {\n    color: #440;\n  }\n\n  .pln {\n    color: #000;\n  }\n\n  .tag {\n    color: #006;\n    font-weight: bold;\n  }\n\n  .atn {\n    color: #404;\n  }\n\n  .atv {\n    color: #060;\n  }\n\n  h1 {\n    font-style: italic;\n  }\n}\n\nol.linenums {\n  margin-top: 0;\n  margin-bottom: 0;\n}\n\ncode {\n  background-color: #fafafa;\n  padding: 0.25em 0.5em;\n  white-space: nowrap;\n}\n\n/* TOC CSS */\n\ntable.columns {\n  border: none;\n}\n\ntd.two_columns {\n  -webkit-column-count: 2;\n  column-count: 2;\n}\n\n.toc_category {\n  font-size: 10pt;\n  padding-top: 1em;\n  padding-bottom: 1em;\n  border-left-width: 2px;\n  border-right-width: 2px;\n  border-color: grey;\n}\n\n.toc_stylepoint {\n  font-size: 10pt;\n  padding-top: 1em;\n  padding-bottom: 1em;\n}\n\nli.toc_entry {\n  padding-right: 1em;\n  display: inline;\n  list-style-type: none;\n}\n\n/*\n * This space is required to trigger the linewrap on the links\n * at href boundaries\n */\nli.toc_entry::after {\n  content: ' ';\n}\n\nli.toc_entry a {\n  white-space: nowrap;\n}\n\n/* Horizontal TOC */\n.toc td,\n.toc th {\n  border-width: 1px 5px;\n  overflow: hidden;\n}\n\n/* Vertical TOC */\n\n.toc td.two_columns {\n  border-width: 0;\n}\n\n/* Numbered sections */\n\nh1 {\n  counter-reset: h2;\n}\n\nh2.numbered {\n  counter-reset: h3;\n}\n\nh3.numbered {\n  counter-reset: h4;\n}\n\nh2.numbered::before {\n  content: counter(h2) ' ';\n  counter-increment: h2;\n}\n\nh3.numbered::before {\n  content: counter(h2) '.' counter(h3) ' ';\n  counter-increment: h3;\n}\n\nh4.numbered::before {\n  content: counter(h2) '.' counter(h3) '.' counter(h4) ' ';\n  counter-increment: h4;\n}\n"
  },
  {
    "path": "javaguide.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Google Java Style Guide</title>\n<link rel=\"stylesheet\" href=\"javaguide.css\">\n<script src=\"include/styleguide.js\"></script>\n<link rel=\"shortcut icon\" href=\"/styleguide/favicon.ico\">\n<script src=\"https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js\"></script>\n</head>\n<body onload=\"initStyleGuide();\">\n<div id=\"content\">\n<h1>Google Java Style Guide</h1>\n<div id=\"tocDiv\" class=\"vertical_toc\"></div>\n\n<div class=\"main_body\">\n<h2 id=\"s1-introduction\">1 Introduction</h2>\n\n<p>This document serves as the <strong>complete</strong> definition of Google's coding standards for\nsource code in the Java™ Programming Language. A Java source file is described as being <em>in\nGoogle Style</em> if and only if it adheres to the rules herein.</p>\n\n\n\n<p>Like other programming style guides, the issues covered span not only aesthetic issues of\nformatting, but other types of conventions or coding standards as well. However, this document\nfocuses primarily on the <strong>hard-and-fast rules</strong> that we follow universally, and\navoids giving <em>advice</em> that isn't clearly enforceable (whether by human or tool).\n</p>\n\n\n\n\n\n<h3 id=\"s1.1-terminology\">1.1 Terminology notes</h3>\n\n<p>In this document, unless otherwise clarified:</p>\n\n<ol>\n  <li>The term <em>class</em> is used inclusively to mean a normal class, record class, enum\n  class, interface or annotation type (<code class=\"prettyprint lang-java\">@interface</code>).</li>\n\n  <li>The term <em>member</em> (of a class) is used inclusively to mean a nested class, field,\n  method, <em>or constructor</em>; that is, all top-level contents of a class except initializers.\n\n  </li><li>The term <em>comment</em> always refers to <em>implementation</em> comments. We do not\n  use the phrase \"documentation comments\", and instead use the common term \"Javadoc.\"</li>\n</ol>\n\n<p>Other \"terminology notes\" will appear occasionally throughout the document.</p>\n\n<h3 id=\"s1.2-guide-notes\">1.2 Guide notes</h3>\n\n<p>Example code in this document is <strong>non-normative</strong>. That is, while the examples\nare in Google Style, they may not illustrate the <em>only</em> stylish way to represent the\ncode. Optional formatting choices made in examples should not be enforced as rules.</p>\n\n\n<h2 id=\"s2-source-file-basics\">2 Source file basics</h2>\n\n<h3 id=\"s2.1-file-name\">2.1 File name</h3>\n\n<p>For a source file containing classes, the file name consists of the case-sensitive name of the\ntop-level class (of which there is <a href=\"#s3.4.1-one-top-level-class\">exactly one</a>), plus the\n<code>.java</code> extension.</p>\n\n<h3 id=\"s2.2-file-encoding\">2.2 File encoding: UTF-8</h3>\n\n<p>Source files are encoded in <strong>UTF-8</strong>.</p>\n\n<h3 id=\"s2.3-special-characters\">2.3 Special characters</h3>\n\n<h4 id=\"s2.3.1-whitespace-characters\">2.3.1 Whitespace characters</h4>\n\n<p>Aside from the line terminator sequence, the <strong>ASCII horizontal space\ncharacter</strong> (<strong>0x20</strong>) is the only whitespace character that appears\nanywhere in a source file. This implies that:</p>\n\n<ol>\n  <li>All other whitespace characters are escaped in <code>char</code> and string literals and in\n    text blocks.</li>\n\n  <li>Tab characters are <strong>not</strong> used for indentation.</li>\n</ol>\n\n<h4 id=\"s2.3.2-special-escape-sequences\">2.3.2 Special escape sequences</h4>\n\n<p>For any character that has a\n<a href=\"http://docs.oracle.com/javase/tutorial/java/data/characters.html\">\n  special escape sequence</a>\n(<code class=\"prettyprint lang-java\">\\b</code>,\n<code class=\"prettyprint lang-java\">\\t</code>,\n<code class=\"prettyprint lang-java\">\\n</code>,\n<code class=\"prettyprint lang-java\">\\f</code>,\n<code class=\"prettyprint lang-java\">\\r</code>,\n<code class=\"prettyprint lang-java\">\\s</code>,\n<code class=\"prettyprint lang-java\">\\\"</code>,\n<code class=\"prettyprint lang-java\">\\'</code> and\n<code class=\"prettyprint lang-java\">\\\\</code>), that sequence\nis used rather than the corresponding octal\n(e.g. <code class=\"badcode\">\\012</code>) or Unicode\n(e.g. <code class=\"badcode\">\\u000a</code>) escape.</p>\n\n<h4 id=\"s2.3.3-non-ascii-characters\">2.3.3 Non-ASCII characters</h4>\n\n<p>For the remaining non-ASCII characters, either the actual Unicode character\n(e.g. <code class=\"prettyprint lang-java\">∞</code>) or the equivalent Unicode escape\n(e.g. <code class=\"prettyprint lang-java\">\\u221e</code>) is used. The choice depends only on\nwhich makes the code <strong>easier to read and understand</strong>, although Unicode escapes\noutside string literals and comments are strongly discouraged.</p>\n\n<p class=\"tip\"><strong>Tip:</strong> In the Unicode escape case, and occasionally even when actual\nUnicode characters are used, an explanatory comment can be very helpful.</p>\n\n<p>Examples:</p>\n\n<table>\n  <tbody><tr>\n    <th>Example</th>\n    <th>Discussion</th>\n  </tr>\n\n  <tr>\n    <td><code class=\"prettyprint lang-java\">String unitAbbrev = \"μs\";</code></td>\n    <td>Best: perfectly clear even without a comment.</td>\n  </tr>\n\n  <tr>\n    <td><code class=\"prettyprint lang-java\">String unitAbbrev = \"\\u03bcs\"; // \"μs\"</code></td>\n    <td>Allowed, but there's no reason to do this.</td>\n  </tr>\n\n  <tr>\n    <td><code class=\"prettyprint lang-java\">String unitAbbrev = \"\\u03bcs\";\n      // Greek letter mu, \"s\"</code></td>\n    <td>Allowed, but awkward and prone to mistakes.</td>\n  </tr>\n\n  <tr>\n    <td><code class=\"badcode\">String unitAbbrev = \"\\u03bcs\";</code></td>\n    <td>Poor: the reader has no idea what this is.</td>\n  </tr>\n\n  <tr>\n     <td><code class=\"prettyprint lang-java\">return '\\ufeff' + content;\n       // byte order mark</code></td>\n     <td>Good: use escapes for non-printable characters, and comment if necessary.</td>\n  </tr>\n</tbody></table>\n\n<p class=\"tip\"><strong>Tip:</strong> Never make your code less readable simply out of fear that\nsome programs might not handle non-ASCII characters properly. If that should happen, those\nprograms are <strong>broken</strong> and they must be <strong>fixed</strong>.</p>\n\n\n<a id=\"filestructure\"></a>\n<h2 id=\"s3-source-file-structure\">3 Source file structure</h2>\n\n<div>\n<p>An ordinary source file consists of these sections, <strong>in order</strong>:</p>\n\n<ol>\n  <li>License or copyright information, if present</li>\n  <li>Package declaration</li>\n  <li>Imports</li>\n  <li>Exactly one top-level class declaration</li>\n</ol>\n</div>\n\n<p><strong>Exactly one blank line</strong> separates each section that is present.</p>\n\n<p>A <code>package-info.java</code> file is the same, but without the class declaration.</p>\n\n<p>A <code>module-info.java</code> file does not contain a package declaration and replaces the\nclass declaration with a module declaration, but otherwise follows the same structure.</p>\n\n<h3 id=\"s3.1-copyright-statement\">3.1 License or copyright information, if present</h3>\n\n<p>If license or copyright information belongs in a file, it belongs here.</p>\n\n\n\n<a id=\"s3.2-package-statement\"></a>\n<h3 id=\"s3.2-package-declaration\">3.2 Package declaration</h3>\n\n<p>The package declaration is <strong>not line-wrapped</strong>. The column limit (Section 4.4,\n<a href=\"#s4.4-column-limit\">Column limit: 100</a>) does not apply to package declarations.</p>\n\n<a id=\"imports\"></a>\n<h3 id=\"s3.3-import-statements\">3.3 Imports</h3>\n\n<h4 id=\"s3.3.1-wildcard-imports\">3.3.1 No wildcard imports</h4>\n\n<p><strong>Wildcard (\"on-demand\") imports</strong>, static or otherwise, <strong>are not\n  used</strong>.</p>\n\n<h4 id=\"s3.3.2-import-line-wrapping\">3.3.2 No line-wrapping</h4>\n\n<p>Imports are <strong>not line-wrapped</strong>. The column limit (Section 4.4,\n<a href=\"#s4.4-column-limit\">Column limit: 100</a>) does not apply to imports.</p>\n\n<h4 id=\"s3.3.3-import-ordering-and-spacing\">3.3.3 Ordering and spacing</h4>\n\n<p>Imports are ordered as follows:</p>\n\n<ol>\n  <li>All static imports in a single group.</li>\n  <li>All non-static imports in a single group.</li>\n</ol>\n\n<p>If there are both static and non-static imports, a single blank line separates the two\ngroups. There are no other blank lines between imports.</p>\n\n<p>Within each group the imported names appear in ASCII sort order. (<strong>Note:</strong>\nthis is not the same as the import <em>lines</em> being in ASCII sort order, since '.'\nsorts before ';'.)</p>\n\n\n\n<h4 id=\"s3.3.4-import-class-not-static\">3.3.4 No static import for classes</h4>\n\n<p>Static import is not used for static nested classes. They are imported with\nnormal imports.</p>\n\n<h3 id=\"s3.4-class-declaration\">3.4 Class declaration</h3>\n\n<a id=\"oneclassperfile\"></a>\n<h4 id=\"s3.4.1-one-top-level-class\">3.4.1 Exactly one top-level class declaration</h4>\n\n<p>Each top-level class resides in a source file of its own.</p>\n\n<a id=\"s3.4.2-class-member-ordering\"></a>\n<h4 id=\"s3.4.2-ordering-class-contents\">3.4.2 Ordering of class contents</h4>\n\n<p>The order you choose for the members and initializers of your class can have a great effect on\nlearnability. However, there's no single correct recipe for how to do it; different classes may\norder their contents in different ways.</p>\n\n<p>What is important is that each class uses <strong><em>some</em> logical order</strong>, which its\nmaintainer could explain if asked. For example, new methods are not just habitually added to the end\nof the class, as that would yield \"chronological by date added\" ordering, which is not a logical\nordering.</p>\n\n\n\n<a id=\"overloads\"></a>\n<h5 id=\"s3.4.2.1-overloads-never-split\">3.4.2.1 Overloads: never split</h5>\n\n<p>Methods of a class that share the same name appear in a single contiguous group with no other\n  members in between. The same applies to multiple constructors. This rule applies even when\n  modifiers such as <code class=\"prettyprint lang-java\">static</code> or\n  <code class=\"prettyprint lang-java\">private</code> differ between the methods or constructors.</p>\n\n<h3 id=\"s3.5-module-declaration\">3.5 Module declaration</h3>\n\n<h4 id=\"s3.5.1-ordering-module-directives\">3.5.1 Ordering and spacing of module directives</h4>\n\n<p>Module directives are ordered as follows:</p>\n\n<ol>\n  <li>All <code>requires</code> directives in a single block.</li>\n  <li>All <code>exports</code> directives in a single block.</li>\n  <li>All <code>opens</code> directives in a single block.</li>\n  <li>All <code>uses</code> directives in a single block.</li>\n  <li>All <code>provides</code> directives in a single block.</li>\n</ol>\n\n<p>A single blank line separates each block that is present.</p>\n\n<h2 id=\"s4-formatting\">4 Formatting</h2>\n\n<p class=\"terminology\"><strong>Terminology Note:</strong> <em>block-like construct</em> refers to\nthe body of a class, method, constructor, or switch. Note that, by Section 4.8.3.1 on\n<a href=\"#s4.8.3.1-array-initializers\">array initializers</a>, any array initializer\n<em>may</em> optionally be treated as if it were a block-like construct.</p>\n\n<a id=\"braces\"></a>\n<h3 id=\"s4.1-braces\">4.1 Braces</h3>\n\n<h4 id=\"s4.1.1-braces-always-used\">4.1.1 Use of optional braces</h4>\n\n<p>Braces are used with\n<code class=\"prettyprint lang-java\">if</code>,\n<code class=\"prettyprint lang-java\">else</code>,\n<code class=\"prettyprint lang-java\">for</code>,\n<code class=\"prettyprint lang-java\">do</code> and\n<code class=\"prettyprint lang-java\">while</code> statements, even when the\nbody is empty or contains only a single statement.</p>\n\n<p>Other optional braces, such as those in a lambda expression, remain optional.</p>\n\n<h4 id=\"s4.1.2-blocks-k-r-style\">4.1.2 Nonempty blocks: K &amp; R style</h4>\n\n<p>Braces follow the Kernighan and Ritchie style for <em>nonempty</em> blocks and block-like\n  constructs:</p>\n\n<ul>\n  <li>No line break before the opening brace, except as detailed below.</li>\n\n  <li>Line break after the opening brace.</li>\n\n  <li>Line break before the closing brace.</li>\n\n  <li>Line break after the closing brace, <em>only if</em> that brace terminates a statement or\n  terminates the body of a method, constructor, or <em>named</em> class.\n  For example, there is <em>no</em> line break after the brace if it is followed by\n  <code class=\"prettyprint lang-java\">else</code> or a comma.</li>\n</ul>\n\n<p>Exception: In places where these rules allow a single statement ending with a semicolon\n(<code class=\"prettyprint lang-java\">;</code>), a block of statements can appear, and the opening\nbrace of this block is preceded by a line break. Blocks like these are typically introduced to\nlimit the scope of local variables.</p>\n\n<p>Examples:</p>\n\n<pre class=\"prettyprint lang-java\">return () -&gt; {\n  while (condition()) {\n    method();\n  }\n};\n\nreturn new MyClass() {\n  @Override public void method() {\n    if (condition()) {\n      try {\n        something();\n      } catch (ProblemException e) {\n        recover();\n      }\n    } else if (otherCondition()) {\n      somethingElse();\n    } else {\n      lastThing();\n    }\n    {\n      int x = foo();\n      frob(x);\n    }\n  }\n};\n</pre>\n\n<p>A few exceptions for enum classes are given in Section 4.8.1,\n<a href=\"#s4.8.1-enum-classes\">Enum classes</a>.</p>\n\n<a id=\"emptyblocks\"></a>\n<h4 id=\"s4.1.3-braces-empty-blocks\">4.1.3 Empty blocks: may be concise</h4>\n\n<p>An empty block or block-like construct may be in K &amp; R style (as described in\n<a href=\"#s4.1.2-blocks-k-r-style\">Section 4.1.2</a>). Alternatively, it may be closed immediately\nafter it is opened, with no characters or line break in between\n(<code class=\"prettyprint lang-java\">{}</code>), <strong>unless</strong> it is part of a\n<em>multi-block statement</em> (one that directly contains multiple blocks:\n<code class=\"prettyprint lang-java\">if/else</code> or\n<code class=\"prettyprint lang-java\">try/catch/finally</code>).</p>\n\n<p>Examples:</p>\n\n<pre class=\"prettyprint lang-java\">  // This is acceptable\n  void doNothing() {}\n\n  // This is equally acceptable\n  void doNothingElse() {\n  }\n</pre>\n<pre class=\"prettyprint lang-java badcode\">  // This is not acceptable: No concise empty blocks in a multi-block statement\n  try {\n    doSomething();\n  } catch (Exception e) {}\n</pre>\n\n<h3 id=\"s4.2-block-indentation\">4.2 Block indentation: +2 spaces</h3>\n\n<p>Each time a new block or block-like construct is opened, the indent increases by two\nspaces. When the block ends, the indent returns to the previous indent level. The indent level\napplies to both code and comments throughout the block. (See the example in Section 4.1.2,\n<a href=\"#s4.1.2-blocks-k-r-style\">Nonempty blocks: K &amp; R Style</a>.)</p>\n\n<h3 id=\"s4.3-one-statement-per-line\">4.3 One statement per line</h3>\n\n<p>Each statement is followed by a line break.</p>\n\n<a id=\"columnlimit\"></a>\n<h3 id=\"s4.4-column-limit\">4.4 Column limit: 100</h3>\n\n<p>Java code has a column limit of 100 characters. A \"character\" means any Unicode code point.\nExcept as noted below, any line that would exceed this limit must be line-wrapped, as explained in\nSection 4.5, <a href=\"#s4.5-line-wrapping\">Line-wrapping</a>.\n</p>\n\n<p class=\"tip\">Each Unicode code point counts as one character, even if its display width is\ngreater or less. For example, if using\n<a href=\"https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms\">fullwidth characters</a>,\nyou may choose to wrap the line earlier than where this rule strictly requires.</p>\n\n<p><strong>Exceptions:</strong></p>\n\n<ol>\n  <li>Lines where obeying the column limit is not possible (for example, a long URL in Javadoc,\n  or a long JSNI method reference).</li>\n\n  <li><code class=\"prettyprint lang-java\">package</code> declarations and\n  imports (see Sections 3.2 <a href=\"#s3.2-package-statement\">Package declarations</a> and\n  3.3 <a href=\"#s3.3-import-statements\">Imports</a>).</li>\n\n  <li>Contents of <a href=\"#s4.8.9-text-blocks\">text blocks</a>.</li>\n\n  <li>Command lines in a comment that may be copied-and-pasted into a shell.</li>\n\n  <li>Very long identifiers, on the rare occasions they are called for, are allowed to exceed the\n  column limit. In that case, the valid wrapping for the surrounding code is as produced by\n\n\n    <a href=\"https://github.com/google/google-java-format\">google-java-format</a>.\n  </li>\n</ol>\n\n<h3 id=\"s4.5-line-wrapping\">4.5 Line-wrapping</h3>\n\n<p class=\"terminology\"><strong>Terminology Note:</strong> When code that might otherwise\noccupy a single line is divided into multiple lines, this activity is called\n<em>line-wrapping</em>.</p>\n\n<p>There is no comprehensive, deterministic formula showing <em>exactly</em> how to line-wrap in\nevery situation. Very often there are several valid ways to line-wrap the same piece of code.</p>\n\n<p class=\"note\"><strong>Note:</strong> While the typical reason for line-wrapping is to avoid\noverflowing the column limit, even code that would in fact fit within the column limit <em>may</em>\nbe line-wrapped at the author's discretion.</p>\n\n<p class=\"tip\"><strong>Tip:</strong> Extracting a method or local variable may solve the problem\nwithout the need to line-wrap.</p>\n\n<h4 id=\"s4.5.1-line-wrapping-where-to-break\">4.5.1 Where to break</h4>\n\n<p>The prime directive of line-wrapping is: prefer to break at a\n<strong>higher syntactic level</strong>. Also:</p>\n\n<ol>\n  <li>When a line is broken at a <em>non-assignment</em> operator the break comes <em>before</em>\n  the symbol. (Note that this is not the same practice used in Google style for other languages,\n  such as C++ and JavaScript.)\n    <ul>\n      <li>This also applies to the following \"operator-like\" symbols:\n        <ul>\n          <li>the dot separator (<code class=\"prettyprint lang-java\">.</code>)</li>\n          <li>the two colons of a method reference\n          (<code class=\"prettyprint lang-java\">::</code>)</li>\n          <li>an ampersand in a type bound\n          (<code class=\"prettyprint lang-java\">&lt;T extends Foo &amp; Bar&gt;</code>)</li>\n          <li>a pipe in a catch block\n          (<code class=\"prettyprint lang-java\">catch (FooException | BarException e)</code>).</li>\n        </ul>\n      </li>\n    </ul>\n  </li>\n\n  <li>When a line is broken at an <em>assignment</em> operator the break typically comes\n  <em>after</em> the symbol, but either way is acceptable.\n    <ul>\n      <li>This also applies to the colon in an enhanced\n      <code class=\"prettyprint lang-java\">for</code> (\"foreach\") statement.</li>\n    </ul>\n  </li>\n\n  <li>A method, constructor, or record-class name stays attached to the open parenthesis\n  (<code class=\"prettyprint lang-java\">(</code>) that follows it.</li>\n\n  <li>A comma (<code class=\"prettyprint lang-java\">,</code>) stays attached to the token that\n  precedes it.</li>\n\n  <li>A line is never broken adjacent to the arrow in a lambda or a switch rule, except that a\n  break may come immediately after the arrow if the text following it consists of a single unbraced\n  expression. Examples:\n<pre class=\"prettyprint lang-java\">MyLambda&lt;String, Long, Object&gt; lambda =\n    (String label, Long value, Object obj) -&gt; {\n      ...\n    };\n\nPredicate&lt;String&gt; predicate = str -&gt;\n    longExpressionInvolving(str);\n\nswitch (x) {\n  case ColorPoint(Color color, Point(int x, int y)) -&gt;\n      handleColorPoint(color, x, y);\n  ...\n}\n</pre>\n  </li>\n</ol>\n\n<p class=\"note\"><strong>Note:</strong> The primary goal for line wrapping is to have clear\ncode, <em>not necessarily</em> code that fits in the smallest number of lines.</p>\n\n<a id=\"indentation\"></a>\n<h4 id=\"s4.5.2-line-wrapping-indent\">4.5.2 Indent continuation lines at least +4 spaces</h4>\n\n<p>When line-wrapping, each line after the first (each <em>continuation line</em>) is indented\nat least +4 from the original line.</p>\n\n<p>When there are multiple continuation lines, indentation may be varied beyond +4 as\ndesired. In general, two continuation lines use the same indentation level if and only if they\nbegin with syntactically parallel elements.</p>\n\n<p>Section 4.6.3 on <a href=\"#s4.6.3-horizontal-alignment\">Horizontal alignment</a> addresses\nthe discouraged practice of using a variable number of spaces to align certain tokens with\nprevious lines.</p>\n\n<h3 id=\"s4.6-whitespace\">4.6 Whitespace</h3>\n\n<h4 id=\"s4.6.1-vertical-whitespace\">4.6.1 Vertical whitespace (blank lines)</h4>\n\n<p>A single blank line always appears:</p>\n\n<ol>\n  <li><em>Between</em> consecutive members or initializers of a class: fields, constructors,\n  methods, nested classes, static initializers, and instance initializers.\n  <ul>\n    <li><span class=\"exception\"><strong>Exception:</strong> A blank line between two consecutive\n    fields (having no other code between them) is optional. Such blank lines are used as needed to\n    create <em>logical groupings</em> of fields.</span></li>\n    <li><span class=\"exception\"><strong>Exception:</strong> Blank lines between enum constants are\n    covered in <a href=\"#s4.8.1-enum-classes\">Section 4.8.1</a>.</span></li>\n  </ul>\n  </li>\n\n  <li>As required by other sections of this document (such as Section 3,\n  <a href=\"#s3-source-file-structure\">Source file structure</a>, and Section 3.3,\n  <a href=\"#s3.3-import-statements\">Imports</a>).</li>\n</ol>\n\n<p>A single blank line may also appear anywhere it improves readability, for example between\nstatements to organize the code into logical subsections. A blank line before the first member or\ninitializer, or after the last member or initializer of the class, is neither encouraged nor\ndiscouraged.\n\n</p><p><em>Multiple</em> consecutive blank lines are permitted, but never required (or encouraged).</p>\n\n<h4 id=\"s4.6.2-horizontal-whitespace\">4.6.2 Horizontal whitespace</h4>\n\n<p>Beyond where required by the language or other style rules, and apart from within literals,\ncomments and Javadoc, a single ASCII space also appears in the following places\n<strong>only</strong>.</p>\n\n<ol>\n  <li>Separating any keyword, such as\n  <code class=\"prettyprint lang-java\">if</code>,\n  <code class=\"prettyprint lang-java\">for</code> or\n  <code class=\"prettyprint lang-java\">catch</code>, from an open parenthesis\n  (<code class=\"prettyprint lang-java\">(</code>)\n  that follows it on that line</li>\n\n  <li>Separating any keyword, such as\n  <code class=\"prettyprint lang-java\">else</code> or\n  <code class=\"prettyprint lang-java\">catch</code>, from a closing curly brace\n  (<code class=\"prettyprint lang-java\">}</code>) that precedes it on that line</li>\n\n  <li>Before any open curly brace\n  (<code class=\"prettyprint lang-java\">{</code>), with two exceptions:\n  <ul>\n    <li><code class=\"prettyprint lang-java\">@SomeAnnotation({a, b})</code> (no space is used)</li>\n\n    <li><code class=\"prettyprint lang-java\">String[][] x = {{\"foo\"}};</code> (no space is required\n    between <code class=\"prettyprint lang-java\">{{</code>, by item 10 below)</li>\n  </ul>\n  </li>\n\n  <li>On both sides of any binary or ternary operator. This also applies to the following\n  \"operator-like\" symbols:\n  <ul>\n    <li>the ampersand that separates multiple type bounds:\n    <code class=\"prettyprint lang-java\">&lt;T extends Foo &amp; Bar&gt;</code></li>\n\n    <li>the pipe for a catch block that handles multiple exceptions:\n    <code class=\"prettyprint lang-java\">catch (FooException | BarException e)</code></li>\n\n    <li>the colon (<code class=\"prettyprint lang-java\">:</code>) in an enhanced\n    <code class=\"prettyprint lang-java\">for</code> (\"foreach\") statement</li>\n\n    <li>the arrow in a lambda expression:\n    <code class=\"prettyprint lang-java\">(String str) -&gt; str.length()</code><br>\n    or switch rule:\n    <code class=\"prettyprint lang-java\">case \"FOO\" -&gt; bar();</code></li>\n  </ul>\n    but not\n\n  <ul>\n    <li>the two colons (<code class=\"prettyprint lang-java\">::</code>) of a method reference, which\n    is written like <code class=\"prettyprint lang-java\">Object::toString</code></li>\n    <li>the dot separator (<code class=\"prettyprint lang-java\">.</code>), which is written like\n    <code class=\"prettyprint lang-java\">object.toString()</code></li>\n  </ul>\n  </li>\n\n  <li>After <code class=\"prettyprint lang-java\">,:;</code> or the closing parenthesis\n  (<code class=\"prettyprint lang-java\">)</code>) of a cast</li>\n\n  <li>Between any content and a double slash (<code class=\"prettyprint lang-java\">//</code>) which\n  begins a comment. Multiple spaces are allowed.</li>\n\n  <li>Between a double slash (<code class=\"prettyprint lang-java\">//</code>) which begins a comment\n  and the comment's text. Multiple spaces are allowed.</li>\n\n  <li>Between the type and identifier of a declaration:\n  <code class=\"prettyprint lang-java\">List&lt;String&gt; list</code></li>\n\n  <li><em>Optional</em> just inside both braces of an array initializer\n  <ul>\n    <li><code class=\"prettyprint lang-java\">new int[] {5, 6}</code> and\n    <code class=\"prettyprint lang-java\">new int[] { 5, 6 }</code> are both valid</li>\n  </ul>\n  </li>\n\n  <li>Between a type annotation and <code class=\"prettyprint lang-java\">[]</code> or\n  <code class=\"prettyprint lang-java\">...</code>.</li>\n</ol>\n\n<p>This rule is never interpreted as requiring or forbidding additional space at the start or\nend of a line; it addresses only <em>interior</em> space.</p>\n\n<h4 id=\"s4.6.3-horizontal-alignment\">4.6.3 Horizontal alignment: never required</h4>\n\n<p class=\"terminology\"><strong>Terminology Note:</strong> <em>Horizontal alignment</em> is the\npractice of adding a variable number of additional spaces in your code with the goal of making\ncertain tokens appear directly below certain other tokens on previous lines.</p>\n\n<p>This practice is permitted, but is <strong>never required</strong> by Google Style. It is not\neven required to <em>maintain</em> horizontal alignment in places where it was already used.</p>\n\n<p>Here is an example without alignment, then using alignment:</p>\n\n<pre class=\"prettyprint lang-java\">private int x; // this is fine\nprivate Color color; // this too\n\nprivate int   x;      // permitted, but future edits\nprivate Color color;  // may leave it unaligned\n</pre>\n\n<p class=\"tip\"><strong>Tip:</strong> Alignment can aid readability, but attempting to preserve\nalignment for its own sake creates future problems. For example, consider a change that touches only\none line. If that change disrupts the previous alignment, it's important **not** to introduce\nadditional changes on nearby lines simply to realign them. Introducing formatting changes on\notherwise unaffected lines corrupts version history, slows down reviewers, and exacerbates merge\nconflicts. These practical concerns take priority over alignment.</p>\n\n<a id=\"parentheses\"></a>\n<h3 id=\"s4.7-grouping-parentheses\">4.7 Grouping parentheses: recommended</h3>\n\n<p>Optional grouping parentheses are omitted only when author and reviewer agree that there is no\nreasonable chance the code will be misinterpreted without them, nor would they have made the code\neasier to read. It is <em>not</em> reasonable to assume that every reader has the entire Java\noperator precedence table memorized.</p>\n\n<h3 id=\"s4.8-specific-constructs\">4.8 Specific constructs</h3>\n\n<h4 id=\"s4.8.1-enum-classes\">4.8.1 Enum classes</h4>\n\n<p>After the comma that follows an enum constant, a line break is optional. Additional blank\nlines (usually just one) are also allowed. This is one possibility:\n\n</p><pre class=\"prettyprint lang-java\">private enum Answer {\n  YES {\n    @Override public String toString() {\n      return \"yes\";\n    }\n  },\n\n  NO,\n  MAYBE\n}\n</pre>\n\n<p>An enum class with no methods and no documentation on its constants may optionally be formatted\nas if it were an array initializer (see Section 4.8.3.1 on\n<a href=\"#s4.8.3.1-array-initializers\">array initializers</a>).</p>\n\n<pre class=\"prettyprint lang-java\">private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }\n</pre>\n\n<p>Since enum classes <em>are classes</em>, all other rules for formatting classes apply.</p>\n\n<a id=\"localvariables\"></a>\n<h4 id=\"s4.8.2-variable-declarations\">4.8.2 Variable declarations</h4>\n\n<h5 id=\"s4.8.2.1-variables-per-declaration\">4.8.2.1 One variable per declaration</h5>\n\n<p>Every variable declaration (field or local) declares only one variable: declarations such as\n<code class=\"badcode\">int a, b;</code> are not used.</p>\n\n<p><strong>Exception:</strong> Multiple variable declarations are acceptable in the header of a\n<code class=\"prettyprint lang-java\">for</code> loop.</p>\n\n<h5 id=\"s4.8.2.2-variables-limited-scope\">4.8.2.2 Declared when needed</h5>\n\n<p>Local variables are <strong>not</strong> habitually declared at the start of their containing\nblock or block-like construct. Instead, local variables are declared close to the point they are\nfirst used (within reason), to minimize their scope. Local variable declarations typically have\ninitializers, or are initialized immediately after declaration.</p>\n\n<h4 id=\"s4.8.3-arrays\">4.8.3 Arrays</h4>\n\n<h5 id=\"s4.8.3.1-array-initializers\">4.8.3.1 Array initializers: can be \"block-like\"</h5>\n\n<p>Any array initializer may <em>optionally</em> be formatted as if it were a \"block-like\nconstruct.\" For example, the following are all valid (<strong>not</strong> an exhaustive\nlist):</p>\n\n<pre class=\"prettyprint lang-java\">new int[] {           new int[] {\n  0, 1, 2, 3            0,\n}                       1,\n                        2,\nnew int[] {             3,\n  0, 1,               }\n  2, 3\n}                     new int[]\n                          {0, 1, 2, 3}\n</pre>\n\n<h5 id=\"s4.8.3.2-array-declarations\">4.8.3.2 No C-style array declarations</h5>\n\n<p>The square brackets form a part of the <em>type</em>, not the variable:\n<code class=\"prettyprint lang-java\">String[] args</code>, not\n<code class=\"badcode\">String args[]</code>.</p>\n\n<h4 id=\"s4.8.4-switch\">4.8.4 Switch statements and expressions</h4>\n\n\n\n<p>For historical reasons, the Java language has two distinct syntaxes for <code class=\"prettyprint lang-java\">switch</code>, which we can call <em>old-style</em> and\n<em>new-style</em>. New-style switches use an arrow\n(<code class=\"prettyprint lang-java\">-&gt;</code>) after the switch labels, while old-style switches\nuse a colon (<code class=\"prettyprint lang-java\">:</code>).\n\n</p><p class=\"terminology\"><strong>Terminology Note:</strong> Inside the braces of a\n<em>switch block</em> are either one or more <em>switch rules</em> (new-style);\nor one or more <em>statement groups</em> (old-style). A <em>switch\nrule</em> consists of a <em>switch label</em> (<code class=\"prettyprint lang-java\">case ...</code>\nor <code class=\"prettyprint lang-java\">default</code>) followed by <code class=\"prettyprint lang-java\">-&gt;</code> and an expression, block, or <code class=\"prettyprint\nlang-java\">throw</code>. A statement group consists of one or more switch labels each followed by\na colon, then one or more statements, or, for the <em>last</em> statement group, <em>zero</em> or\nmore statements. (These definitions match the Java Language Specification,\n<a href=\"https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.11\">§14.11</a>.)</p>\n\n<h5 id=\"s4.8.4.1-switch-indentation\">4.8.4.1 Indentation</h5>\n\n<p>As with any other block, the contents of a switch block are indented +2. Each switch label\nstarts with this +2 indentation.</p>\n\n<p>In a new-style switch, a switch rule can be written on a single line if it otherwise follows\nGoogle style. (It must not exceed the column limit, and if it contains a non-empty block then\nthere must be a line break after <code class=\"prettyprint lang-java\">{</code>.) The line-wrapping\nrules of <a href=\"#s4.5-line-wrapping\">Section 4.5</a> apply, including the +4 indent for\ncontinuation lines. For a switch rule with a non-empty block after the arrow, the same rules apply\nas for blocks elsewhere: lines between <code class=\"prettyprint lang-java\">{</code> and\n<code class=\"prettyprint lang-java\">}</code> are indented a further +2 relative to the line with the\nswitch label.\n\n</p><pre class=\"prettyprint lang-java\">switch (number) {\n  case 0, 1 -&gt; handleZeroOrOne();\n  case 2 -&gt;\n      handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine();\n  default -&gt; {\n    logger.atInfo().log(\"Surprising number %s\", number);\n    handleSurprisingNumber(number);\n  }\n}\n</pre>\n\n<p>In an old-style switch, the colon of each switch label is followed by a line break. The\nstatements within a statement group are indented a further +2.</p>\n\n<a id=\"fallthrough\"></a>\n<h5 id=\"s4.8.4.2-switch-fall-through\">4.8.4.2 Fall-through: commented</h5>\n\n<p>Within an old-style switch block, each statement group either terminates abruptly (with a\n<code class=\"prettyprint lang-java\">break</code>,\n<code class=\"prettyprint lang-java\">continue</code>,\n<code class=\"prettyprint lang-java\">return</code> or thrown exception), or is marked with a comment\nto indicate that execution will or <em>might</em> continue into the next statement group. Any\ncomment that communicates the idea of fall-through is sufficient (typically\n<code class=\"prettyprint lang-java\">// fall through</code>). This special comment is not required in\nthe last statement group of the switch block. Example:</p>\n\n<pre class=\"prettyprint lang-java\">switch (input) {\n  case 1:\n  case 2:\n    prepareOneOrTwo();\n  // fall through\n  case 3:\n    handleOneTwoOrThree();\n    break;\n  default:\n    handleLargeNumber(input);\n}\n</pre>\n\n<p>Notice that no comment is needed after <code class=\"prettyprint lang-java\">case 1:</code>, only\nat the end of the statement group.</p>\n\n<p>There is no fall-through in new-style switches.</p>\n\n<h5 id=\"s4.8.4.3-switch-default\">4.8.4.3 Exhaustiveness and presence of the <code>default</code> label</h5>\n\n<p>The Java language requires switch expressions and many kinds of switch statements to be\n<em>exhaustive</em>. That effectively means that every possible value that could be switched on will\nbe matched by one of the switch labels. A switch is exhaustive if it has a <code class=\"prettyprint lang-java\">default</code> label, but also for example if the value being switched\non is an enum and every value of the enum is matched by a switch label. Google Style requires\n<em>every</em> switch to be exhaustive, even those where the language itself does not require it.\nThis may require adding a <code class=\"prettyprint lang-java\">default</code> label, even if it\ncontains no code.</p>\n\n<h5 id=\"s4.8.4.4-switch-expressions\">4.8.4.4 Switch expressions</h5>\n\n<p>Switch expressions must be new-style switches:</p>\n\n<pre class=\"prettyprint lang-java\">  return switch (list.size()) {\n    case 0 -&gt; \"\";\n    case 1 -&gt; list.getFirst();\n    default -&gt; String.join(\", \", list);\n  };\n</pre>\n\n<a id=\"annotations\"></a>\n<h4 id=\"s4.8.5-annotations\">4.8.5 Annotations</h4>\n\n<h5 id=\"s4.8.5.1-type-use-annotation-style\">4.8.5.1 Type-use annotations</h5>\n\n<p>Type-use annotations appear immediately before the annotated type. An annotation is a type-use\nannotation if it is meta-annotated with\n<code class=\"prettyprint lang-java\">@Target(ElementType.TYPE_USE)</code>. Example:</p>\n\n<pre class=\"prettyprint lang-java\">final @Nullable String name;\n\npublic @Nullable Person getPersonByName(String name);\n</pre>\n\n<h5 id=\"s4.8.5.2-class-annotation-style\">4.8.5.2 Class, package, and module annotations</h5>\n\n<p>Annotations applying to a class, package, or module declaration appear immediately after the\ndocumentation block, and each annotation is listed on a line of its own (that is, one annotation\nper line). These line breaks do not constitute line-wrapping (Section\n4.5, <a href=\"#s4.5-line-wrapping\">Line-wrapping</a>), so the indentation level is not\nincreased. Examples:</p>\n\n<pre class=\"prettyprint lang-java\">/** This is a class. */\n@Deprecated\n@CheckReturnValue\npublic final class Frozzler { ... }\n</pre>\n<pre class=\"prettyprint lang-java\">/** This is a package. */\n@Deprecated\n@CheckReturnValue\npackage com.example.frozzler;\n</pre>\n<pre class=\"prettyprint lang-java\">/** This is a module. */\n@Deprecated\n@SuppressWarnings(\"CheckReturnValue\")\nmodule com.example.frozzler { ... }\n</pre>\n\n<h5 id=\"s4.8.5.3-method-annotation-style\">4.8.5.3 Method and constructor annotations</h5>\n\n<p>The rules for annotations on method and constructor declarations are the same as the\n<a href=\"#s4.8.5.2-class-annotation-style\">previous section</a>. Example: </p>\n\n<pre class=\"prettyprint lang-java\">@Deprecated\n@Override\npublic String getNameIfPresent() { ... }\n</pre>\n\n<p class=\"exception\"><strong>Exception:</strong> A <em>single</em> parameterless annotation\n<em>may</em> instead appear together with the first line of the signature, for example:</p>\n\n<pre class=\"prettyprint lang-java\">@Override public int hashCode() { ... }\n</pre>\n\n<h5 id=\"s4.8.5.4-field-annotation-style\">4.8.5.4 Field annotations</h5>\n\n<p>Annotations applying to a field also appear immediately after the documentation block, but in\nthis case, <em>multiple</em> annotations (possibly parameterized) may be listed on the same line;\nfor example:</p>\n\n<pre class=\"prettyprint lang-java\">@Partial @Mock DataLoader loader;\n</pre>\n\n<h5 id=\"s4.8.5.5-local-parameter-annotation-style\">4.8.5.5 Parameter and local variable annotations</h5>\n\n<p>There are no specific rules for formatting annotations on parameters or local variables (except,\nof course, when the annotation is a type-use annotation).</p>\n\n<a id=\"comments\"></a>\n<h4 id=\"s4.8.6-comments\">4.8.6 Comments</h4>\n\n<p>This section addresses <em>implementation comments</em>. Javadoc is addressed separately in\nSection 7, <a href=\"#s7-javadoc\">Javadoc</a>.</p>\n\n<p>Any line break may be preceded by arbitrary whitespace followed by an implementation comment.\nSuch a comment renders the line non-blank.</p>\n\n<h5 id=\"s4.8.6.1-block-comment-style\">4.8.6.1 Block comment style</h5>\n\n<p>Block comments are indented at the same level as the surrounding code. They may be in\n<code class=\"prettyprint lang-java\">/* ... */</code> style or\n<code class=\"prettyprint lang-java\">// ...</code> style. For multi-line\n<code class=\"prettyprint lang-java\">/* ... */</code> comments, subsequent lines must start with\n<code>*</code> aligned with the <code>*</code> on the previous line.</p>\n\n<pre class=\"prettyprint lang-java\">/*\n * This is          // And so           /* Or you can\n * okay.            // is this.          * even do this. */\n */\n</pre>\n\n\n<p>Comments are not enclosed in boxes drawn with asterisks or other characters.</p>\n\n<p class=\"tip\"><strong>Tip:</strong> When writing multi-line comments, use the\n<code class=\"prettyprint lang-java\">/* ... */</code> style if you want automatic code formatters to\nre-wrap the lines when necessary (paragraph-style). Most formatters don't re-wrap lines in\n<code class=\"prettyprint lang-java\">// ...</code> style comment blocks.</p>\n\n<a id=\"todo\"></a>\n<h5 id=\"s4.8.6.2-todo-comments\">4.8.6.2 TODO comments</h5>\n\n\n\n<div>\n<p>Use <code>TODO</code> comments for code that is temporary, a short-term solution, or good-enough\n  but not perfect.</p>\n\n<p>A <code>TODO</code> comment begins with the word <code>TODO</code> in all caps, a following\n  colon, and a link to a resource that contains the context, ideally a bug reference. A bug\n  reference is preferable because bugs are tracked and have follow-up comments. Follow this piece of\n  context with an explanatory string introduced with a hyphen <code>-</code>.</p>\n\n<p>The purpose is to have a consistent <code>TODO</code> format that can be searched to find out how\n  to get more details.</p>\n\n<pre class=\"good\">// TODO: crbug.com/12345678 - Remove this after the 2047q4 compatibility window expires.\n</pre>\n\n<p>Avoid adding TODOs that refer to an individual or team as the context:</p>\n\n<pre class=\"bad\">// TODO: @yourusername - File an issue and use a '*' for repetition.\n</pre>\n\n<p>If your <code>TODO</code> is of the form \"At a future date do something\" make sure that you\n  either include a very specific date (\"Fix by November 2005\") or a very specific event (\"Remove\n  this code when all clients can handle XML responses.\").</p>\n</div>\n\n<a id=\"modifiers\"></a>\n<h4 id=\"s4.8.7-modifiers\">4.8.7 Modifiers</h4>\n\n<p>Class and member modifiers, when present, appear in the order\nrecommended by the Java Language Specification:\n</p>\n\n<pre>public protected private abstract default static final sealed non-sealed\n  transient volatile synchronized native strictfp\n</pre>\n\n<p>Modifiers on <code>requires</code> module directives, when present, appear in the following\norder:</p>\n\n<pre>transitive static</pre>\n\n<h4 id=\"s4.8.8-numeric-literals\">4.8.8 Numeric Literals</h4>\n\n<p><code>long</code>-valued integer literals use an uppercase <code>L</code> suffix, never\nlowercase (to avoid confusion with the digit <code>1</code>). For example, <code>3000000000L</code>\nrather than <code class=\"badcode\">3000000000l</code>.</p>\n\n<h4 id=\"s4.8.9-text-blocks\">4.8.9 Text Blocks</h4>\n\n<p>The opening <code>\"\"\"</code> of a text block is always on a new line. That line may\n  either follow the same indentation rules as other constructs, or it may have no indentation at all\n  (so it starts at the left margin). The closing <code>\"\"\"</code> is on a new line\n  with the same indentation as the opening <code>\"\"\"</code>, and may be followed on the\n  same line by further code. Each line of text in the text block is indented at least as much as the\n  opening and closing <code>\"\"\"</code>. (If a line is indented further, then the string\n  literal defined by the text block will have space at the start of that line.)\n\n</p><p>The contents of a text block may exceed the <a href=\"#columnlimit\">column limit</a>.\n\n<a id=\"naming\"></a>\n</p><h2 id=\"s5-naming\">5 Naming</h2>\n\n<h3 id=\"s5.1-identifier-names\">5.1 Rules common to all identifiers</h3>\n\n<p>Identifiers use only ASCII letters and digits, and, in a small number of cases noted below,\nunderscores. Thus each valid identifier name is matched by the regular expression\n<code>\\w+</code> .</p>\n\n<p>In Google Style, special prefixes or suffixes are <strong>not</strong> used. For example, these\nnames are not Google Style: <code class=\"badcode\">name_</code>, <code class=\"badcode\">mName</code>,\n<code class=\"badcode\">s_name</code> and <code class=\"badcode\">kName</code>.</p>\n\n\n\n<h3 id=\"s5.2-specific-identifier-names\">5.2 Rules by identifier type</h3>\n\n<h4 id=\"s5.2.1-package-names\">5.2.1 Package and module names</h4>\n\n<p>Package and module names use only lowercase letters and digits (no underscores). Consecutive\nwords are simply concatenated together. For example, <code>com.example.deepspace</code>, not\n<code class=\"badcode\">com.example.deepSpace</code> or\n<code class=\"badcode\">com.example.deep_space</code>.</p>\n\n<h4 id=\"s5.2.2-class-names\">5.2.2 Class names</h4>\n\n<p>Class names are written in <a href=\"#s5.3-camel-case\">UpperCamelCase</a>.</p>\n\n<p>Class names are typically nouns or noun phrases. For example,\n<code class=\"prettyprint lang-java\">Character</code> or\n<code class=\"prettyprint lang-java\">ImmutableList</code>. Interface names may also be nouns or\nnoun phrases (for example, <code class=\"prettyprint lang-java\">List</code>), but may sometimes be\nadjectives or adjective phrases instead (for example,\n<code class=\"prettyprint lang-java\">Readable</code>).</p>\n\n<p>There are no specific rules or even well-established conventions for naming annotation types.</p>\n\n<p>A <em>test</em> class has a name that ends with <code class=\"prettyprint lang-java\">Test</code>,\nfor example, <code class=\"prettyprint lang-java\">HashIntegrationTest</code>.\nIf it covers a single class, its name is the name of that class\nplus <code class=\"prettyprint lang-java\">Test</code>, for example <code class=\"prettyprint\n  lang-java\">HashImplTest</code>.</p>\n\n<h4 id=\"s5.2.3-method-names\">5.2.3 Method names</h4>\n\n<p>Method names are written in <a href=\"#s5.3-camel-case\">lowerCamelCase</a>.</p>\n\n<p>Method names are typically verbs or verb phrases. For example,\n<code class=\"prettyprint lang-java\">sendMessage</code> or\n<code class=\"prettyprint lang-java\">stop</code>.</p>\n\n<p>Underscores may appear in JUnit <em>test</em> method names to separate logical components of the\nname, with <em>each</em> component written in <a href=\"#s5.3-camel-case\">lowerCamelCase</a>, for\nexample <code class=\"prettyprint lang-java\">transferMoney_deductsFromSource</code>. There is no One\nCorrect Way to name test methods.</p>\n\n<a id=\"constants\"></a>\n<h4 id=\"s5.2.4-constant-names\">5.2.4 Constant names</h4>\n\n<p>Constant names use <code class=\"prettyprint lang-java\">UPPER_SNAKE_CASE</code>: all uppercase\nletters, with each word separated from the next by a single underscore. But what <em>is</em> a\nconstant, exactly?</p>\n\n<p>Constants are static final fields whose contents are deeply immutable and whose methods have no\ndetectable side effects. Examples include primitives, strings, immutable value classes, and anything\nset to <code>null</code>. If any of the instance's observable state can change, it is not a\nconstant. Merely <em>intending</em> to never mutate the object is not enough. Examples:</p>\n\n<pre class=\"prettyprint lang-java\">// Constants\nstatic final int NUMBER = 5;\nstatic final ImmutableList&lt;String&gt; NAMES = ImmutableList.of(\"Ed\", \"Ann\");\nstatic final Map&lt;String, Integer&gt; AGES = ImmutableMap.of(\"Ed\", 35, \"Ann\", 32);\nstatic final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable\nstatic final SomeMutableType[] EMPTY_ARRAY = {};\n\n// Not constants\nstatic String nonFinal = \"non-final\";\nfinal String nonStatic = \"non-static\";\nstatic final Set&lt;String&gt; mutableCollection = new HashSet&lt;String&gt;();\nstatic final ImmutableSet&lt;SomeMutableType&gt; mutableElements = ImmutableSet.of(mutable);\nstatic final ImmutableMap&lt;String, SomeMutableType&gt; mutableValues =\n    ImmutableMap.of(\"Ed\", mutableInstance, \"Ann\", mutableInstance2);\nstatic final Logger logger = Logger.getLogger(MyClass.getName());\nstatic final String[] nonEmptyArray = {\"these\", \"can\", \"change\"};\n</pre>\n\n<p>These names are typically nouns or noun phrases.</p>\n\n<h4 id=\"s5.2.5-non-constant-field-names\">5.2.5 Non-constant field names</h4>\n\n<p>Non-constant field names (static or otherwise) are written\nin <a href=\"#s5.3-camel-case\">lowerCamelCase</a>.</p>\n\n<p>These names are typically nouns or noun phrases.  For example,\n<code class=\"prettyprint lang-java\">computedValues</code> or\n<code class=\"prettyprint lang-java\">index</code>.</p>\n\n<h4 id=\"s5.2.6-parameter-names\">5.2.6 Parameter names</h4>\n\n<p>Parameter names are written in <a href=\"#s5.3-camel-case\">lowerCamelCase</a>.</p>\n\n<p>One-character parameter names in public methods should be avoided.</p>\n\n<h4 id=\"s5.2.7-local-variable-names\">5.2.7 Local variable names</h4>\n\n<p>Local variable names are written in <a href=\"#s5.3-camel-case\">lowerCamelCase</a>.</p>\n\n<p>Even when final and immutable, local variables are not considered to be constants, and should not\nbe styled as constants.</p>\n\n<h4 id=\"s5.2.8-type-variable-names\">5.2.8 Type variable names</h4>\n\n<p>Each type variable is named in one of two styles:</p>\n\n<ul>\n  <li>A single capital letter, optionally followed by a single numeral (such as\n  <code class=\"prettyprint lang-java\">E</code>, <code class=\"prettyprint lang-java\">T</code>,\n  <code class=\"prettyprint lang-java\">X</code>, <code class=\"prettyprint lang-java\">T2</code>)\n  </li>\n\n  <li>A name in the form used for classes (see Section 5.2.2,\n  <a href=\"#s5.2.2-class-names\">Class names</a>), followed by the capital letter\n  <code class=\"prettyprint lang-java\">T</code> (examples:\n  <code class=\"prettyprint lang-java\">RequestT</code>,\n  <code class=\"prettyprint lang-java\">FooBarT</code>).</li>\n</ul>\n\n<a id=\"acronyms\"></a>\n<a id=\"camelcase\"></a>\n<h3 id=\"s5.3-camel-case\">5.3 Camel case: defined</h3>\n\n<p>Sometimes there is more than one reasonable way to convert an English phrase into camel case,\nsuch as when acronyms or unusual constructs like \"IPv6\" or \"iOS\" are present. To improve\npredictability, Google Style specifies the following (nearly) deterministic scheme.</p>\n\n<p>Beginning with the prose form of the name:</p>\n\n<ol>\n  <li>Convert the phrase to plain ASCII and remove any apostrophes. For example, \"Müller's\n  algorithm\" might become \"Muellers algorithm\".</li>\n\n  <li>Divide this result into words, splitting on spaces and any remaining punctuation (typically\n  hyphens).\n\n  <ul>\n    <li><em>Recommended:</em> if any word already has a conventional camel-case appearance in common\n    usage, split this into its constituent parts (e.g., \"AdWords\" becomes \"ad words\"). Note\n    that a word such as \"iOS\" is not really in camel case <em>per se</em>; it defies <em>any</em>\n    convention, so this recommendation does not apply.</li>\n  </ul>\n  </li>\n\n  <li>Now lowercase <em>everything</em> (including acronyms), then uppercase only the first\n  character of:\n  <ul>\n    <li>... each word, to yield <em>upper camel case</em>, or</li>\n    <li>... each word except the first, to yield <em>lower camel case</em></li>\n  </ul>\n  </li>\n\n  <li>Finally, join all the words into a single identifier. Note that the casing of the original\n  words is almost entirely disregarded.</li>\n</ol>\n\n<p>In very rare circumstances (for example, multipart version numbers), you may need to use\nunderscores to separate adjacent numbers, since numbers do not have upper and lower case variants.\n</p>\n\n<p>Examples:</p>\n\n<table>\n  <tbody><tr>\n    <th>Prose form</th>\n    <th>Correct</th>\n    <th>Incorrect</th>\n  </tr>\n  <tr>\n    <td>\"XML HTTP request\"</td>\n    <td><code class=\"prettyprint lang-java\">XmlHttpRequest</code></td>\n    <td><code class=\"badcode\">XMLHTTPRequest</code></td>\n  </tr>\n  <tr>\n    <td>\"new customer ID\"</td>\n    <td><code class=\"prettyprint lang-java\">newCustomerId</code></td>\n    <td><code class=\"badcode\">newCustomerID</code></td>\n  </tr>\n  <tr>\n    <td>\"inner stopwatch\"</td>\n    <td><code class=\"prettyprint lang-java\">innerStopwatch</code></td>\n    <td><code class=\"badcode\">innerStopWatch</code></td>\n  </tr>\n  <tr>\n    <td>\"supports IPv6 on iOS?\"</td>\n    <td><code class=\"prettyprint lang-java\">supportsIpv6OnIos</code></td>\n    <td><code class=\"badcode\">supportsIPv6OnIOS</code></td>\n  </tr>\n  <tr>\n    <td>\"YouTube importer\"</td>\n    <td><code class=\"prettyprint lang-java\">YouTubeImporter</code><br>\n        <code class=\"prettyprint lang-java\">YoutubeImporter</code>*</td>\n    <td></td>\n  </tr>\n  <tr>\n    <td>\"Turn on 2SV\"</td>\n    <td><code class=\"prettyprint lang-java\">turnOn2sv</code></td>\n    <td><code class=\"badcode\">turnOn2Sv</code></td>\n  </tr>\n  <tr>\n    <td>\"Guava 33.4.6\"</td>\n    <td><code class=\"prettyprint lang-java\">guava33_4_6</code></td>\n    <td><code class=\"badcode\">guava3346</code></td>\n  </tr>\n</tbody></table>\n\n<p>*Acceptable, but not recommended.</p>\n\n<p class=\"note\"><strong>Note:</strong> Some words are ambiguously hyphenated in the English\nlanguage: for example \"nonempty\" and \"non-empty\" are both correct, so the method names\n<code class=\"prettyprint lang-java\">checkNonempty</code> and\n<code class=\"prettyprint lang-java\">checkNonEmpty</code> are likewise both correct.</p>\n\n\n<h2 id=\"s6-programming-practices\">6 Programming Practices</h2>\n\n<h3 id=\"s6.1-override-annotation\">6.1 <code>@Override</code>: always used</h3>\n\n<p>A method is marked with the <code class=\"prettyprint lang-java\">@Override</code> annotation\nwhenever it is legal.  This includes a class method overriding a superclass method, a class method\nimplementing an interface method, an interface method respecifying a superinterface method, and an\nexplicitly declared accessor method for a record component.</p>\n\n<p class=\"exception\"><strong>Exception:</strong>\n<code class=\"prettyprint lang-java\">@Override</code> may be omitted when the parent method is\n<code class=\"prettyprint lang-java\">@Deprecated</code>.</p>\n\n<a id=\"caughtexceptions\"></a>\n<h3 id=\"s6.2-caught-exceptions\">6.2 Caught exceptions: not ignored</h3>\n\n<p>It is very rarely correct to do nothing in response to a caught\nexception. (Typical responses are to log it, or if it is considered \"impossible\", rethrow it as an\n<code class=\"prettyprint lang-java\">AssertionError</code>.)</p>\n\n<p>When it truly is appropriate to take no action whatsoever in a catch block, the reason this is\njustified is explained in a comment.</p>\n\n<pre class=\"prettyprint lang-java\">try {\n  int i = Integer.parseInt(response);\n  return handleNumericResponse(i);\n} catch (NumberFormatException ok) {\n  // it's not numeric; that's fine, just continue\n}\nreturn handleTextResponse(response);\n</pre>\n\n<h3 id=\"s6.3-static-members\">6.3 Static members: qualified using class</h3>\n\n<p>When a reference to a static class member must be qualified, it is qualified with that class's\nname, not with a reference or expression of that class's type.</p>\n\n<pre class=\"prettyprint lang-java\">Foo aFoo = ...;\nFoo.aStaticMethod(); // good\n<span class=\"badcode\">aFoo.aStaticMethod();</span> // bad\n<span class=\"badcode\">somethingThatYieldsAFoo().aStaticMethod();</span> // very bad\n</pre>\n\n<a id=\"finalizers\"></a>\n<h3 id=\"s6.4-finalizers\">6.4 Finalizers: not used</h3>\n\n<p>Do not override <code class=\"prettyprint lang-java\">Object.finalize</code>. Finalization support\nis <a href=\"https://openjdk.org/jeps/421\"><em>scheduled for removal</em></a>.</p>\n\n\n<a id=\"javadoc\"></a>\n<h2 id=\"s7-javadoc\">7 Javadoc</h2>\n\n\n\n<h3 id=\"s7.1-javadoc-formatting\">7.1 Formatting</h3>\n\n<h4 id=\"s7.1.1-javadoc-multi-line\">7.1.1 General form</h4>\n\n<p>The <em>basic</em> formatting of Javadoc blocks is as seen in this example:</p>\n\n<pre class=\"prettyprint lang-java\">/**\n * Multiple lines of Javadoc text are written here,\n * wrapped normally...\n */\npublic int method(String p1) { ... }\n</pre>\n\n<p>... or in this single-line example:</p>\n\n<pre class=\"prettyprint lang-java\">/** An especially short bit of Javadoc. */\n</pre>\n\n<p>The basic form is always acceptable. The single-line form may be substituted when the entirety\nof the Javadoc block (including comment markers) can fit on a single line. Note that this only\napplies when there are no block tags such as <code>@param</code>.</p>\n\n<h4 id=\"s7.1.2-javadoc-paragraphs\">7.1.2 Paragraphs</h4>\n\n<p>One blank line—that is, a line containing only the aligned leading asterisk\n(<code>*</code>)—appears between paragraphs, and before the group of block tags if present.\nEach paragraph except the first has <code>&lt;p&gt;</code> immediately before the first word, with\nno space after it. HTML tags for other block-level elements, such as <code>&lt;ul&gt;</code> or\n<code>&lt;table&gt;</code>, are <em>not</em> preceded with <code>&lt;p&gt;</code>.</p>\n\n<a id=\"s7.1.3-javadoc-at-clauses\"></a>\n\n<h4 id=\"s7.1.3-javadoc-block-tags\">7.1.3 Block tags</h4>\n\n<p>Any of the standard \"block tags\" that are used appear in the order <code>@param</code>,\n<code>@return</code>, <code>@throws</code>, <code>@deprecated</code>, and these four types never\nappear with an empty description. When a block tag doesn't fit on a single line, continuation lines\nare indented four (or more) spaces from the position of the <code>@</code>.\n</p>\n\n<h3 id=\"s7.2-summary-fragment\">7.2 The summary fragment</h3>\n\n<p>Each Javadoc block begins with a brief <strong>summary fragment</strong>. This\nfragment is very important: it is the only part of the text that appears in certain contexts such as\nclass and method indexes.</p>\n\n<p>This is a fragment—a noun phrase or verb phrase, not a complete sentence. It does\n<strong>not</strong> begin with <code class=\"badcode\">A {@code Foo} is a...</code>, or\n<code class=\"badcode\">This method returns...</code>, nor does it form a complete imperative sentence\nlike <code class=\"badcode\">Save the record.</code>. However, the fragment is capitalized and\npunctuated as if it were a complete sentence.</p>\n\n<p class=\"tip\"><strong>Tip:</strong> A common mistake is to write simple Javadoc in the form\n<code class=\"badcode prettyprint lang-java\">/** @return the customer ID */</code>. This is\nincorrect, and should be changed to\n<code class=\"prettyprint lang-java\">/** Returns the customer ID. */</code> or\n<code class=\"prettyprint lang-java\">/** {@return the customer ID} */</code>.</p>\n\n<a id=\"s7.3.3-javadoc-optional\"></a>\n<h3 id=\"s7.3-javadoc-where-required\">7.3 Where Javadoc is used</h3>\n\n<p>At the <em>minimum</em>, Javadoc is present for every <em>visible</em> class, member, or record\ncomponent, with a few exceptions noted below. A top-level class is visible if it is <code class=\"prettyprint lang-java\">public</code>; a member is visible if it is <code class=\"prettyprint\nlang-java\">public</code> or <code class=\"prettyprint lang-java\">protected</code> and its containing\nclass is visible; and a record component is visible if its containing record is visible.\n\n</p><p>Additional Javadoc content may also be present, as explained in Section 7.3.4,\n<a href=\"#s7.3.4-javadoc-non-required\">Non-required Javadoc</a>.</p>\n\n<h4 id=\"s7.3.1-javadoc-exception-self-explanatory\">7.3.1 Exception: self-explanatory members</h4>\n\n<p>Javadoc is optional for \"simple, obvious\" members and record components, such as a\n<code class=\"prettyprint lang-java\">getFoo()</code> method, <em>if</em> there <em>really and\ntruly</em> is nothing else worthwhile to say but \"the foo\".</p>\n\n<p class=\"note\"><strong>Important:</strong> it is not appropriate to cite this exception to justify\nomitting relevant information that a typical reader might need to know. For example, for a record\ncomponent named <code class=\"prettyprint lang-java\">canonicalName</code>, don't omit its\ndocumentation (with the rationale that it would say only\n<code class=\"badcode\">@param canonicalName the canonical name</code>) if a typical reader may have\nno idea what the term \"canonical name\" means!</p>\n\n<h4 id=\"s7.3.2-javadoc-exception-overrides\">7.3.2 Exception: overrides</h4>\n\n<p>Javadoc is not always present on a method that overrides a supertype method.\n\n</p>\n\n\n\n<h4 id=\"s7.3.4-javadoc-non-required\">7.3.4 Non-required Javadoc</h4>\n\n<p>Other classes, members, and record components have Javadoc <em>as needed or desired</em>.\n\n</p><p>Whenever an implementation comment would be used to define the overall purpose or behavior of a\nclass or member, that comment is written as Javadoc instead (using <code>/**</code>).</p>\n\n<p>Non-required Javadoc is not strictly required to follow the formatting rules of Sections\n7.1.1, 7.1.2, 7.1.3, and 7.2, though it is of course recommended.</p>\n\n\n\n</div>\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "javascriptguide.xml",
    "content": "<?xml version = '1.0'?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google JavaScript Style Guide\">\n  <p style=\"position: fixed; left: 0; top: 0; padding: 0.5em; margin: 0; background-color: #fef6e0; text-align: center; width: 100%; font-weight: bold;\">\n    Please note: This guide is old and is not being updated. It is retained\n    as a reference as it was written for pre-ECMAScript 6th Edition features.\n    Please use the <a href=\"jsguide.html\">newer guide</a> instead.\n  </p>\n  <p class=\"revision\">\n    Revision 2.93\n  </p>\n\n  <address>\n    Aaron Whyte<br/>\n    Bob Jervis<br/>\n    Dan Pupius<br/>\n    Erik Arvidsson<br/>\n    Fritz Schneider<br/>\n    Robby Walker<br/>\n  </address>\n  <OVERVIEW>\n    <CATEGORY title=\"Important Note\">\n      <STYLEPOINT title=\"Displaying Hidden Details in this Guide\">\n        <SUMMARY>\n          This style guide contains many details that are initially\n          hidden from view.  They are marked by the triangle icon, which you\n          see here on your left.  Click it now.\n          You should see \"Hooray\" appear below.\n        </SUMMARY>\n        <BODY>\n          <p>\n            Hooray!  Now you know you can expand points to get more\n            details.  Alternatively, there's a \"toggle all\" at the\n            top of this document.\n          </p>\n        </BODY>\n      </STYLEPOINT>\n    </CATEGORY>\n    <CATEGORY title=\"Background\">\n      <p>\n        JavaScript is the main client-side scripting language used\n\n        by many of Google's open-source\n          projects.\n        This style guide is a list of <em>do</em>s and <em>don't</em>s for\n        JavaScript programs.\n      </p>\n\n\n\n\n\n    </CATEGORY>\n  </OVERVIEW>\n  <CATEGORY title=\"JavaScript Language Rules\">\n\n\n\n\n    <STYLEPOINT title=\"var\">\n      <SUMMARY>\n        Declarations with <code>var</code>: Always\n      </SUMMARY>\n      <BODY>\n        <DECISION>\n          When you fail to specify <code>var</code>,\n          the variable gets placed in the global context, potentially clobbering\n          existing values. Also, if there's no declaration, it's hard to tell in\n          what scope a variable lives (e.g., it could be in the Document or\n          Window just as easily as in the local scope). So always declare with\n          <code>var</code>.\n        </DECISION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Constants\">\n      <SUMMARY>\n        <ul>\n          <li>Use <code>NAMES_LIKE_THIS</code> for constant <em>values</em>.</li>\n          <li>Use <code>@const</code> to indicate a constant (non-overwritable)\n            <em>pointer</em> (a variable or property).</li>\n          <li>Never use the\n            <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Statements/const\">\n              <code>const</code> keyword</a>\n            as it's not supported in Internet Explorer.</li>\n        </ul>\n      </SUMMARY>\n      <BODY>\n        <DECISION>\n          <SUBSECTION title=\"Constant values\">\n\n          <p>If a value is intended to be <em>constant</em>\n             and <em>immutable</em>, it should be given a name\n             in <code>CONSTANT_VALUE_CASE</code>.\n             <code>ALL_CAPS</code> additionally implies <code>@const</code>\n             (that the value is not overwritable).\n           </p>\n\n           <p>Primitive types (<code>number</code>, <code>string</code>,\n             <code>boolean</code>) are constant values.</p>\n\n           <p><code>Objects</code>'\n             immutability is more subjective — objects should be\n             considered immutable only if they do not demonstrate observable\n             state change.  This is not enforced by the compiler.</p>\n\n\n           </SUBSECTION>\n\n          <SUBSECTION title=\"Constant pointers (variables and properties)\">\n            <p>The <code>@const</code> annotation on a variable or property\n              implies that it is not overwritable.  This is enforced by the\n              compiler at build time.  This behavior is consistent with the\n              <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Statements/const\">\n                <code>const</code> keyword</a> (which we do not use due to the\n              lack of support in Internet Explorer).</p>\n\n            <p>A <code>@const</code> annotation on a method additionally\n              implies that the method cannot not be overridden in subclasses.\n            </p>\n\n            <p>A <code>@const</code> annotation on a constructor implies the\n              class cannot be subclassed (akin to <code>final</code> in Java).\n            </p>\n\n          </SUBSECTION>\n\n          <SUBSECTION title=\"Examples\">\n\n            <p>Note that <code>@const</code> does not necessarily imply\n              <code>CONSTANT_VALUES_CASE</code>.\n\n              However, <code>CONSTANT_VALUES_CASE</code>\n              <em>does</em> imply <code>@const</code>.\n            </p>\n\n            <CODE_SNIPPET>\n              /**\n               * Request timeout in milliseconds.\n               * @type {number}\n               */\n              goog.example.TIMEOUT_IN_MILLISECONDS = 60;\n            </CODE_SNIPPET>\n\n            <p>The number of seconds in a minute never changes.  It is a\n              constant value.  <code>ALL_CAPS</code>\n              also implies <code>@const</code>, so the constant cannot be\n              overwritten.\n            </p>\n\n            <p>The open source compiler will allow the symbol to be\n              overwritten because the constant is\n              <em>not</em> marked as <code>@const</code>.</p>\n\n            <CODE_SNIPPET>\n              /**\n               * Map of URL to response string.\n               * @const\n               */\n              MyClass.fetchedUrlCache_ = new goog.structs.Map();\n            </CODE_SNIPPET>\n\n            <CODE_SNIPPET>\n              /**\n               * Class that cannot be subclassed.\n               * @const\n               * @constructor\n               */\n              sloth.MyFinalClass = function() {};\n            </CODE_SNIPPET>\n\n            <p>In this case, the pointer can never be overwritten, but\n              value is highly mutable and <b>not</b> constant (and thus in\n              <code>camelCase</code>, not <code>ALL_CAPS</code>).</p>\n        </SUBSECTION>\n\n        </DECISION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Semicolons\">\n      <SUMMARY>\n        Always use semicolons.\n      </SUMMARY>\n      <BODY>\n        <p>Relying on implicit insertion can cause subtle, hard to debug\n          problems. Don't do it. You're better than that.</p>\n        <p>There are a couple places where missing semicolons are particularly\n          dangerous:</p>\n        <BAD_CODE_SNIPPET>\n          // 1.\n          MyClass.prototype.myMethod = function() {\n            return 42;\n          }  // No semicolon here.\n\n          (function() {\n            // Some initialization code wrapped in a function to create a scope for locals.\n          })();\n\n\n          var x = {\n            'i': 1,\n            'j': 2\n          }  // No semicolon here.\n\n          // 2.  Trying to do one thing on Internet Explorer and another on Firefox.\n          // I know you'd never write code like this, but throw me a bone.\n          [ffVersion, ieVersion][isIE]();\n\n\n          var THINGS_TO_EAT = [apples, oysters, sprayOnCheese]  // No semicolon here.\n\n          // 3. conditional execution a la bash\n          -1 == resultOfOperation() || die();\n        </BAD_CODE_SNIPPET>\n        <SUBSECTION title=\"So what happens?\">\n          <ol>\n            <li>JavaScript error - first the function returning 42 is called\n              with the second function as a parameter, then the number 42 is\n              \"called\" resulting in an error.</li>\n            <li>You will most likely get a 'no such property in undefined'\n              error at runtime as it tries to call\n              <code>x[ffVersion, ieVersion][isIE]()</code>.</li>\n            <li><code>die</code> is always called since the array minus 1 is\n              <code>NaN</code> which is never equal to anything (not even if\n              <code>resultOfOperation()</code> returns <code>NaN</code>) and\n              <code>THINGS_TO_EAT</code> gets assigned the result of\n              <code>die()</code>.</li>\n          </ol>\n        </SUBSECTION>\n        <SUBSECTION title=\"Why?\">\n          <p>JavaScript requires statements to end with a semicolon, except when\n            it thinks it can safely infer their existence. In each of these\n            examples, a function declaration or object or array literal is used\n            inside a statement. The closing brackets are not enough to signal\n            the end of the statement. Javascript never ends a statement if the\n            next token is an infix or bracket operator.</p>\n          <p>This has really surprised people, so make sure your assignments end\n            with semicolons.</p>\n        </SUBSECTION>\n        <SUBSECTION title=\"Clarification: Semicolons and functions\">\n          <p>Semicolons should be included at the end of function expressions,\n            but not at the end of function declarations. The distinction is\n            best illustrated with an example:</p>\n          <CODE_SNIPPET>\n            var foo = function() {\n              return true;\n            };  // semicolon here.\n\n            function foo() {\n              return true;\n            }  // no semicolon here.\n          </CODE_SNIPPET>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Nested functions\">\n      <SUMMARY>Yes</SUMMARY>\n      <BODY>\n        <p>Nested functions can be very useful, for example in the creation of\n          continuations and for the task of hiding helper functions. Feel free\n          to use them.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Function Declarations Within Blocks\">\n      <SUMMARY>No</SUMMARY>\n      <BODY>\n        <p>Do not do this:</p>\n        <BAD_CODE_SNIPPET>\n          if (x) {\n            function foo() {}\n          }\n        </BAD_CODE_SNIPPET>\n\n        <p>While most script engines support Function Declarations within blocks\n          it is not part of ECMAScript (see\n          <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\">ECMA-262</a>,\n          clause 13 and 14). Worse implementations are inconsistent with each\n          other and with future EcmaScript proposals. ECMAScript only allows for\n          Function Declarations in the root statement list of a script or\n          function. Instead use a variable initialized with a Function\n          Expression to define a function within a block:</p>\n        <CODE_SNIPPET>\n           if (x) {\n             var foo = function() {};\n           }\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Exceptions\">\n      <SUMMARY>Yes</SUMMARY>\n      <BODY>\n        <p>You basically can't avoid exceptions if you're doing something\n          non-trivial (using an application development framework, etc.).\n          Go for it.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Custom exceptions\">\n      <SUMMARY>Yes</SUMMARY>\n      <BODY>\n        <p>Without custom exceptions, returning error information from a\n          function that also returns a value can be tricky, not to mention\n          inelegant.  Bad solutions include passing in a reference type to hold\n          error information or always returning Objects with a potential\n          error member.  These basically amount to a primitive exception\n          handling hack. Feel free to use custom exceptions when\n          appropriate.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Standards features\">\n      <SUMMARY>Always preferred over non-standards features</SUMMARY>\n      <BODY>\n        <p>For maximum portability and compatibility, always prefer standards\n          features over non-standards features (e.g.,\n          <code>string.charAt(3)</code> over <code>string[3]</code> and element\n          access with DOM functions instead of using an application-specific\n          shorthand).</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Wrapper objects for primitive types\">\n      <SUMMARY>No</SUMMARY>\n      <BODY>\n        <p>There's no reason to use wrapper objects for primitive types, plus\n          they're dangerous:</p>\n        <BAD_CODE_SNIPPET>\n          var x = new Boolean(false);\n          if (x) {\n            alert('hi');  // Shows 'hi'.\n          }\n        </BAD_CODE_SNIPPET>\n        <p>Don't do it!</p>\n        <p>However type casting is fine.</p>\n        <CODE_SNIPPET>\n          var x = Boolean(0);\n          if (x) {\n            alert('hi');  // This will never be alerted.\n          }\n          typeof Boolean(0) == 'boolean';\n          typeof new Boolean(0) == 'object';\n        </CODE_SNIPPET>\n        <p>This is very useful for casting things to\n          <code>number</code>, <code>string</code> and <code>boolean</code>.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Multi-level prototype hierarchies\">\n      <SUMMARY>Not preferred</SUMMARY>\n      <BODY>\n        <p>Multi-level prototype hierarchies are how JavaScript implements\n          inheritance. You have a multi-level hierarchy if you have a\n          user-defined class D with another user-defined class B as its\n          prototype. These hierarchies are much harder to get right than they\n          first appear! </p>\n\n        <p>For that reason, it is best to use <code>goog.inherits()</code> from\n          <a href=\"https://code.google.com/closure/library/\">\n            the Closure Library\n          </a>\n          or a similar library function.\n        </p>\n        <CODE_SNIPPET>\n          function D() {\n            goog.base(this)\n          }\n          goog.inherits(D, B);\n\n          D.prototype.method = function() {\n            ...\n          };\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Method and property definitions\">\n      <SUMMARY><code>/** @constructor */\n        function SomeConstructor() {\n          this.someProperty = 1;\n        }\n        Foo.prototype.someMethod = function() { ... };</code></SUMMARY>\n      <BODY>\n        <p>While there are several ways to attach methods and properties to an\n          object created via \"new\", the preferred style for methods\n          is:</p>\n        <CODE_SNIPPET>\n          Foo.prototype.bar = function() {\n            /* ... */\n          };\n        </CODE_SNIPPET>\n        <p>The preferred style for other properties is to initialize the field\n          in the constructor:</p>\n        <CODE_SNIPPET>\n          /** @constructor */\n          function Foo() {\n            this.bar = value;\n          }\n        </CODE_SNIPPET>\n        <SUBSECTION title=\"Why?\">\n          <p>Current JavaScript engines optimize based on the \"shape\"\n            of an object, <a href=\"https://developers.google.com/v8/design#prop_access\">\n            adding a property to an object (including overriding\n            a value set on the prototype) changes the shape and can degrade\n            performance.</a></p>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"delete\">\n      <SUMMARY>Prefer <code>this.foo = null</code>.</SUMMARY>\n      <BODY>\n        <CODE_SNIPPET>\n          Foo.prototype.dispose = function() {\n            this.property_ = null;\n          };\n        </CODE_SNIPPET>\n        <p>Instead of:</p>\n        <BAD_CODE_SNIPPET>\n          Foo.prototype.dispose = function() {\n            delete this.property_;\n          };\n        </BAD_CODE_SNIPPET>\n        <p>In modern JavaScript engines, changing the number of properties on an\n          object is much slower than reassigning the values. The delete keyword\n          should be avoided except when it is necessary to remove a property\n          from an object's iterated list of keys, or to change the result of\n          <code>if (key in obj)</code>.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Closures\">\n      <SUMMARY>Yes, but be careful.</SUMMARY>\n      <BODY>\n        <p>The ability to create closures is perhaps the most useful and often\n          overlooked feature of JS. Here is\n          <a href=\"http://jibbering.com/faq/faq_notes/closures.html\">\n            a good description of how closures work</a>.</p>\n        <p>One thing to keep in mind, however, is that a closure keeps a pointer\n          to its enclosing scope. As a result, attaching a closure to a DOM\n          element can create a circular reference and thus, a memory leak. For\n          example, in the following code:</p>\n        <BAD_CODE_SNIPPET>\n          function foo(element, a, b) {\n            element.onclick = function() { /* uses a and b */ };\n          }\n        </BAD_CODE_SNIPPET>\n        <p>the function closure keeps a reference to <code>element</code>,\n          <code>a</code>, and <code>b</code> even if it never uses\n          <code>element</code>. Since <code>element</code> also keeps a\n          reference to the closure, we have a cycle that won't be cleaned up by\n          garbage collection. In these situations, the code can be structured\n          as follows:</p>\n        <CODE_SNIPPET>\n          function foo(element, a, b) {\n            element.onclick = bar(a, b);\n          }\n\n          function bar(a, b) {\n            return function() { /* uses a and b */ };\n          }\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"eval()\">\n      <SUMMARY>\n        Only for code loaders and REPL (Read–eval–print loop)\n      </SUMMARY>\n      <BODY>\n        <p><code>eval()</code> makes for confusing semantics and is dangerous\n          to use if the string being <code>eval()</code>'d contains user input.\n          There's usually a better, clearer, and safer way to write your code,\n          so its use is generally not permitted.</p>\n\n        <p>For RPC you can always use JSON and read the result using\n          <code>JSON.parse()</code> instead of <code>eval()</code>.</p>\n\n        <p>Let's assume we have a server that returns something like this:</p>\n\n        <CODE_SNIPPET>\n          {\n            \"name\": \"Alice\",\n            \"id\": 31502,\n            \"email\": \"looking_glass@example.com\"\n          }\n        </CODE_SNIPPET>\n\n        <BAD_CODE_SNIPPET>\n          var userInfo = eval(feed);\n          var email = userInfo['email'];\n        </BAD_CODE_SNIPPET>\n\n        <p>If the feed was modified to include malicious JavaScript code, then\n          if we use <code>eval</code> then that code will be executed.</p>\n\n        <CODE_SNIPPET>\n          var userInfo = JSON.parse(feed);\n          var email = userInfo['email'];\n        </CODE_SNIPPET>\n\n        <p>With <code>JSON.parse</code>, invalid JSON (including all executable\n          JavaScript) will cause an exception to be thrown.</p>\n\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"with() {}\">\n      <SUMMARY>No</SUMMARY>\n      <BODY>\n        <p>Using <code>with</code> clouds the semantics of your program.\n          Because the object of the <code>with</code> can have properties that\n          collide with local variables, it can drastically change the meaning\n          of your program. For example, what does this do?</p>\n        <BAD_CODE_SNIPPET>\n          with (foo) {\n            var x = 3;\n            return x;\n          }\n        </BAD_CODE_SNIPPET>\n        <p>Answer: anything. The local variable <code>x</code> could be\n          clobbered by a property of <code>foo</code> and perhaps it even has\n          a setter, in which case assigning <code>3</code> could cause lots of\n          other code to execute. Don't use <code>with</code>.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"this\">\n      <SUMMARY>\n        Only in object constructors, methods, and in setting up closures\n      </SUMMARY>\n      <BODY>\n        <p>The semantics of <code>this</code> can be tricky. At times it refers\n          to the global object (in most places), the scope of the caller (in\n          <code>eval</code>), a node in the DOM tree (when attached using an\n          event handler HTML attribute), a newly created object (in a\n          constructor), or some other object (if function was\n          <code>call()</code>ed or <code>apply()</code>ed).</p>\n        <p>Because this is so easy to get wrong, limit its use to those places\n          where it is required:</p>\n        <ul>\n          <li>in constructors</li>\n          <li>in methods of objects (including in the creation of closures)</li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"for-in loop\">\n      <SUMMARY>\n        Only for iterating over keys in an object/map/hash\n      </SUMMARY>\n      <BODY>\n        <p><code>for-in</code> loops are often incorrectly used to loop over\n          the elements in an <code>Array</code>. This is however very error\n          prone because it does not loop from <code>0</code> to\n          <code>length - 1</code> but over all the present keys in the object\n          and its prototype chain. Here are a few cases where it fails:</p>\n        <BAD_CODE_SNIPPET>\n          function printArray(arr) {\n            for (var key in arr) {\n              print(arr[key]);\n            }\n          }\n\n          printArray([0,1,2,3]);  // This works.\n\n          var a = new Array(10);\n          printArray(a);  // This is wrong.\n\n          a = document.getElementsByTagName('*');\n          printArray(a);  // This is wrong.\n\n          a = [0,1,2,3];\n          a.buhu = 'wine';\n          printArray(a);  // This is wrong again.\n\n          a = new Array;\n          a[3] = 3;\n          printArray(a);  // This is wrong again.\n        </BAD_CODE_SNIPPET>\n        <p>Always use normal for loops when using arrays.</p>\n        <CODE_SNIPPET>\n          function printArray(arr) {\n            var l = arr.length;\n            for (var i = 0; i &lt; l; i++) {\n              print(arr[i]);\n            }\n          }\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Associative Arrays\">\n      <SUMMARY>\n        Never use <code>Array</code> as a map/hash/associative array\n      </SUMMARY>\n      <BODY>\n        <p>Associative <code>Array</code>s are not allowed... or more precisely\n          you are not allowed to use non number indexes for arrays. If you need\n          a map/hash use <code>Object</code> instead of <code>Array</code> in\n          these cases because the features that you want are actually features\n          of <code>Object</code> and not of <code>Array</code>.\n          <code>Array</code> just happens to extend <code>Object</code> (like\n          any other object in JS and therefore you might as well have used\n          <code>Date</code>, <code>RegExp</code> or <code>String</code>).</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Multiline string literals\">\n      <SUMMARY>No</SUMMARY>\n      <BODY>\n        <p>Do not do this:</p>\n        <BAD_CODE_SNIPPET>\n          var myString = 'A rather long string of English text, an error message \\\n                          actually that just keeps going and going -- an error \\\n                          message to make the Energizer bunny blush (right through \\\n                          those Schwarzenegger shades)! Where was I? Oh yes, \\\n                          you\\'ve got an error and all the extraneous whitespace is \\\n                          just gravy.  Have a nice day.';\n        </BAD_CODE_SNIPPET>\n        <p>The whitespace at the beginning of each line can't be safely stripped\n          at compile time; whitespace after the slash will result in tricky\n          errors. </p>\n        <p>Use string concatenation instead:</p>\n        <CODE_SNIPPET>\n          var myString = 'A rather long string of English text, an error message ' +\n              'actually that just keeps going and going -- an error ' +\n              'message to make the Energizer bunny blush (right through ' +\n              'those Schwarzenegger shades)! Where was I? Oh yes, ' +\n              'you\\'ve got an error and all the extraneous whitespace is ' +\n              'just gravy.  Have a nice day.';\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Array and Object literals\">\n      <SUMMARY>Yes</SUMMARY>\n      <BODY>\n        <p>Use <code>Array</code> and <code>Object</code> literals instead of\n          <code>Array</code> and <code>Object</code> constructors.</p>\n        <p>Array constructors are error-prone due to their arguments.</p>\n        <BAD_CODE_SNIPPET>\n          // Length is 3.\n          var a1 = new Array(x1, x2, x3);\n\n          // Length is 2.\n          var a2 = new Array(x1, x2);\n\n          // If x1 is a number and it is a natural number the length will be x1.\n          // If x1 is a number but not a natural number this will throw an exception.\n          // Otherwise the array will have one element with x1 as its value.\n          var a3 = new Array(x1);\n\n          // Length is 0.\n          var a4 = new Array();\n        </BAD_CODE_SNIPPET>\n        <p>Because of this, if someone changes the code to pass 1 argument\n          instead of 2 arguments, the array might not have the expected\n          length.</p>\n        <p>To avoid these kinds of weird cases, always use the more readable\n          array literal.</p>\n        <CODE_SNIPPET>\n          var a = [x1, x2, x3];\n          var a2 = [x1, x2];\n          var a3 = [x1];\n          var a4 = [];\n        </CODE_SNIPPET>\n        <p>Object constructors don't have the same problems, but for readability\n          and consistency object literals should be used.</p>\n        <BAD_CODE_SNIPPET>\n          var o = new Object();\n\n          var o2 = new Object();\n          o2.a = 0;\n          o2.b = 1;\n          o2.c = 2;\n          o2['strange key'] = 3;\n        </BAD_CODE_SNIPPET>\n        <p>Should be written as:</p>\n        <CODE_SNIPPET>\n          var o = {};\n\n          var o2 = {\n            a: 0,\n            b: 1,\n            c: 2,\n            'strange key': 3\n          };\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Modifying prototypes of builtin objects\">\n      <SUMMARY>No</SUMMARY>\n      <BODY>\n        <p>Modifying builtins like <code>Object.prototype</code> and\n          <code>Array.prototype</code> are strictly forbidden.  Modifying other\n          builtins like <code>Function.prototype</code> is less dangerous but\n          still leads to hard to debug issues in production and should be\n          avoided.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Internet Explorer's Conditional Comments\">\n      <SUMMARY>No</SUMMARY>\n      <BODY>\n        <p>Don't do this:</p>\n        <BAD_CODE_SNIPPET>\n        var f = function () {\n            /*@cc_on if (@_jscript) { return 2* @*/  3; /*@ } @*/\n        };\n        </BAD_CODE_SNIPPET>\n        <p>Conditional Comments hinder automated tools as they can vary the\n        JavaScript syntax tree at runtime.</p>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n\n  <CATEGORY title=\"JavaScript Style Rules\">\n    <STYLEPOINT title=\"Naming\">\n      <SUMMARY>\n        <p>In general, use\n          <code>functionNamesLikeThis</code>,\n          <code>variableNamesLikeThis</code>,\n          <code>ClassNamesLikeThis</code>,\n          <code>EnumNamesLikeThis</code>,\n          <code>methodNamesLikeThis</code>,\n          <code>CONSTANT_VALUES_LIKE_THIS</code>,\n          <code>foo.namespaceNamesLikeThis.bar</code>, and\n          <code>filenameslikethis.js</code>.\n        </p>\n      </SUMMARY>\n      <BODY>\n        <SUBSECTION title=\"Properties and methods\">\n          <ul>\n            <li><em>Private</em> properties and methods should be named with a\n              trailing underscore.\n              </li>\n            <li><em>Protected</em> properties and methods should be\n              named without a trailing underscore (like public ones).</li>\n          </ul>\n          <p>For more information on <em>private</em> and <em>protected</em>,\n            read the section on\n            <a href=\"#Visibility__private_and_protected_fields_\">\n              visibility</a>.\n            </p>\n\n\n\n\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Method and function parameter\">\n          <p>Optional function arguments start with <code>opt_</code>.</p>\n          <p>Functions that take a variable number of arguments should have the\n            last argument named <code>var_args</code>. You may not refer to\n            <code>var_args</code> in the code; use the <code>arguments</code>\n            array.</p>\n          <p>Optional and variable arguments can also be specified in\n            <code>@param</code> annotations. Although either convention is\n            acceptable to the compiler, using both together is preferred.</p>\n\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Getters and Setters\">\n          <p>EcmaScript 5 getters and setters for properties are discouraged.\n            However, if they are used, then getters must not change observable\n            state.</p>\n            <BAD_CODE_SNIPPET>\n              /**\n               * WRONG -- Do NOT do this.\n               */\n              var foo = { get next() { return this.nextId++; } };\n            </BAD_CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Accessor functions\">\n          <p>Getters and setters methods for properties are not required.\n            However, if they are used, then getters must be named\n            <code>getFoo()</code> and setters must be named\n            <code>setFoo(value)</code>. (For boolean getters,\n            <code>isFoo()</code> is also acceptable, and often sounds more\n            natural.)</p>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Namespaces\">\n          <p>JavaScript has no inherent packaging or namespacing support.</p>\n          <p>Global name conflicts are difficult to debug, and can cause\n            intractable problems when two projects try to integrate. In order\n            to make it possible to share common JavaScript code, we've adopted\n            conventions to prevent collisions. </p>\n          <SUBSUBSECTION title=\"Use namespaces for global code\">\n            <p><em>ALWAYS</em> prefix identifiers in the global scope with a\n              unique pseudo namespace related to the project or library. If you\n              are working on \"Project Sloth\", a reasonable pseudo namespace\n              would be <code>sloth.*</code>.</p>\n            <CODE_SNIPPET>\n              var sloth = {};\n\n              sloth.sleep = function() {\n                ...\n              };\n            </CODE_SNIPPET>\n\n\n            <p>Many JavaScript libraries, including\n              <a href=\"https://code.google.com/closure/library/\">\n                the Closure Library\n              </a>\n              and\n              <a href=\"http://www.dojotoolkit.org/\">\n                Dojo toolkit\n              </a>\n              give you high-level functions for declaring your namespaces.\n              Be consistent about how you declare your namespaces.</p>\n            <CODE_SNIPPET>\n              goog.provide('sloth');\n\n              sloth.sleep = function() {\n                ...\n              };\n            </CODE_SNIPPET>\n          </SUBSUBSECTION>\n          <SUBSUBSECTION title=\"Respect namespace ownership\">\n            <p>When choosing a child-namespace, make sure that the owners of the\n              parent namespace know what you are doing. If you start a project\n              that creates hats for sloths, make sure that the Sloth team knows\n              that you're using <code>sloth.hats</code>.</p>\n\n          </SUBSUBSECTION>\n          <SUBSUBSECTION title=\"Use different namespaces for external code and internal code\">\n            <p>\"External code\" is code that comes from outside your codebase,\n              and is compiled independently. Internal and external names should\n              be kept strictly separate. If you're using an external library\n              that makes things available in <code>foo.hats.*</code>, your\n              internal code should not define all its symbols in\n              <code>foo.hats.*</code>, because it will break if the other\n              team defines new symbols.</p>\n            <BAD_CODE_SNIPPET>\n              foo.require('foo.hats');\n\n              /**\n               * WRONG -- Do NOT do this.\n               * @constructor\n               * @extends {foo.hats.RoundHat}\n               */\n              foo.hats.BowlerHat = function() {\n              };\n            </BAD_CODE_SNIPPET>\n            <p>If you need to define new APIs on an external namespace, then you\n              should explicitly export the public API functions, and only those\n              functions. Your internal code should call the internal APIs by\n              their internal names, for consistency and so that the compiler\n              can optimize them better.</p>\n            <CODE_SNIPPET>\n              foo.provide('googleyhats.BowlerHat');\n\n              foo.require('foo.hats');\n\n              /**\n               * @constructor\n               * @extends {foo.hats.RoundHat}\n               */\n              googleyhats.BowlerHat = function() {\n                ...\n              };\n\n              goog.exportSymbol('foo.hats.BowlerHat', googleyhats.BowlerHat);\n            </CODE_SNIPPET>\n\n\n          </SUBSUBSECTION>\n          <SUBSUBSECTION title=\"Alias long type names to improve readability\">\n            <p>Use local aliases for fully-qualified types if doing so improves\n              readability. The name of a local alias should match the last part\n              of the type.</p>\n            <CODE_SNIPPET>\n              /**\n               * @constructor\n               */\n              some.long.namespace.MyClass = function() {\n              };\n\n              /**\n               * @param {some.long.namespace.MyClass} a\n               */\n              some.long.namespace.MyClass.staticHelper = function(a) {\n                ...\n              };\n\n              myapp.main = function() {\n                var MyClass = some.long.namespace.MyClass;\n                var staticHelper = some.long.namespace.MyClass.staticHelper;\n                staticHelper(new MyClass());\n              };\n            </CODE_SNIPPET>\n            <p>Do not create local aliases of namespaces. Namespaces should only\n              be aliased using <a href=\"#goog-scope\">goog.scope</a>.</p>\n            <BAD_CODE_SNIPPET>\n              myapp.main = function() {\n                var namespace = some.long.namespace;\n                namespace.MyClass.staticHelper(new namespace.MyClass());\n              };\n            </BAD_CODE_SNIPPET>\n            <p>Avoid accessing properties of an aliased type, unless it is an\n              enum.</p>\n            <CODE_SNIPPET>\n              /** @enum {string} */\n              some.long.namespace.Fruit = {\n                APPLE: 'a',\n                BANANA: 'b'\n              };\n\n              myapp.main = function() {\n                var Fruit = some.long.namespace.Fruit;\n                switch (fruit) {\n                  case Fruit.APPLE:\n                    ...\n                  case Fruit.BANANA:\n                    ...\n                }\n              };\n            </CODE_SNIPPET>\n            <BAD_CODE_SNIPPET>\n              myapp.main = function() {\n                var MyClass = some.long.namespace.MyClass;\n                MyClass.staticHelper(null);\n              };\n            </BAD_CODE_SNIPPET>\n            <p>Never create aliases in the global scope. Use them only in\n              function blocks.</p>\n          </SUBSUBSECTION>\n        </SUBSECTION>\n        <SUBSECTION title=\"Filenames\">\n          <p>Filenames should be all lowercase in order to avoid confusion on\n            case-sensitive platforms. Filenames should end in <code>.js</code>,\n            and should contain no punctuation except for <code>-</code> or\n            <code>_</code> (prefer <code>-</code> to <code>_</code>).</p>\n        </SUBSECTION>\n\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Custom toString() methods\">\n      <SUMMARY>\n        Must always succeed without side effects.\n      </SUMMARY>\n      <BODY>\n        <p>You can control how your objects string-ify themselves by defining a\n          custom <code>toString()</code> method. This is fine, but you need\n          to ensure that your method (1) always succeeds and (2) does not have\n          side-effects. If your method doesn't meet these criteria, it's very\n          easy to run into serious problems. For example, if\n          <code>toString()</code> calls a method that does an\n          <code>assert</code>, <code>assert</code> might try to output the name\n          of the object in which it failed, which of course requires calling\n          <code>toString()</code>.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Deferred initialization\">\n      <SUMMARY>OK</SUMMARY>\n      <BODY>\n        <p>It isn't always possible to initialize variables at the point of\n          declaration, so deferred initialization is fine.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Explicit scope\">\n      <SUMMARY>Always</SUMMARY>\n      <BODY>\n        <p>Always use explicit scope - doing so increases portability and\n          clarity. For example, don't rely on <code>window</code> being in the\n          scope chain. You might want to use your function in another\n          application for which <code>window</code> is not the content\n          window.</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Code formatting\">\n      <SUMMARY>Expand for more information.</SUMMARY>\n      <BODY>\n        <p>We follow the <a href=\"cppguide.html#Formatting\">C++ formatting\n          rules</a> in spirit, with the following additional clarifications.</p>\n        <SUBSECTION title=\"Curly Braces\">\n          <p>Because of implicit semicolon insertion, always start your curly\n            braces on the same line as whatever they're opening.  For\n            example:</p>\n          <CODE_SNIPPET>\n            if (something) {\n              // ...\n            } else {\n              // ...\n            }\n          </CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Array and Object Initializers\">\n          <p>Single-line array and object initializers are allowed when they\n            fit on a line:</p>\n          <CODE_SNIPPET>\n            var arr = [1, 2, 3];  // No space after [ or before ].\n            var obj = {a: 1, b: 2, c: 3};  // No space after { or before }.\n          </CODE_SNIPPET>\n          <p>Multiline array initializers and object initializers are indented\n            2 spaces, with the braces on their own line, just like blocks.</p>\n          <CODE_SNIPPET>\n            // Object initializer.\n            var inset = {\n              top: 10,\n              right: 20,\n              bottom: 15,\n              left: 12\n            };\n\n            // Array initializer.\n            this.rows_ = [\n              '\"Slartibartfast\" &lt;fjordmaster@magrathea.com&gt;',\n              '\"Zaphod Beeblebrox\" &lt;theprez@universe.gov&gt;',\n              '\"Ford Prefect\" &lt;ford@theguide.com&gt;',\n              '\"Arthur Dent\" &lt;has.no.tea@gmail.com&gt;',\n              '\"Marvin the Paranoid Android\" &lt;marv@googlemail.com&gt;',\n              'the.mice@magrathea.com'\n            ];\n\n            // Used in a method call.\n            goog.dom.createDom(goog.dom.TagName.DIV, {\n              id: 'foo',\n              className: 'some-css-class',\n              style: 'display:none'\n            }, 'Hello, world!');\n          </CODE_SNIPPET>\n          <p>Long identifiers or values present problems for aligned\n            initialization lists, so always prefer non-aligned initialization.\n            For example:</p>\n          <CODE_SNIPPET>\n            CORRECT_Object.prototype = {\n              a: 0,\n              b: 1,\n              lengthyName: 2\n            };\n          </CODE_SNIPPET>\n          <p>Not like this:</p>\n          <BAD_CODE_SNIPPET>\n            WRONG_Object.prototype = {\n              a          : 0,\n              b          : 1,\n              lengthyName: 2\n            };\n          </BAD_CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Function Arguments\">\n          <p>When possible, all function arguments should be listed on the same\n            line. If doing so would exceed the 80-column limit, the arguments\n            must be line-wrapped in a readable way. To save space, you may wrap\n            as close to 80 as possible, or put each argument on its own line to\n            enhance readability. The indentation may be either four spaces, or\n            aligned to the parenthesis. Below are the most common patterns for\n            argument wrapping:</p>\n          <CODE_SNIPPET>\n            // Four-space, wrap at 80.  Works with very long function names, survives\n            // renaming without reindenting, low on space.\n            goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(\n                veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,\n                tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {\n              // ...\n            };\n\n            // Four-space, one argument per line.  Works with long function names,\n            // survives renaming, and emphasizes each argument.\n            goog.foo.bar.doThingThatIsVeryDifficultToExplain = function(\n                veryDescriptiveArgumentNumberOne,\n                veryDescriptiveArgumentTwo,\n                tableModelEventHandlerProxy,\n                artichokeDescriptorAdapterIterator) {\n              // ...\n            };\n\n            // Parenthesis-aligned indentation, wrap at 80.  Visually groups arguments,\n            // low on space.\n            function foo(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,\n                         tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {\n              // ...\n            }\n\n            // Parenthesis-aligned, one argument per line.  Emphasizes each\n            // individual argument.\n            function bar(veryDescriptiveArgumentNumberOne,\n                         veryDescriptiveArgumentTwo,\n                         tableModelEventHandlerProxy,\n                         artichokeDescriptorAdapterIterator) {\n              // ...\n            }\n          </CODE_SNIPPET>\n          <p>When the function call is itself indented, you're free to start the\n          4-space indent relative to the beginning of the original statement\n          or relative to the beginning of the current function call.\n          The following are all acceptable indentation styles.</p>\n          <CODE_SNIPPET>\n            if (veryLongFunctionNameA(\n                    veryLongArgumentName) ||\n                veryLongFunctionNameB(\n                veryLongArgumentName)) {\n              veryLongFunctionNameC(veryLongFunctionNameD(\n                  veryLongFunctioNameE(\n                      veryLongFunctionNameF)));\n            }\n          </CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Passing Anonymous Functions\">\n          <p>When declaring an anonymous function in the list of arguments for\n            a function call, the body of the function is indented two spaces\n            from the left edge of the statement, or two spaces from the left\n            edge of the function keyword. This is to make the body of the\n            anonymous function easier to read (i.e. not be all squished up into\n            the right half of the screen).</p>\n          <CODE_SNIPPET>\n            prefix.something.reallyLongFunctionName('whatever', function(a1, a2) {\n              if (a1.equals(a2)) {\n                someOtherLongFunctionName(a1);\n              } else {\n                andNowForSomethingCompletelyDifferent(a2.parrot);\n              }\n            });\n\n            var names = prefix.something.myExcellentMapFunction(\n                verboselyNamedCollectionOfItems,\n                function(item) {\n                  return item.name;\n                });\n          </CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Aliasing with goog.scope\">\n          <a name=\"goog-scope\"/>\n          <p>\n            <a href=\"https://docs.google.com/document/pub?id=1ETFAuh2kaXMVL-vafUYhaWlhl6b5D9TOvboVg7Zl68Y\"><code>goog.scope</code></a>\n            may be used to shorten references to\n            namespaced symbols in programs using\n            <a href=\"https://code.google.com/closure/library/\">the Closure\n              Library</a>.</p>\n          <p>Only one <code>goog.scope</code> invocation may be added per\n            file.  Always place it in the global scope.</p>\n          <p>The opening <code>goog.scope(function() {</code> invocation\n            must be preceded by exactly one blank line and follow any\n            <code>goog.provide</code> statements, <code>goog.require</code>\n            statements, or top-level comments.  The invocation must be closed on\n            the last line in the file.  Append <code>// goog.scope</code> to the\n            closing statement of the scope. Separate the comment from the\n            semicolon by two spaces.</p>\n          <p>Similar to C++ namespaces, do not indent under goog.scope\n            declarations. Instead, continue from the 0 column.</p>\n          <p>Only alias names that will not be re-assigned to another object\n            (e.g., most constructors, enums, and namespaces). Do not do\n            this (see below for how to alias a constructor):</p>\n\n          <BAD_CODE_SNIPPET>\n            goog.scope(function() {\n            var Button = goog.ui.Button;\n\n            Button = function() { ... };\n            ...\n          </BAD_CODE_SNIPPET>\n\n          <p>Names must be the same as the last property of the global that they\n            are aliasing.</p>\n\n          <CODE_SNIPPET>\n            goog.provide('my.module.SomeType');\n\n            goog.require('goog.dom');\n            goog.require('goog.ui.Button');\n\n            goog.scope(function() {\n            var Button = goog.ui.Button;\n            var dom = goog.dom;\n\n            // Alias new types <b>after</b> the constructor declaration.\n            my.module.SomeType = function() { ... };\n            var SomeType = my.module.SomeType;\n\n            // Declare methods on the prototype as usual:\n            SomeType.prototype.findButton = function() {\n              // Button as aliased above.\n              this.button = new Button(dom.getElement('my-button'));\n            };\n            ...\n            });  // goog.scope\n          </CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Indenting wrapped lines\">\n          <p>Except for <a href=\"#Array_and_Object_literals\">array literals,\n            object literals</a>, and anonymous functions, all wrapped lines\n            should be indented either left-aligned to a sibling expression\n            above, or four spaces (not two spaces) deeper than a parent\n            expression (where \"sibling\" and \"parent\" refer to parenthesis\n            nesting level).\n          </p>\n\n          <CODE_SNIPPET>\n            someWonderfulHtml = '<div class=\"' + getClassesForWonderfulHtml()'\">' +\n                                getEvenMoreHtml(someReallyInterestingValues, moreValues,\n                                                evenMoreParams, 'a duck', true, 72,\n                                                slightlyMoreMonkeys(0xfff)) +\n                                '</div>';\n\n            thisIsAVeryLongVariableName =\n                hereIsAnEvenLongerOtherFunctionNameThatWillNotFitOnPrevLine();\n\n            thisIsAVeryLongVariableName = siblingOne + siblingTwo + siblingThree +\n                siblingFour + siblingFive + siblingSix + siblingSeven +\n                moreSiblingExpressions + allAtTheSameIndentationLevel;\n\n            thisIsAVeryLongVariableName = operandOne + operandTwo + operandThree +\n                operandFour + operandFive * (\n                    aNestedChildExpression + shouldBeIndentedMore);\n\n            someValue = this.foo(\n                shortArg,\n                'Some really long string arg - this is a pretty common case, actually.',\n                shorty2,\n                this.bar());\n\n            if (searchableCollection(allYourStuff).contains(theStuffYouWant) &amp;&amp;\n                !ambientNotification.isActive() &amp;&amp; (client.isAmbientSupported() ||\n                                                    client.alwaysTryAmbientAnyways())) {\n              ambientNotification.activate();\n            }\n          </CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Blank lines\">\n          <p>Use newlines to group logically related pieces of code.\n            For example:</p>\n          <CODE_SNIPPET>\n            doSomethingTo(x);\n            doSomethingElseTo(x);\n            andThen(x);\n\n            nowDoSomethingWith(y);\n\n            andNowWith(z);\n          </CODE_SNIPPET>\n        </SUBSECTION>\n        <SUBSECTION title=\"Binary and Ternary Operators\">\n          <p>Always put the operator on the preceding line. Otherwise,\n            line breaks and indentation follow the same rules as in other\n            Google style guides. This operator placement was initially agreed\n            upon out of concerns about automatic semicolon insertion. In fact,\n            semicolon insertion cannot happen before a binary operator, but new\n            code should stick to this style for consistency.</p>\n          <CODE_SNIPPET>\n            var x = a ? b : c;  // All on one line if it will fit.\n\n            // Indentation +4 is OK.\n            var y = a ?\n                longButSimpleOperandB : longButSimpleOperandC;\n\n            // Indenting to the line position of the first operand is also OK.\n            var z = a ?\n                    moreComplicatedB :\n                    moreComplicatedC;\n          </CODE_SNIPPET>\n          <p>This includes the dot operator.</p>\n          <CODE_SNIPPET>\n            var x = foo.bar().\n                doSomething().\n                doSomethingElse();\n          </CODE_SNIPPET>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Parentheses\">\n      <SUMMARY>Only where required</SUMMARY>\n      <BODY>\n        <p>Use sparingly and in general only where required by the syntax\n          and semantics.</p>\n        <p>Never use parentheses for unary operators such as\n          <code>delete</code>, <code>typeof</code> and <code>void</code> or\n          after keywords such as <code>return</code>, <code>throw</code> as\n          well as others (<code>case</code>, <code>in</code> or\n          <code>new</code>).</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Strings\">\n      <SUMMARY>Prefer ' over \"</SUMMARY>\n      <BODY>\n        <p>For consistency single-quotes (') are preferred to double-quotes (\").\n          This is helpful when creating strings that include HTML:</p>\n        <CODE_SNIPPET>\n          var msg = 'This is <a href=\"http://foo\">some HTML</a>';\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Visibility (private and protected fields)\">\n      <SUMMARY>Encouraged, use JSDoc annotations <code>@private</code> and\n        <code>@protected</code></SUMMARY>\n      <BODY>\n        <p>We recommend the use of the JSDoc annotations <code>@private</code> and\n          <code>@protected</code> to indicate visibility levels for classes,\n          functions, and properties.</p>\n        <p>The --jscomp_warning=visibility compiler flag turns on compiler\n          warnings for visibility violations. See\n          <a href=\"https://code.google.com/p/closure-compiler/wiki/Warnings\">\n            Closure Compiler\n          Warnings</a>.\n        </p>\n        <p><code>@private</code> global variables and functions are only\n          accessible to code in the same file.</p>\n        <p>Constructors marked <code>@private</code> may only be instantiated by\n          code in the same file and by their static and instance members.\n          <code>@private</code> constructors may also be accessed anywhere in the\n          same file for their public static properties and by the\n          <code>instanceof</code> operator.</p>\n        <p>Global variables, functions, and constructors should never be\n          annotated <code>@protected</code>.</p>\n        <CODE_SNIPPET>\n          // File 1.\n          // AA_PrivateClass_ and AA_init_ are accessible because they are global\n          // and in the same file.\n\n          /**\n           * @private\n           * @constructor\n           */\n          AA_PrivateClass_ = function() {\n          };\n\n          /** @private */\n          function AA_init_() {\n            return new AA_PrivateClass_();\n          }\n\n          AA_init_();\n        </CODE_SNIPPET>\n        <p><code>@private</code> properties are accessible to all code in the\n          same file, plus all static methods and instance methods of that class\n          that \"owns\" the property, if the property belongs to a class. They\n          cannot be accessed or overridden from a subclass in a different file.</p>\n        <p><code>@protected</code> properties are accessible to all code in the\n          same file, plus any static methods and instance methods of any subclass\n          of a class that \"owns\" the property.</p>\n        <p>Note that these semantics differ from those of C++ and Java, in that\n          they grant private and protected access to all code in the same file,\n          not just in the same class or class hierarchy. Also, unlike in C++,\n          private properties cannot be overridden by a subclass.\n        </p>\n        <CODE_SNIPPET>\n          // File 1.\n\n          /** @constructor */\n          AA_PublicClass = function() {\n            /** @private */\n            this.privateProp_ = 2;\n\n            /** @protected */\n            this.protectedProp = 4;\n          };\n\n          /** @private */\n          AA_PublicClass.staticPrivateProp_ = 1;\n\n          /** @protected */\n          AA_PublicClass.staticProtectedProp = 31;\n\n          /** @private */\n          AA_PublicClass.prototype.privateMethod_ = function() {};\n\n          /** @protected */\n          AA_PublicClass.prototype.protectedMethod = function() {};\n\n          // File 2.\n\n          /**\n           * @return {number} The number of ducks we've arranged in a row.\n           */\n          AA_PublicClass.prototype.method = function() {\n            // Legal accesses of these two properties.\n            return this.privateProp_ + AA_PublicClass.staticPrivateProp_;\n          };\n\n          // File 3.\n\n          /**\n           * @constructor\n           * @extends {AA_PublicClass}\n           */\n          AA_SubClass = function() {\n            // Legal access of a protected static property.\n            AA_PublicClass.staticProtectedProp = this.method();\n          };\n          goog.inherits(AA_SubClass, AA_PublicClass);\n\n          /**\n           * @return {number} The number of ducks we've arranged in a row.\n           */\n          AA_SubClass.prototype.method = function() {\n            // Legal access of a protected instance property.\n            return this.protectedProp;\n          };\n        </CODE_SNIPPET>\n\n        <p>Notice that in JavaScript, there is no distinction between a type\n        (like  <code>AA_PrivateClass_</code>) and the constructor for that\n        type. There is no way to express both that a type is public and its\n        constructor is private (because the constructor could easily be aliased\n        in a way that would defeat the privacy check).</p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"JavaScript Types\">\n      <SUMMARY>Encouraged and enforced by the compiler.</SUMMARY>\n      <BODY>\n        <a name=\"JsTypes\"/>\n        <p>When documenting a type in JSDoc, be as specific and accurate as\n          possible. The types we support are based on the\n          <a href=\"http://wiki.ecmascript.org/doku.php?id=spec:spec\">\n            EcmaScript 4 spec</a>.</p>\n        <SUBSECTION title=\"The JavaScript Type Language\">\n          <p>The ES4 proposal contained a language for specifying JavaScript\n            types. We use this language in JsDoc to express the types of\n            function parameters and return values.</p>\n\n          <p>As the ES4 proposal has evolved, this language has changed. The\n            compiler still supports old syntaxes for types, but those syntaxes\n            are deprecated.</p>\n\n          <p/>\n          <table border=\"1\" style=\"border-collapse:collapse\" cellpadding=\"4\">\n            <thead>\n              <tr>\n                <th>Syntax Name</th>\n                <th>Syntax</th>\n                <th>Description</th>\n                <th>Deprecated Syntaxes</th>\n              </tr>\n            </thead>\n            <tbody>\n              <tr>\n                <td>Primitive Type</td>\n                <td>\n                  There are 5 primitive types in JavaScript:\n                  <code>{null}</code>,\n                  <code>{undefined}</code>,\n                  <code>{boolean}</code>,\n                  <code>{number}</code>, and\n                  <code>{string}</code>.\n                </td>\n                <td>Simply the name of a type.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Instance Type</td>\n                <td>\n                  <code>{Object}</code><br/>\n                  An instance of Object or null.<p/>\n                  <code>{Function}</code><br/>\n                  An instance of Function or null.<p/>\n                  <code>{EventTarget}</code><br/>\n                  An instance of a constructor that implements the EventTarget\n                  interface, or null.\n                </td>\n                <td>An instance of a constructor or interface function.<p/>\n\n                Constructor functions are functions defined with the\n                <code>@constructor</code> JSDoc tag.\n                Interface functions are functions defined with the\n                <code>@interface</code> JSDoc tag.<p/>\n\n                By default, instance types will accept null. This is the only\n\t\ttype syntax that makes the type nullable. Other type syntaxes\n\t\tin this table will not accept null.\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Enum Type</td>\n                <td>\n                  <code>{goog.events.EventType}</code><br/>\n                  One of the properties of the object literal initializer\n                  of <code>goog.events.EventType</code>.\n                </td>\n                <td>An enum must be initialized as an object literal, or as\n                an alias of another enum, annotated with the <code>@enum</code>\n                JSDoc tag. The properties of this literal are the instances\n                of the enum. The syntax of the enum is defined\n                <a href=\"#enums\">below</a>.<p/>\n\n                Note that this is one of the few things in our type system\n                that were not in the ES4 spec.\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Type Application</td>\n                <td>\n                  <code>{Array.&lt;string&gt;}</code><br/>An array of strings.<p/>\n                  <code>{Object.&lt;string, number&gt;}</code>\n                  <br/>An object in which the keys are strings and the values\n                  are numbers.\n                </td>\n                <td>Parameterizes a type, by applying a set of type arguments\n                  to that type. The idea is analogous to generics in Java.\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Type Union</td>\n                <td>\n                  <code>{(number|boolean)}</code><br/>A number or a boolean.\n                </td>\n                <td>Indicates that a value might have type A OR type B.<p/>\n\n                  The parentheses may be omitted at the top-level\n                  expression, but the parentheses should be included in\n                  sub-expressions to avoid ambiguity.<br/>\n                  <code>{number|boolean}</code><br/>\n                  <code>{function(): (number|boolean)}</code>\n                </td>\n                <td>\n                  <code>{(number,boolean)}</code>,<br/>\n                  <code>{(number||boolean)}</code>\n                </td>\n              </tr>\n\n              <tr>\n                <td>Nullable type</td>\n                <td>\n                  <code>{?number}</code><br/> A number or null.\n                </td>\n                <td>Shorthand for the union of the null type with any\n                other type. This is just syntactic sugar.\n                </td>\n                <td>\n                  <code>{number?}</code>\n                </td>\n              </tr>\n\n              <tr>\n                <td>Non-nullable type</td>\n                <td>\n                  <code>{!Object}</code><br/> An Object, but never the\n                  <code>null</code> value.\n                </td>\n                <td>Filters null out of nullable types. Most often used\n                with instance types, which are nullable by default.\n                </td>\n                <td>\n                  <code>{Object!}</code>\n                </td>\n              </tr>\n\n              <tr>\n                <td>Record Type</td>\n                <td>\n                  <code>{{myNum: number, myObject}}</code>\n                  <br/>An anonymous type with the given type members.\n                </td>\n                <td>\n                  <p>Indicates that the value has the specified members with the\n                    specified types. In this case, <code>myNum</code> with a\n                    type <code>number</code> and <code>myObject</code> with any\n                    type.</p>\n                  <p>Notice that the braces are part of the type syntax. For\n                    example, to denote an <code>Array</code> of objects that\n                    have a <code>length</code> property, you might write\n                  <code>Array.&lt;{length}&gt;</code>.</p>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Function Type</td>\n                <td>\n                  <code>{function(string, boolean)}</code><br/>\n                  A function that takes two arguments (a string and a boolean),\n                  and has an unknown return value.<br/>\n                </td>\n                <td>Specifies a function.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Function Return Type</td>\n                <td>\n                  <code>{function(): number}</code><br/>\n                  A function that takes no arguments and returns a number.<br/>\n                </td>\n                <td>Specifies a function return type.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Function <code>this</code> Type</td>\n                <td>\n                  <code>{function(this:goog.ui.Menu, string)}</code><br/>\n                  A function that takes one argument (a string), and executes\n                  in the context of a goog.ui.Menu.\n                </td>\n                <td>Specifies the context type of a function type.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Function <code>new</code> Type</td>\n                <td>\n                  <code>{function(new:goog.ui.Menu, string)}</code><br/>\n                  A constructor that takes one argument (a string), and\n                  creates a new instance of goog.ui.Menu when called\n                  with the 'new' keyword.\n                </td>\n                <td>Specifies the constructed type of a constructor.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Variable arguments</td>\n                <td>\n                  <code>{function(string, ...[number]): number}</code><br/>\n                  A function that takes one argument (a string), and then a\n                  variable number of arguments that must be numbers.\n                </td>\n                <td>Specifies variable arguments to a function.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>\n                  <a name=\"var-args-annotation\"/>\n                  Variable arguments (in <code>@param</code> annotations)\n                </td>\n                <td>\n                  <code>@param {...number} var_args</code><br/>\n                  A variable number of arguments to an annotated function.\n                </td>\n                <td>\n                  Specifies that the annotated function accepts a variable\n                  number of arguments.\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Function <a href=\"#optional\">optional arguments</a></td>\n                <td>\n                  <code>{function(?string=, number=)}</code><br/>\n                  A function that takes one optional, nullable string and one\n                  optional number as arguments. The <code>=</code> syntax is\n                  only for <code>function</code> type declarations.\n                </td>\n                <td>Specifies optional arguments to a function.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>\n                  <a name=\"optional-arg-annotation\"/>\n                  Function <a href=\"#optional\">optional arguments</a>\n                  (in <code>@param</code> annotations)\n                </td>\n                <td>\n                  <code>@param {number=} opt_argument</code><br/>\n                  An optional parameter of type <code>number</code>.\n                </td>\n                <td>Specifies that the annotated function accepts an optional\n                  argument.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>The ALL type</td>\n                <td><code>{*}</code></td>\n                <td>Indicates that the variable can take on any type.</td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>The UNKNOWN type</td>\n                <td><code>{?}</code></td>\n                <td>Indicates that the variable can take on any type,\n                    and the compiler should not type-check any uses of it.</td>\n                <td/>\n              </tr>\n            </tbody>\n          </table>\n        </SUBSECTION>\n        <SUBSECTION title=\"Types in JavaScript\">\n          <p/>\n          <table border=\"1\" style=\"border-collapse:collapse\" cellpadding=\"4\">\n            <thead>\n              <tr>\n                <th>Type Example</th>\n                <th>Value Examples</th>\n                <th>Description</th>\n              </tr>\n            </thead>\n            <tbody>\n\n              <tr>\n                <td>number</td>\n                <td>\n                  <CODE_SNIPPET>\n                    1\n                    1.0\n                    -5\n                    1e5\n                    Math.PI\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Number</td>\n                <td>\n                  <CODE_SNIPPET>\n                    new Number(true)\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <a href=\"#Wrapper_objects_for_primitive_types\">\n                    Number object\n                  </a>\n                </td>\n              </tr>\n\n              <tr>\n                <td>string</td>\n                <td>\n                  <CODE_SNIPPET>\n                    'Hello'\n                    \"World\"\n                    String(42)\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  String value\n                </td>\n              </tr>\n\n              <tr>\n                <td>String</td>\n                <td>\n                  <CODE_SNIPPET>\n                    new String('Hello')\n                    new String(42)\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <a href=\"#Wrapper_objects_for_primitive_types\">\n                    String object\n                  </a>\n                </td>\n              </tr>\n\n              <tr>\n                <td>boolean</td>\n                <td>\n                  <CODE_SNIPPET>\n                    true\n                    false\n                    Boolean(0)\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Boolean value\n                </td>\n              </tr>\n\n              <tr>\n                <td>Boolean</td>\n                <td>\n                  <CODE_SNIPPET>\n                    new Boolean(true)\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <a href=\"#Wrapper_objects_for_primitive_types\">\n                    Boolean object\n                  </a>\n                </td>\n              </tr>\n\n              <tr>\n                <td>RegExp</td>\n                <td>\n                  <CODE_SNIPPET>\n                    new RegExp('hello')\n                    /world/g\n                  </CODE_SNIPPET></td><td>\n                </td>\n              </tr>\n\n              <tr>\n                <td>Date</td>\n                <td>\n                  <CODE_SNIPPET>\n                    new Date\n                    new Date()\n                  </CODE_SNIPPET></td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>\n\n                  null\n\n                </td>\n                <td>\n                  <CODE_SNIPPET>\n                    null\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>\n\n                  undefined\n\n                </td>\n                <td>\n                  <CODE_SNIPPET>\n                    undefined\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>void</td>\n                <td>\n                  <CODE_SNIPPET>\n                    function f() {\n                      return;\n                    }\n                  </CODE_SNIPPET>\n                </td>\n                <td>No return value</td>\n              </tr>\n\n              <tr>\n                <td>Array</td>\n                <td>\n                  <CODE_SNIPPET>\n                    ['foo', 0.3, null]\n                    []\n                  </CODE_SNIPPET>\n                </td>\n                <td>Untyped Array</td>\n              </tr>\n\n              <tr>\n                <td>Array.&lt;number&gt;</td>\n                <td>\n                  <CODE_SNIPPET>\n                    [11, 22, 33]\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  An Array of numbers\n                </td>\n              </tr>\n\n              <tr>\n                <td>Array.&lt;Array.&lt;string&gt;&gt;</td>\n                <td>\n                  <CODE_SNIPPET>\n                    [['one', 'two', 'three'], ['foo', 'bar']]\n                  </CODE_SNIPPET>\n                </td>\n                <td>Array of Arrays of strings</td>\n              </tr>\n\n              <tr>\n                <td>Object</td>\n                <td>\n                  <CODE_SNIPPET>\n                    {}\n                    {foo: 'abc', bar: 123, baz: null}\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>Object.&lt;string&gt;</td>\n                <td>\n                  <CODE_SNIPPET>\n                    {'foo': 'bar'}\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  An Object in which the values are strings.\n                </td>\n              </tr>\n\n              <tr>\n                <td>Object.&lt;number, string&gt;</td>\n                <td>\n                  <CODE_SNIPPET>\n                    var obj = {};\n                    obj[1] = 'bar';\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  An Object in which the keys are numbers and the values are\n                  strings.  <p/>Note that in JavaScript, the keys are always\n                  implicitly converted to strings, so\n                  <code>obj['1'] == obj[1]</code>.\n                  So the key will always be a string in for...in loops. But the\n                  compiler will verify the type of the key when indexing into\n                  the object.\n                </td>\n              </tr>\n\n              <tr>\n                <td>Function</td>\n                <td>\n                  <CODE_SNIPPET>\n                    function(x, y) {\n                      return x * y;\n                    }\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <a href=\"#Wrapper_objects_for_primitive_types\">\n                    Function object\n                  </a>\n                </td>\n              </tr>\n\n              <tr>\n                <td>function(number, number): number</td>\n                <td>\n                  <CODE_SNIPPET>\n                    function(x, y) {\n                      return x * y;\n                    }\n                  </CODE_SNIPPET>\n                </td>\n                <td>function value</td>\n              </tr>\n\n              <tr>\n                <td><a name=\"constructor-tag\">SomeClass</a></td>\n                <td>\n                  <CODE_SNIPPET>\n                    /** @constructor */\n                    function SomeClass() {}\n\n                    new SomeClass();\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>SomeInterface</td>\n                <td>\n                  <CODE_SNIPPET>\n                    /** @interface */\n                    function SomeInterface() {}\n\n                    SomeInterface.prototype.draw = function() {};\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>project.MyClass</td>\n                <td>\n                  <CODE_SNIPPET>\n                    /** @constructor */\n                    project.MyClass = function () {}\n\n                    new project.MyClass()\n                  </CODE_SNIPPET>\n                </td>\n                <td/>\n              </tr>\n\n              <tr>\n                <td>project.MyEnum</td>\n                <td>\n                  <CODE_SNIPPET>\n                    /** @enum {string} */\n                    project.MyEnum = {\n                      /** The color blue. */\n                      BLUE: '#0000dd',\n                      /** The color red. */\n                      RED: '#dd0000'\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td><a name=\"enums\">Enumeration</a><p/>\n                  JSDoc comments on enum values are optional.\n                </td>\n              </tr>\n\n              <tr>\n                <td>Element</td>\n                <td>\n                  <CODE_SNIPPET>\n                    document.createElement('div')\n                  </CODE_SNIPPET>\n                </td>\n                <td>Elements in the DOM.</td>\n              </tr>\n\n              <tr>\n                <td>Node</td>\n                <td>\n                  <CODE_SNIPPET>\n                    document.body.firstChild\n                  </CODE_SNIPPET>\n                </td>\n                <td>Nodes in the DOM.</td>\n              </tr>\n\n              <tr>\n                <td>HTMLInputElement</td>\n                <td>\n                  <CODE_SNIPPET>\n                    htmlDocument.getElementsByTagName('input')[0]\n                  </CODE_SNIPPET>\n                </td>\n                <td>A specific type of DOM element.</td>\n              </tr>\n            </tbody>\n          </table>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Type Casts\">\n          <p>In cases where type-checking doesn't accurately infer the type of\n            an expression, it is possible to add a type cast comment by adding a\n            type annotation comment and enclosing the expression in\n            parentheses. The parentheses are required.</p>\n\n          <CODE_SNIPPET>\n            /** @type {number} */ (x)\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Nullable vs. Optional Parameters and Properties\">\n          <a name=\"optional\"/>\n          <p>Because JavaScript is a loosely-typed language, it is very\n            important to understand the subtle differences between optional,\n            nullable, and undefined function parameters and class\n            properties.</p>\n\n          <p>Instances of classes and interfaces are nullable by default.\n          For example, the following declaration</p>\n\n          <CODE_SNIPPET>\n            /**\n             * Some class, initialized with a value.\n             * @param {Object} value Some value.\n             * @constructor\n             */\n            function MyClass(value) {\n              /**\n               * Some value.\n               * @type {Object}\n               * @private\n               */\n              this.myValue_ = value;\n            }\n          </CODE_SNIPPET>\n\n          <p>tells the compiler that the <code>myValue_</code> property holds\n            either an Object or null.  If <code>myValue_</code> must never be\n            null, it should be declared like this:</p>\n\n          <CODE_SNIPPET>\n            /**\n             * Some class, initialized with a non-null value.\n             * @param {!Object} value Some value.\n             * @constructor\n             */\n            function MyClass(value) {\n              /**\n               * Some value.\n               * @type {!Object}\n               * @private\n               */\n              this.myValue_ = value;\n            }\n          </CODE_SNIPPET>\n\n          <p>This way, if the compiler can determine that somewhere in the code\n            <code>MyClass</code> is initialized with a null value, it will issue\n            a warning.</p>\n\n\n\n          <p>Optional parameters to functions may be undefined at runtime, so if\n          they are assigned to class properties, those properties must be\n          declared accordingly:</p>\n\n          <CODE_SNIPPET>\n            /**\n             * Some class, initialized with an optional value.\n             * @param {Object=} opt_value Some value (optional).\n             * @constructor\n             */\n            function MyClass(opt_value) {\n              /**\n               * Some value.\n               * @type {Object|undefined}\n               * @private\n               */\n              this.myValue_ = opt_value;\n            }\n          </CODE_SNIPPET>\n\n          <p>This tells the compiler that <code>myValue_</code> may hold an\n            Object, null, or remain undefined.</p>\n\n          <p>Note that the optional parameter <code>opt_value</code> is declared\n            to be of type <code>{Object=}</code>, not\n            <code>{Object|undefined}</code>.  This is because optional\n            parameters may, by definition, be undefined.  While there is no harm\n            in explicitly declaring an optional parameter as possibly undefined,\n            it is both unnecessary and makes the code harder to read.</p>\n\n          <p>Finally, note that being nullable and being optional are orthogonal\n            properties.  The following four declarations are all different:</p>\n\n          <CODE_SNIPPET>\n            /**\n             * Takes four arguments, two of which are nullable, and two of which are\n             * optional.\n             * @param {!Object} nonNull Mandatory (must not be undefined), must not be null.\n             * @param {Object} mayBeNull Mandatory (must not be undefined), may be null.\n             * @param {!Object=} opt_nonNull Optional (may be undefined), but if present,\n             *     must not be null!\n             * @param {Object=} opt_mayBeNull Optional (may be undefined), may be null.\n             */\n            function strangeButTrue(nonNull, mayBeNull, opt_nonNull, opt_mayBeNull) {\n              // ...\n            };\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Typedefs\">\n          <a name=\"Typedefs\"/>\n          <p>Sometimes types can get complicated. A function that accepts\n            content for an Element might look like:</p>\n\n          <CODE_SNIPPET>\n            /**\n             * @param {string} tagName\n             * @param {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} contents\n             * @return {!Element}\n             */\n            goog.createElement = function(tagName, contents) {\n              ...\n            };\n          </CODE_SNIPPET>\n\n          <p>You can define commonly used type expressions with a\n            <code>@typedef</code> tag. For example,</p>\n\n          <CODE_SNIPPET>\n            /** @typedef {(string|Element|Text|Array.&lt;Element&gt;|Array.&lt;Text&gt;)} */\n            goog.ElementContent;\n\n            /**\n             * @param {string} tagName\n             * @param {goog.ElementContent} contents\n             * @return {!Element}\n             */\n            goog.createElement = function(tagName, contents) {\n            ...\n            };\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Template types\">\n          <a name=\"Template_types\"/>\n          <p>The compiler has limited support for template types. It can only\n            infer the type of <code>this</code> inside an anonymous function\n            literal from the type of the <code>this</code> argument and whether the\n            <code>this</code> argument is missing.</p>\n\n          <CODE_SNIPPET>\n            /**\n             * @param {function(this:T, ...)} fn\n             * @param {T} thisObj\n             * @param {...*} var_args\n             * @template T\n             */\n            goog.bind = function(fn, thisObj, var_args) {\n            ...\n            };\n            // Possibly generates a missing property warning.\n            goog.bind(function() { this.someProperty; }, new SomeClass());\n            // Generates an undefined this warning.\n            goog.bind(function() { this.someProperty; });\n          </CODE_SNIPPET>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Comments\">\n      <SUMMARY>Use JSDoc</SUMMARY>\n      <BODY>\n        <p>\n          We follow the\n          <a href=\"cppguide.html#Comments\">\n            C++ style for comments</a> in spirit.\n        </p>\n\n        <p>All files, classes, methods and properties should be documented with\n          <a href=\"https://code.google.com/p/jsdoc-toolkit/\">JSDoc</a>\n          comments with the appropriate <a href=\"#JSDoc_Tag_Reference\">tags</a>\n          and <a href=\"#JsTypes\">types</a>. Textual descriptions for properties,\n          methods, method parameters and method return values should be included\n          unless obvious from the property, method, or parameter name.\n        </p>\n\n        <p>Inline comments should be of the <code>//</code> variety.</p>\n\n        <p>Complete sentences are recommended but not required.\n        Complete sentences should use appropriate capitalization\n        and punctuation.</p>\n\n        <SUBSECTION title=\"Comment Syntax\">\n          <p>The JSDoc syntax is based on\n          <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\">\n          JavaDoc</a>. Many tools extract metadata from JSDoc comments to\n          perform code validation and optimizations. These comments must be\n          well-formed.</p>\n\n          <CODE_SNIPPET>\n          /**\n           * A JSDoc comment should begin with a slash and 2 asterisks.\n           * Inline tags should be enclosed in braces like {@code this}.\n           * @desc Block tags should always start on their own line.\n           */\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"JSDoc Indentation\">\n          <p>If you have to line break a block tag, you should treat this as\n          breaking a code statement and indent it four spaces.</p>\n\n          <CODE_SNIPPET>\n            /**\n             * Illustrates line wrapping for long param/return descriptions.\n             * @param {string} foo This is a param with a description too long to fit in\n             *     one line.\n             * @return {number} This returns something that has a description too long to\n             *     fit in one line.\n             */\n            project.MyClass.prototype.method = function(foo) {\n              return 5;\n            };\n          </CODE_SNIPPET>\n\n          <p>You should not indent the <code>@fileoverview</code> command. You do not have to\n            indent the <code>@desc</code> command.</p>\n\n          <p>Even though it is not preferred, it is also acceptable to line up\n             the description.</p>\n\n          <CODE_SNIPPET>\n            /**\n             * This is NOT the preferred indentation method.\n             * @param {string} foo This is a param with a description too long to fit in\n             *                     one line.\n             * @return {number} This returns something that has a description too long to\n             *                  fit in one line.\n             */\n            project.MyClass.prototype.method = function(foo) {\n              return 5;\n            };\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"HTML in JSDoc\">\n          <p>Like JavaDoc, JSDoc supports many HTML tags, like &lt;code&gt;,\n            &lt;pre&gt;, &lt;tt&gt;, &lt;strong&gt;, &lt;ul&gt;, &lt;ol&gt;,\n            &lt;li&gt;, &lt;a&gt;, and others.</p>\n\n          <p>This means that plaintext formatting is not respected. So, don't\n            rely on whitespace to format JSDoc:</p>\n\n          <BAD_CODE_SNIPPET>\n            /**\n             * Computes weight based on three factors:\n             *   items sent\n             *   items received\n             *   last timestamp\n             */\n          </BAD_CODE_SNIPPET>\n\n          <p>It'll come out like this:</p>\n\n          <BAD_CODE_SNIPPET>\n          Computes weight based on three factors: items sent items received last timestamp\n          </BAD_CODE_SNIPPET>\n\n          <p>Instead, do this:</p>\n\n          <CODE_SNIPPET>\n            /**\n             * Computes weight based on three factors:\n             * &lt;ul&gt;\n             * &lt;li&gt;items sent\n             * &lt;li&gt;items received\n             * &lt;li&gt;last timestamp\n             * &lt;/ul&gt;\n             */\n          </CODE_SNIPPET>\n\n          The <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\">\n          JavaDoc</a> style guide is a useful resource on how to write\n          well-formed doc comments.\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Top/File-Level Comments\">\n          <p>\n\n            A <a href=\"copyright.html\">copyright notice</a> and author information are optional.\n            File overviews are generally recommended whenever a file consists of\n            more than a single class definition. The top level comment is\n            designed to orient readers unfamiliar with the code to what is in\n            this file.  If present, it should provide a description of the\n            file's contents and any dependencies or compatibility information.\n            As an example:\n          </p>\n\n          <CODE_SNIPPET>\n            /**\n             * @fileoverview Description of file, its uses and information\n             * about its dependencies.\n             */\n          </CODE_SNIPPET>\n\n\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Class Comments\">\n          <p>Classes must be documented with a description and a\n            <a href=\"#constructor-tag\">type tag that\n              identifies the constructor</a>.\n          </p>\n\n          <CODE_SNIPPET>\n            /**\n             * Class making something fun and easy.\n             * @param {string} arg1 An argument that makes this more interesting.\n             * @param {Array.&lt;number&gt;} arg2 List of numbers to be processed.\n             * @constructor\n             * @extends {goog.Disposable}\n             */\n            project.MyClass = function(arg1, arg2) {\n              // ...\n            };\n            goog.inherits(project.MyClass, goog.Disposable);\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Method and Function Comments\">\n          <p>Parameter and return types should be documented. The method\n             description may be omitted if it is obvious from the parameter\n             or return type descriptions. Method descriptions should start\n             with a sentence written in the third person declarative voice.</p>\n          <CODE_SNIPPET>\n            /**\n             * Operates on an instance of MyClass and returns something.\n             * @param {project.MyClass} obj Instance of MyClass which leads to a long\n             *     comment that needs to be wrapped to two lines.\n             * @return {boolean} Whether something occurred.\n             */\n            function PR_someMethod(obj) {\n              // ...\n            }\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Property Comments\">\n          <CODE_SNIPPET>\n            /** @constructor */\n            project.MyClass = function() {\n              /**\n               * Maximum number of things per pane.\n               * @type {number}\n               */\n              this.someProperty = 4;\n            }\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"JSDoc Tag Reference\">\n          <a name=\"JSDoc_Tag_Reference\"/>\n          <p/>\n          <table border=\"1\" style=\"border-collapse:collapse\" cellpadding=\"4\">\n            <thead>\n              <tr>\n                <th>Tag</th>\n                <th>Template &amp; Examples</th>\n                <th>Description</th>\n              </tr>\n            </thead>\n            <tbody>\n              <tr>\n                <td>\n                  <a name=\"tag-author\">@author</a>\n\n                </td>\n                <td>\n                  <code>@author username@google.com (first last)</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @fileoverview Utilities for handling textareas.\n                     * @author kuth@google.com (Uthur Pendragon)\n                     */\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Document the author of a file or the owner of a test,\n                  generally only used in the <code>@fileoverview</code> comment.\n\n                </td>\n              </tr>\n\n\n\n              <tr>\n                <td><a name=\"tag-code\">@code</a></td>\n                <td>\n                  <code>{@code ...}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Moves to the next position in the selection.\n                     * Throws {@code goog.iter.StopIteration} when it\n                     * passes the end of the range.\n                     * @return {Node} The node at the next position.\n                     */\n                    goog.dom.RangeIterator.prototype.next = function() {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Indicates that a term in a JSDoc description is code so it may\n                  be correctly formatted in generated documentation.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-const\">@const</a></td>\n                <td>\n                  <code>@const</code><br/>\n                  <code>@const {type}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @const */ var MY_BEER = 'stout';\n\n                    /**\n                     * My namespace's favorite kind of beer.\n                     * @const {string}\n                     */\n                    mynamespace.MY_BEER = 'stout';\n\n                    /** @const */ MyClass.MY_BEER = 'stout';\n\n                    /**\n                     * Initializes the request.\n                     * @const\n                     */\n                    mynamespace.Request.prototype.initialize = function() {\n                      // This method cannot be overridden in a subclass.\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <p>Marks a variable (or property) as read-only and suitable\n                  for inlining.</p>\n\n                  <p>A <code>@const</code> variable is an immutable pointer to\n                  a value.  If a variable or property marked as\n                  <code>@const</code> is overwritten, JSCompiler will give\n                  warnings.</p>\n\n                  <p>The type declaration of a constant value can be omitted\n                    if it can be clearly inferred. An additional comment about\n                    the variable is optional.</p>\n\n                  <p>When <code>@const</code> is applied to a method, it\n                    implies the method is not only not overwritable, but also\n                    that the method is <em>finalized</em> —\n                    not overridable in subclasses.</p>\n\n                  <p>For more on <code>@const</code>, see the\n                    <a href=\"#Constants\">Constants</a> section.</p>\n\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-constructor\">@constructor</a></td>\n                <td>\n                  <code>@constructor</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * A rectangle.\n                     * @constructor\n                     */\n                    function GM_Rect() {\n                      ...\n                    }\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used in a class's documentation to indicate the constructor.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-define\">@define</a></td>\n                <td>\n                  <code>@define {Type} description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @define {boolean} */\n                    var TR_FLAGS_ENABLE_DEBUG = true;\n\n                    /**\n                     * @define {boolean} Whether we know at compile-time that\n                     *     the browser is IE.\n                     */\n                    goog.userAgent.ASSUME_IE = false;\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Indicates a constant that can be overridden by the compiler at\n                  compile-time. In the example, the compiler flag\n                  <code>--define='goog.userAgent.ASSUME_IE=true'</code>\n                  could be specified in the BUILD file to indicate that the\n                  constant <code>goog.userAgent.ASSUME_IE</code> should be replaced\n                  with <code>true</code>.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-deprecated\">@deprecated</a></td>\n                <td>\n                  <code>@deprecated Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Determines whether a node is a field.\n                     * @return {boolean} True if the contents of\n                     *     the element are editable, but the element\n                     *     itself is not.\n                     * @deprecated Use isField().\n                     */\n                    BN_EditUtil.isTopEditableField = function(node) {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used to tell that a function, method or property should not be\n                  used any more.  Always provide instructions on what callers\n                  should use instead.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-dict\">@dict</a></td>\n                <td>\n                  <code>@dict Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @constructor\n                     * @dict\n                     */\n                    function Foo(x) {\n                      this['x'] = x;\n                    }\n                    var obj = new Foo(123);\n                    var num = obj.x;  // warning\n\n                    (/** @dict */ { x: 1 }).x = 123;  // warning\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  When a constructor (<code>Foo</code> in the example) is\n                  annotated with <code>@dict</code>, you can only use the\n                  bracket notation to access the properties of <code>Foo</code>\n                  objects.\n                  The annotation can also be used directly on object literals.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-enum\">@enum</a></td>\n                <td>\n                  <code>@enum {Type}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Enum for tri-state values.\n                     * @enum {number}\n                     */\n                    project.TriState = {\n                      TRUE: 1,\n                      FALSE: -1,\n                      MAYBE: 0\n                    };\n                  </CODE_SNIPPET>\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-export\">@export</a></td>\n                <td>\n                  <code>@export</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @export */\n                    foo.MyPublicClass.prototype.myPublicMethod = function() {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <p>Given the code on the left, when the compiler is run with\n                  the <code>--generate_exports</code> flag, it will generate the\n                  code:</p>\n                  <CODE_SNIPPET>\n                    goog.exportSymbol('foo.MyPublicClass.prototype.myPublicMethod',\n                        foo.MyPublicClass.prototype.myPublicMethod);\n                  </CODE_SNIPPET>\n                  <p>which will export the symbols to uncompiled code.\n                  Code that uses the <code>@export</code> annotation must either</p>\n                  <ol>\n                    <li>include <code>//javascript/closure/base.js</code>, or</li>\n                    <li>define both <code>goog.exportSymbol</code> and\n                      <code>goog.exportProperty</code> with the same method\n                      signature in their own codebase.</li>\n                  </ol>\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-expose\">@expose</a></td>\n                <td>\n                  <code>@expose</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @expose */\n                    MyClass.prototype.exposedProperty = 3;\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <p>\n                    Declares an exposed property. Exposed properties\n                    will not be removed, or renamed, or collapsed,\n                    or optimized in any way by the compiler. No properties\n                    with the same name will be able to be optimized either.\n                  </p>\n\n                  <p>\n                    <code>@expose</code> should never be used in library code,\n                    because it will prevent that property from ever getting\n                    removed.\n                  </p>\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-extends\">@extends</a></td>\n                <td>\n                  <code>\n                    @extends Type<br/>\n                    @extends {Type}\n                  </code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Immutable empty node list.\n                     * @constructor\n                     * @extends goog.ds.BasicNodeList\n                     */\n                    goog.ds.EmptyNodeList = function() {\n                      ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used with <code>@constructor</code> to indicate that a class\n                  inherits from another class. Curly braces around the type are\n                  optional.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-externs\">@externs</a></td>\n                <td>\n                  <code>@externs</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @fileoverview This is an externs file.\n                     * @externs\n                     */\n\n                    var document;\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <p>\n                    Declares an\n\n                    externs file.\n                  </p>\n\n\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-fileoverview\">@fileoverview</a></td>\n                <td>\n                  <code>@fileoverview Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @fileoverview Utilities for doing things that require this very long\n                     * but not indented comment.\n                     * @author kuth@google.com (Uthur Pendragon)\n                     */\n                  </CODE_SNIPPET>\n                </td>\n                <td>Makes the comment block provide file level information.</td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-implements\">@implements</a></td>\n                <td>\n                  <code>\n                    @implements Type<br/>\n                    @implements {Type}\n                  </code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * A shape.\n                     * @interface\n                     */\n                    function Shape() {};\n                    Shape.prototype.draw = function() {};\n\n                    /**\n                     * @constructor\n                     * @implements {Shape}\n                     */\n                    function Square() {};\n                    Square.prototype.draw = function() {\n                      ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used with <code>@constructor</code> to indicate that a class\n                  implements an interface. Curly braces around the type are\n                  optional.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-inheritDoc\">@inheritDoc</a></td>\n                <td>\n                  <code>@inheritDoc</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @inheritDoc */\n                    project.SubClass.prototype.toString() {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  <p style=\"font-weight:bold\">Deprecated. Use\n                    <code>@override</code> instead.</p>\n\n                  Indicates that a method or property of a subclass\n                  intentionally hides a method or property of the superclass,\n                  and has exactly the same documentation. Notice that\n                  <code>@inheritDoc</code> implies <code>@override</code>\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-interface\">@interface</a></td>\n                <td>\n                  <code>@interface</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * A shape.\n                     * @interface\n                     */\n                    function Shape() {};\n                    Shape.prototype.draw = function() {};\n\n                    /**\n                     * A polygon.\n                     * @interface\n                     * @extends {Shape}\n                     */\n                    function Polygon() {};\n                    Polygon.prototype.getSides = function() {};\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used to indicate that the function defines an interface.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-lends\">@lends</a></td>\n                <td>\n                  <code>@lends objectName</code><br/>\n                  <code>@lends {objectName}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    goog.object.extend(\n                        Button.prototype,\n                        /** @lends {Button.prototype} */ {\n                          isButton: function() { return true; }\n                        });\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Indicates that the keys of an object literal should\n                  be treated as properties of some other object. This annotation\n                  should only appear on object literals.<p/>\n\n                  Notice that the name in braces is not a type name like\n                  in other annotations. It's an object name. It names\n                  the object on which the properties are \"lent\".\n                  For example, <code>@type {Foo}</code> means \"an instance of Foo\",\n                  but <code>@lends {Foo}</code> means \"the constructor Foo\".<p/>\n\n                  The <a href=\"https://code.google.com/p/jsdoc-toolkit/wiki/TagLends\">\n                  JSDoc Toolkit docs</a> have more information on this\n                  annotation.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-license\">@license</a> or\n                  <a name=\"tag-preserve\">@preserve</a></td>\n                <td>\n                  <code>@license Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @preserve Copyright 2009 SomeThirdParty.\n                     * Here is the full license text and copyright\n                     * notice for this file. Note that the notice can span several\n                     * lines and is only terminated by the closing star and slash:\n                     */\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Anything marked by <code>@license</code> or\n                  <code>@preserve</code> will be retained by the compiler and\n                  output at the top of the compiled code for that file. This\n                  annotation allows important notices (such as legal licenses or\n                  copyright text) to survive compilation unchanged. Line breaks\n                  are preserved.\n                </td>\n              </tr>\n\n\n\n\n\n              <tr>\n                <td><a name=\"tag-noalias\">@noalias</a></td>\n                <td>\n                  <code>@noalias</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @noalias */\n                    function Range() {}\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used in an externs file to indicate to the compiler that the\n                  variable or function should not be aliased as part of the\n                  alias externals pass of the compiler.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-nocompile\">@nocompile</a></td>\n                <td>\n                  <code>@nocompile</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @nocompile */\n\n                    // JavaScript code\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used at the top of a file to tell the compiler to parse this\n                  file but not compile it.\n                  Code that is not meant for compilation and should be omitted\n                  from compilation tests (such as bootstrap code) uses this\n                  annotation.\n                  Use sparingly.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-nosideeffects\">@nosideeffects</a></td>\n                <td>\n                  <code>@nosideeffects</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @nosideeffects */\n                    function noSideEffectsFn1() {\n                      // ...\n                    }\n\n                    /** @nosideeffects */\n                    var noSideEffectsFn2 = function() {\n                      // ...\n                    };\n\n                    /** @nosideeffects */\n                    a.prototype.noSideEffectsFn3 = function() {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  This annotation can be used as part of function and\n                  constructor declarations to indicate that calls to the\n                  declared function have no side-effects.  This annotation\n                  allows the compiler to remove calls to these functions if the\n                  return value is not used.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-override\">@override</a></td>\n                <td>\n                  <code>@override</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @return {string} Human-readable representation of project.SubClass.\n                     * @override\n                     */\n                    project.SubClass.prototype.toString = function() {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Indicates that a method or property of a subclass\n                  intentionally hides a method or property of the superclass. If\n                  no other documentation is included, the method or property\n                  also inherits documentation from its superclass.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-param\">@param</a></td>\n                <td>\n                  <code>@param {Type} varname Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Queries a Baz for items.\n                     * @param {number} groupNum Subgroup id to query.\n                     * @param {string|number|null} term An itemName,\n                     *     or itemId, or null to search everything.\n                     */\n                    goog.Baz.prototype.query = function(groupNum, term) {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used with method, function and constructor calls to document\n                  the arguments of a function.<p/>\n\n                  <a href=\"#JsTypes\">Type</a>\n                  names must be enclosed in curly braces. If the type\n                  is omitted, the compiler will not type-check the parameter.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-private\">@private</a></td>\n                <td>\n                  <code>@private</code><br/>\n                  <code>@private {type}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Handlers that are listening to this logger.\n                     * @private {!Array.&lt;Function&gt;}\n                     */\n                    this.handlers_ = [];\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used in conjunction with a trailing underscore on the method\n                  or property name to indicate that the member is\n                  <a href=\"#Visibility__private_and_protected_fields_\">private</a> and final.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-protected\">@protected</a></td>\n                <td>\n                  <code>@protected</code><br/>\n                  <code>@protected {type}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Sets the component's root element to the given element.\n                     * @param {Element} element Root element for the component.\n                     * @protected\n                     */\n                    goog.ui.Component.prototype.setElementInternal = function(element) {\n                      // ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used to indicate that the member or property is\n                  <a href=\"#Visibility__private_and_protected_fields_\">protected</a>.\n                  Should be used in conjunction with names with no trailing\n                  underscore.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-public\">@public</a></td>\n                <td>\n                  <code>@public</code><br/>\n                  <code>@public {type}</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Whether to cancel the event in internal capture/bubble processing.\n                     * @public {boolean}\n                     * @suppress {visibility} Referencing this outside this package is strongly\n                     * discouraged.\n                     */\n                     goog.events.Event.prototype.propagationStopped_ = false;\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used to indicate that the member or property is public. Variables and\n                  properties are public by default, so this annotation is rarely necessary.\n                  Should only be used in legacy code that cannot be easily changed to\n                  override the visibility of members that were named as private variables.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-return\">@return</a></td>\n                <td>\n                  <code>@return {Type} Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @return {string} The hex ID of the last item.\n                     */\n                    goog.Baz.prototype.getLastId = function() {\n                      // ...\n                      return id;\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used with method and function calls to document the return\n                  type.  When writing descriptions for boolean parameters,\n                  prefer \"Whether the component is visible\" to \"True if the\n                  component is visible, false otherwise\". If there is no return\n                  value, do not use an <code>@return</code> tag.<p/>\n\n                  <a href=\"#JsTypes\">Type</a>\n                  names must be enclosed in curly braces. If the type\n                  is omitted, the compiler will not type-check the return value.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-see\">@see</a></td>\n                <td>\n                  <code>@see Link</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * Adds a single item, recklessly.\n                     * @see #addSafely\n                     * @see goog.Collect\n                     * @see goog.RecklessAdder#add\n                     ...\n                  </CODE_SNIPPET>\n                </td>\n                <td>Reference a lookup to another class function or method.</td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-struct\">@struct</a></td>\n                <td>\n                  <code>@struct Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @constructor\n                     * @struct\n                     */\n                    function Foo(x) {\n                      this.x = x;\n                    }\n                    var obj = new Foo(123);\n                    var num = obj['x'];  // warning\n                    obj.y = \"asdf\";  // warning\n\n                    Foo.prototype = /** @struct */ {\n                      method1: function() {}\n                    };\n                    Foo.prototype.method2 = function() {};  // warning\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  When a constructor (<code>Foo</code> in the example) is\n                  annotated with <code>@struct</code>, you can only use the dot\n                  notation to access the properties of <code>Foo</code> objects.\n                  Also, you cannot add new properties to <code>Foo</code>\n                  objects after they have been created.\n                  The annotation can also be used directly on object literals.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-supported\">@supported</a></td>\n                <td>\n                  <code>@supported Description</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @fileoverview Event Manager\n                     * Provides an abstracted interface to the\n                     * browsers' event systems.\n                     * @supported So far tested in IE6 and FF1.5\n                     */\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Used in a fileoverview to indicate what browsers are supported\n                  by the file.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-suppress\">@suppress</a></td>\n                <td>\n                  <code>\n                    @suppress {warning1|warning2}\n                  </code>\n                  <code>\n                    @suppress {warning1,warning2}\n                  </code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @suppress {deprecated}\n                     */\n                    function f() {\n                      deprecatedVersionOfF();\n                    }\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Suppresses warnings from tools. Warning categories are\n                  separated by <code>|</code> or <code>,</code>.\n\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-template\">@template</a></td>\n                <td>\n                  <code>@template</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * @param {function(this:T, ...)} fn\n                     * @param {T} thisObj\n                     * @param {...*} var_args\n                     * @template T\n                     */\n                    goog.bind = function(fn, thisObj, var_args) {\n                       ...\n                    };\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  This annotation can be used to declare a\n                  <a href=\"#Template_types\">template typename</a>.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-this\">@this</a></td>\n                <td>\n                  <code>\n                    @this Type<br/>\n                    @this {Type}\n                  </code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    pinto.chat.RosterWidget.extern('getRosterElement',\n                    /**\n                     * Returns the roster widget element.\n                     * @this pinto.chat.RosterWidget\n                     * @return {Element}\n                     */\n                    function() {\n                      return this.getWrappedComponent_().getElement();\n                    });\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  The type of the object in whose context a particular method is\n                  called. Required when the <code>this</code> keyword is referenced\n                  from a function that is not a prototype method.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-type\">@type</a></td>\n                <td>\n                  <code>\n                    @type Type<br/>\n                    @type {Type}\n                  </code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /**\n                     * The message hex ID.\n                     * @type {string}\n                     */\n                    var hexId = hexId;\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  Identifies the <a href=\"#JsTypes\">type</a> of a variable,\n                  property, or expression. Curly braces are not required around\n                  most types, but some projects mandate them for all types, for\n                  consistency.\n                </td>\n              </tr>\n\n              <tr>\n                <td><a name=\"tag-typedef\">@typedef</a></td>\n                <td>\n                  <code>@typedef</code>\n                  <p><i>For example:</i></p>\n                  <CODE_SNIPPET>\n                    /** @typedef {(string|number)} */\n                    goog.NumberLike;\n\n                    /** @param {goog.NumberLike} x A number or a string. */\n                    goog.readNumber = function(x) {\n                      ...\n                    }\n                  </CODE_SNIPPET>\n                </td>\n                <td>\n                  This annotation can be used to declare an alias of a more\n                  <a href=\"#Typedefs\">complex type</a>.\n                </td>\n              </tr>\n\n\n\n            </tbody>\n          </table>\n\n\n\n          <p>\n            You may also see other types of JSDoc annotations in third-party\n            code. These annotations appear in the\n            <a href=\"https://code.google.com/p/jsdoc-toolkit/wiki/TagReference\">\n              JSDoc Toolkit Tag Reference\n            </a>\n            but are currently discouraged in Google code. You should consider\n            them \"reserved\" names for future use. These include:\n            <ul>\n              <li>@augments</li>\n              <li>@argument</li>\n              <li>@borrows</li>\n              <li>@class</li>\n              <li>@constant</li>\n              <li>@constructs</li>\n              <li>@default</li>\n              <li>@event</li>\n              <li>@example</li>\n              <li>@field</li>\n              <li>@function</li>\n              <li>@ignore</li>\n              <li>@inner</li>\n              <li>@link</li>\n              <li>@memberOf</li>\n              <li>@name</li>\n              <li>@namespace</li>\n              <li>@property</li>\n              <li>@public</li>\n              <li>@requires</li>\n              <li>@returns</li>\n              <li>@since</li>\n              <li>@static</li>\n              <li>@version</li>\n            </ul>\n          </p>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Providing Dependencies With goog.provide\">\n      <SUMMARY>\n        Only provide top-level symbols.\n      </SUMMARY>\n      <BODY>\n        <p>\n          All members defined on a class should be in the same file. So, only\n          top-level classes should be provided in a file that contains multiple\n          members defined on the same class (e.g. enums, inner classes, etc).\n        </p>\n        <p>Do this:</p>\n        <CODE_SNIPPET>\n          goog.provide('namespace.MyClass');\n        </CODE_SNIPPET>\n        <p>Not this:</p>\n        <BAD_CODE_SNIPPET>\n          goog.provide('namespace.MyClass');\n          goog.provide('namespace.MyClass.Enum');\n          goog.provide('namespace.MyClass.InnerClass');\n          goog.provide('namespace.MyClass.TypeDef');\n          goog.provide('namespace.MyClass.CONSTANT');\n          goog.provide('namespace.MyClass.staticMethod');\n        </BAD_CODE_SNIPPET>\n        <p>\n          Members on namespaces may also be provided:\n        </p>\n        <CODE_SNIPPET>\n          goog.provide('foo.bar');\n          goog.provide('foo.bar.method');\n          goog.provide('foo.bar.CONSTANT');\n        </CODE_SNIPPET>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Compiling\">\n      <SUMMARY>Required</SUMMARY>\n      <BODY>\n\n\n        <p>Use of JS compilers such as the\n          <a href=\"https://code.google.com/closure/compiler/\">Closure Compiler</a>\n          is required for all customer-facing code.</p>\n\n\n\n\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Tips and Tricks\">\n      <SUMMARY>JavaScript tidbits</SUMMARY>\n      <BODY>\n        <SUBSECTION title=\"True and False Boolean Expressions\">\n          <p>The following are all false in boolean expressions:</p>\n          <ul>\n            <li><code>null</code></li>\n            <li><code>undefined</code></li>\n            <li><code>''</code> the empty string</li>\n            <li><code>0</code> the number</li>\n          </ul>\n          <p>But be careful, because these are all true:</p>\n          <ul>\n            <li><code>'0'</code> the string</li>\n            <li><code>[]</code> the empty array</li>\n            <li><code>{}</code> the empty object</li>\n          </ul>\n\n          <p>This means that instead of this:</p>\n          <BAD_CODE_SNIPPET>\n            while (x != null) {\n          </BAD_CODE_SNIPPET>\n          <p>you can write this shorter code (as long as you don't expect x to\n            be 0, or the empty string, or false):</p>\n          <CODE_SNIPPET>\n            while (x) {\n          </CODE_SNIPPET>\n\n          <p>And if you want to check a string to see if it is null or empty,\n            you could do this:</p>\n          <BAD_CODE_SNIPPET>\n            if (y != null &amp;&amp; y != '') {\n          </BAD_CODE_SNIPPET>\n          <p>But this is shorter and nicer:</p>\n          <CODE_SNIPPET>\n            if (y) {\n          </CODE_SNIPPET>\n\n          <p><strong>Caution:</strong> There are many unintuitive things about\n            boolean expressions.  Here are some of them:</p>\n          <ul>\n            <li><code>\n              Boolean('0') == true<br/>\n              '0' != true</code></li>\n            <li><code>\n              0 != null<br/>\n              0 == []<br/>\n              0 == false</code></li>\n            <li><code>\n              Boolean(null) == false<br/>\n              null != true<br/>\n              null != false</code></li>\n            <li><code>\n              Boolean(undefined) == false<br/>\n              undefined != true<br/>\n              undefined != false</code></li>\n            <li><code>\n              Boolean([]) == true<br/>\n              [] != true<br/>\n              [] == false</code></li>\n            <li><code>\n              Boolean({}) == true<br/>\n              {} != true<br/>\n              {} != false</code></li>\n          </ul>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Conditional (Ternary) Operator (?:)\">\n          <p>Instead of this:</p>\n          <CODE_SNIPPET>\n            if (val) {\n              return foo();\n            } else {\n              return bar();\n            }\n          </CODE_SNIPPET>\n          <p>you can write this:</p>\n          <CODE_SNIPPET>\n            return val ? foo() : bar();\n          </CODE_SNIPPET>\n\n          <p>The ternary conditional is also useful when generating HTML:</p>\n          <CODE_SNIPPET>\n            var html = '&lt;input type=\"checkbox\"' +\n                (isChecked ? ' checked' : '') +\n                (isEnabled ? '' : ' disabled') +\n                ' name=\"foo\"&gt;';\n          </CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"&amp;&amp; and ||\">\n          <p>These binary boolean operators are short-circuited, and evaluate\n            to the last evaluated term.</p>\n\n          <p>\"||\" has been called the 'default' operator, because instead of\n            writing this:</p>\n          <BAD_CODE_SNIPPET>\n            /** @param {*=} opt_win */\n            function foo(opt_win) {\n              var win;\n              if (opt_win) {\n                win = opt_win;\n              } else {\n                win = window;\n              }\n              // ...\n            }\n          </BAD_CODE_SNIPPET>\n          <p>you can write this:</p>\n          <CODE_SNIPPET>\n            /** @param {*=} opt_win */\n            function foo(opt_win) {\n              var win = opt_win || window;\n              // ...\n            }\n          </CODE_SNIPPET>\n\n          <p>\"&amp;&amp;\" is also useful for shortening code. For instance,\n            instead of this:</p>\n          <BAD_CODE_SNIPPET>\n            if (node) {\n              if (node.kids) {\n                if (node.kids[index]) {\n                  foo(node.kids[index]);\n                }\n              }\n            }\n          </BAD_CODE_SNIPPET>\n\n          <p>you could do this:</p>\n          <CODE_SNIPPET>\n            if (node &amp;&amp; node.kids &amp;&amp; node.kids[index]) {\n              foo(node.kids[index]);\n            }\n          </CODE_SNIPPET>\n\n          <p>or this:</p>\n          <CODE_SNIPPET>\n            var kid = node &amp;&amp; node.kids &amp;&amp; node.kids[index];\n            if (kid) {\n              foo(kid);\n            }\n          </CODE_SNIPPET>\n\n          <p>However, this is going a little too far:</p>\n          <BAD_CODE_SNIPPET>\n            node &amp;&amp; node.kids &amp;&amp; node.kids[index] &amp;&amp; foo(node.kids[index]);\n          </BAD_CODE_SNIPPET>\n        </SUBSECTION>\n\n        <SUBSECTION title=\"Iterating over Node Lists\">\n          <p>Node lists are often implemented as node iterators with a filter.\n            This means that getting a property like length is O(n), and\n            iterating over the list by re-checking the length will be\n            O(n^2).</p>\n          <BAD_CODE_SNIPPET>\n            var paragraphs = document.getElementsByTagName('p');\n            for (var i = 0; i &lt; paragraphs.length; i++) {\n              doSomething(paragraphs[i]);\n            }\n          </BAD_CODE_SNIPPET>\n\n          <p>It is better to do this instead:</p>\n          <CODE_SNIPPET>\n            var paragraphs = document.getElementsByTagName('p');\n            for (var i = 0, paragraph; paragraph = paragraphs[i]; i++) {\n              doSomething(paragraph);\n            }\n          </CODE_SNIPPET>\n\n          <p>This works well for all collections and arrays as long as the array\n            does not contain things that are treated as boolean false.</p>\n\n          <p>In cases where you are iterating over the childNodes you can also\n            use the firstChild and nextSibling properties.</p>\n          <CODE_SNIPPET>\n            var parentNode = document.getElementById('foo');\n            for (var child = parentNode.firstChild; child; child = child.nextSibling) {\n              doSomething(child);\n            }\n          </CODE_SNIPPET>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n\n\n\n  <PARTING_WORDS>\n    <p>\n      <em>BE CONSISTENT</em>.\n    </p>\n\n    <p>\n      If you're editing code, take a few minutes to look at the code\n      around you and determine its style.  If they use spaces around\n      all their arithmetic operators, you should too.  If their\n      comments have little boxes of hash marks around them, make your\n      comments have little boxes of hash marks around them too.\n    </p>\n\n    <p>\n      The point of having style guidelines is to have a common vocabulary\n      of coding so people can concentrate on what you're saying rather\n      than on how you're saying it.  We present global style rules here so\n      people know the vocabulary, but local style is also important.  If\n      code you add to a file looks drastically different from the existing\n      code around it, it throws readers out of their rhythm when they go to\n      read it.  Avoid this.\n    </p>\n\n  </PARTING_WORDS>\n\n  <p align=\"right\">\n    Revision 2.93\n  </p>\n\n\n  <address>\n    Aaron Whyte<br/>\n    Bob Jervis<br/>\n    Dan Pupius<br/>\n    Erik Arvidsson<br/>\n    Fritz Schneider<br/>\n    Robby Walker<br/>\n  </address>\n</GUIDE>\n"
  },
  {
    "path": "jsguide.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Google JavaScript Style Guide</title>\n<link rel=\"stylesheet\" href=\"javaguide.css\">\n<script src=\"include/styleguide.js\"></script>\n<link rel=\"shortcut icon\" href=\"/styleguide/favicon.ico\">\n<script src=\"include/jsguide.js\"></script>\n</head>\n<body onload=\"initStyleGuide();\">\n<div id=\"content\">\n<h1>Google JavaScript Style Guide</h1>\n\n<p style=\"position: fixed; left: 0; top: 0; padding: 0.5em; margin: 0; background-color: #fef6e0; text-align: center; width: 100%; font-weight: bold; z-index: 1;\">\nPlease note: This guide is no longer being updated. Google recommends migrating\nto TypeScript, and following the <a href=\"tsguide.html\">TypeScript guide</a>.\n</p>\n\n<h2 id=\"introduction\">1 Introduction</h2>\n\n<p>This document serves as the <strong>complete</strong> definition of Google’s coding standards\nfor source code in the JavaScript programming language. A JavaScript source file\nis described as being <em>in Google Style</em> if and only if it adheres to the rules\nherein.</p>\n\n<p>Like other programming style guides, the issues covered span not only aesthetic\nissues of formatting, but other types of conventions or coding standards as\nwell. However, this document focuses primarily on the hard-and-fast rules that\nwe follow universally, and avoids giving advice that isn't clearly enforceable\n(whether by human or tool).</p>\n\n<h3 id=\"terminology-notes\">1.1 Terminology notes</h3>\n\n<p>In this document, unless otherwise clarified:</p>\n\n<ol>\n<li><p>The term <em>comment</em> always refers to <em>implementation</em> comments. We do not use\nthe phrase <q>documentation comments</q>, instead using the common term “JSDoc”\nfor both human-readable text and machine-readable annotations within <code>/** …\n*/</code>.</p></li>\n<li><p>This Style Guide uses <a href=\"http://tools.ietf.org/html/rfc2119\">RFC 2119</a> terminology when using the phrases <em>must</em>,\n<em>must not</em>, <em>should</em>, <em>should not</em>, and <em>may</em>. The terms <em>prefer</em> and\n<em>avoid</em> correspond to <em>should</em> and <em>should not</em>, respectively. Imperative\nand declarative statements are prescriptive and correspond to <em>must</em>.</p></li>\n</ol>\n\n<p>Other <q>terminology notes</q> will appear occasionally throughout the document.</p>\n\n<h3 id=\"guide-notes\">1.2 Guide notes</h3>\n\n<p>Example code in this document is <strong>non-normative</strong>. That is, while the examples\nare in Google Style, they may not illustrate the <em>only</em> stylish way to represent\nthe code. Optional formatting choices made in examples must not be enforced as\nrules.</p>\n\n<h2 id=\"source-file-basics\">2 Source file basics</h2>\n\n<h3 id=\"file-name\">2.1 File name</h3>\n\n<p>File names must be all lowercase and may include underscores (<code>_</code>) or dashes\n(<code>-</code>), but no additional punctuation. Follow the convention that your project\nuses. Filenames’ extension must be <code>.js</code>.</p>\n\n<h3 id=\"file-encoding\">2.2 File encoding: UTF-8</h3>\n\n<p>Source files are encoded in <strong>UTF-8</strong>.</p>\n\n<h3 id=\"special-characters\">2.3 Special characters</h3>\n\n<h4 id=\"whitespace-characters\">2.3.1 Whitespace characters</h4>\n\n<p>Aside from the line terminator sequence, the ASCII horizontal space character\n(0x20) is the only whitespace character that appears anywhere in a source file.\nThis implies that</p>\n\n<ol>\n<li><p>All other whitespace characters in string literals are escaped, and</p></li>\n<li><p>Tab characters are <strong>not</strong> used for indentation.</p></li>\n</ol>\n\n<h4 id=\"special-escape-sequences\">2.3.2 Special escape sequences</h4>\n\n<p>For any character that has a special escape sequence (<code>\\'</code>, <code>\\\"</code>, <code>\\\\</code>, <code>\\b</code>,\n<code>\\f</code>, <code>\\n</code>, <code>\\r</code>, <code>\\t</code>, <code>\\v</code>), that sequence is used rather than the\ncorresponding numeric escape (e.g <code>\\x0a</code>, <code>\\u000a</code>, or <code>\\u{a}</code>). Legacy octal\nescapes are never used.</p>\n\n<h4 id=\"non-ascii-characters\">2.3.3 Non-ASCII characters</h4>\n\n<p>For the remaining non-ASCII characters, either the actual Unicode character\n(e.g. <code>∞</code>) or the equivalent hex or Unicode escape (e.g. <code>\\u221e</code>) is used,\ndepending only on which makes the code <strong>easier to read and understand</strong>.</p>\n\n<p>Tip: In the Unicode escape case, and occasionally even when actual Unicode\ncharacters are used, an explanatory comment can be very helpful.</p>\n\n<pre><code class=\"language-js prettyprint good\">/* Best: perfectly clear even without a comment. */\nconst units = 'μs';\n\n/* Allowed: but unnecessary as μ is a printable character. */\nconst units = '\\u03bcs'; // 'μs'\n\n/* Good: use escapes for non-printable characters with a comment for clarity. */\nreturn '\\ufeff' + content;  // Prepend a byte order mark.\n</code></pre>\n\n<pre><code class=\"language-js prettyprint bad\">/* Poor: the reader has no idea what character this is. */\nconst units = '\\u03bcs';\n</code></pre>\n\n<p>Tip: Never make your code less readable simply out of fear that some programs\nmight not handle non-ASCII characters properly. If that happens, those programs\nare <strong>broken</strong> and they must be <strong>fixed</strong>.</p>\n\n<h2 id=\"source-file-structure\">3 Source file structure</h2>\n\n<p>All new source files should either be a <code>goog.module</code>\nfile (a file containing a <code>goog.module</code> call) or an ECMAScript (ES) module (uses\n<code>import</code> and <code>export</code> statements).</p>\n\n<p>Files consist of the following, <strong>in order</strong>:</p>\n\n<ol>\n<li>License or copyright information, if present</li>\n<li><code>@fileoverview</code> JSDoc, if present</li>\n<li><code>goog.module</code> statement, if a <code>goog.module</code> file</li>\n<li>ES <code>import</code> statements, if an ES module</li>\n<li><code>goog.require</code> and <code>goog.requireType</code> statements</li>\n<li>The file’s implementation</li>\n</ol>\n\n<p><strong>Exactly one blank line</strong> separates each section that is present, except the\nfile's implementation, which may be preceded by 1 or 2 blank lines.</p>\n\n<h3 id=\"file-copyright\">3.1 License or copyright information, if present</h3>\n\n<p>If license or copyright information belongs in a file, it belongs here.</p>\n\n<h3 id=\"file-fileoverview\">3.2 <code>@fileoverview</code> JSDoc, if present</h3>\n\n<p>See <a href=\"#jsdoc-top-file-level-comments\">??</a> for formatting rules.</p>\n\n<h3 id=\"file-goog-module\">3.3 <code>goog.module</code> statement</h3>\n\n<p>All <code>goog.module</code> files must declare exactly one <code>goog.module</code> name on a single\nline: lines containing a <code>goog.module</code> declaration must not be wrapped, and are\ntherefore an exception to the 80-column limit.</p>\n\n<p>The entire argument to <code>goog.module</code> is what defines a namespace. It is the\npackage name (an identifier that reflects the fragment of the directory\nstructure where the code lives) plus, optionally, the main class/enum/interface\nthat it defines concatenated to the end in <code>lowerCamelCase</code>.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">goog.module('search.urlHistory.urlHistoryService');\n</code></pre>\n\n<h4 id=\"naming-hierarchy\">3.3.1 Hierarchy</h4>\n\n<p>Module namespaces may never be named as a <em>direct</em> child of another module's\nnamespace.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">goog.module('foo.bar');   // 'foo.bar.qux' would be fine, though\ngoog.module('foo.bar.baz');\n</code></pre>\n\n<p>The directory hierarchy reflects the namespace hierarchy, so that deeper-nested\nchildren are subdirectories of higher-level parent directories. Note that this\nimplies that owners of “parent” namespace groups are necessarily aware of all\nchild namespaces, since they exist in the same directory.</p>\n\n<h4 id=\"file-declare-legacy-namespace\">3.3.2 <code>goog.module.declareLegacyNamespace</code></h4>\n\n<p>The single <code>goog.module</code> statement may optionally be followed by a call to\n<code>goog.module.declareLegacyNamespace();</code>. Avoid\n<code>goog.module.declareLegacyNamespace()</code> when possible.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">goog.module('my.test.helpers');\ngoog.module.declareLegacyNamespace();\ngoog.setTestOnly();\n</code></pre>\n\n<p><code>goog.module.declareLegacyNamespace</code> exists to ease the transition from\ntraditional object hierarchy-based namespaces but comes with some naming\nrestrictions. As the child module name must be created after the parent\nnamespace, this name <strong>must not</strong> be a child or parent of any other\n<code>goog.module</code> (for example, <code>goog.module('parent');</code> and\n<code>goog.module('parent.child');</code> cannot both exist safely, nor can\n<code>goog.module('parent');</code> and <code>goog.module('parent.child.grandchild');</code>).</p>\n\n<h4 id=\"file-goog-module-exports\">3.3.3 <code>goog.module</code> Exports</h4>\n\n<p>Classes, enums, functions, constants, and other symbols are exported using the\n<code>exports</code> object. Exported symbols may be defined directly on the <code>exports</code>\nobject, or else declared locally and exported separately. Symbols are only\nexported if they are meant to be used outside the module. Non-exported\nmodule-local symbols are not declared <code>@private</code>. There is no prescribed\nordering for exported and module-local symbols.</p>\n\n<p>Examples:</p>\n\n<pre><code class=\"language-js prettyprint good\">const /** !Array&lt;number&gt; */ exportedArray = [1, 2, 3];\n\nconst /** !Array&lt;number&gt; */ moduleLocalArray = [4, 5, 6];\n\n/** @return {number} */\nfunction moduleLocalFunction() {\n  return moduleLocalArray.length;\n}\n\n/** @return {number} */\nfunction exportedFunction() {\n  return moduleLocalFunction() * 2;\n}\n\nexports = {exportedArray, exportedFunction};\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">/** @const {number} */\nexports.CONSTANT_ONE = 1;\n\n/** @const {string} */\nexports.CONSTANT_TWO = 'Another constant';\n</code></pre>\n\n<p>Do not annotate the <code>exports</code> object as <code>@const</code> as it is already treated as a\nconstant by the compiler.</p>\n\n<pre><code class=\"language-js prettyprint bad\">/** @const */\nexports = {exportedFunction};\n</code></pre>\n\n<p>Do not use default exports as they don't translate easily to ES module\nsemantics.</p>\n\n<pre><code class=\"language-js prettyprint bad\">exports = FancyClass;\n</code></pre>\n\n<p><span id=\"file-es6-modules\"></span></p>\n\n<h3 id=\"file-es-modules\">3.4 ES modules</h3>\n\n<p>ES modules are files that use the <code>import</code> and <code>export</code> keywords.</p>\n\n<p><span id=\"es6-module-imports\"></span></p>\n\n<h4 id=\"es-module-imports\">3.4.1 Imports</h4>\n\n<p>Import statements must not be line wrapped and are therefore an exception to the\n80-column limit.</p>\n\n<p><span id=\"es6-import-paths\"></span></p>\n\n<h5 id=\"esm-import-paths\">3.4.1.1 Import paths</h5>\n\n<p>ES module files must use the <code>import</code> statement to import other ES module\nfiles. Do not <code>goog.require</code> another ES module.</p>\n\n<pre><code class=\"language-js prettyprint good\">import './sideeffects.js';\n\nimport * as goog from '../closure/goog/goog.js';\nimport * as parent from '../parent.js';\n\nimport {name} from './sibling.js';\n</code></pre>\n\n<p><span id=\"es6-import-paths-file-extension\"></span></p>\n\n<h6 id=\"esm-import-paths-file-extension\">3.4.1.1.1 File extensions in import paths</h6>\n\n<p>The <code>.js</code> file extension is not optional in import paths and must always be\nincluded.</p>\n\n<pre><code class=\"language-js prettyprint bad\">import '../directory/file';\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">import '../directory/file.js';\n</code></pre>\n\n<h5 id=\"importing-the-same-file-multiple-times\">3.4.1.2 Importing the same file multiple times</h5>\n\n<p>Do not import the same file multiple times. This can make it hard to determine\nthe aggregate imports of a file.</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Imports have the same path, but since it doesn't align it can be hard to see.\nimport {short} from './long/path/to/a/file.js';\nimport {aLongNameThatBreaksAlignment} from './long/path/to/a/file.js';\n</code></pre>\n\n<p><span id=\"naming-es6-imports\"></span></p>\n\n<h5 id=\"naming-esm-imports\">3.4.1.3 Naming imports</h5>\n\n<h6 id=\"naming-module-imports\">3.4.1.3.1 Naming module imports</h6>\n\n<p>Module import names (<code>import * as name</code>) are <code>lowerCamelCase</code> names that are\nderived from the imported file name.</p>\n\n<pre><code class=\"language-js prettyprint good\">import * as fileOne from '../file-one.js';\nimport * as fileTwo from '../file_two.js';\nimport * as fileThree from '../filethree.js';\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">import * as libString from './lib/string.js';\nimport * as math from './math/math.js';\nimport * as vectorMath from './vector/math.js';\n</code></pre>\n\n<p>Some libraries might commonly use a namespace import prefix that violates this\nnaming scheme, but overbearingly common open source use makes the violating\nstyle more readable. The only library that currently falls under this exception\nis <a href=\"https://threejs.org/\">threejs</a>, using the <code>THREE</code> prefix.</p>\n\n<h6 id=\"naming-default-imports\">3.4.1.3.2 Naming default imports</h6>\n\n<p>Default import names are derived from the imported file name and follow the\nrules in <a href=\"#naming-rules-by-identifier-type\">??</a>.</p>\n\n<pre><code class=\"language-js prettyprint good\">import MyClass from '../my-class.js';\nimport myFunction from '../my_function.js';\nimport SOME_CONSTANT from '../someconstant.js';\n</code></pre>\n\n<p>Note: In general this should not happen as default exports are banned by this\nstyle guide, see <a href=\"#named-vs-default-exports\">??</a>. Default imports are only used\nto import modules that do not conform to this style guide.</p>\n\n<h6 id=\"naming-named-imports\">3.4.1.3.3 Naming named imports</h6>\n\n<p>In general symbols imported via the named import (<code>import {name}</code>) should keep\nthe same name. Avoid aliasing imports (<code>import {SomeThing as SomeOtherThing}</code>).\nPrefer fixing name collisions by using a module import (<code>import *</code>) or renaming\nthe exports themselves.</p>\n\n<pre><code class=\"language-js prettyprint good\">import * as bigAnimals from './biganimals.js';\nimport * as domesticatedAnimals from './domesticatedanimals.js';\n\nnew bigAnimals.Cat();\nnew domesticatedAnimals.Cat();\n</code></pre>\n\n<p>If renaming a named import is needed then use components of the imported\nmodule's file name or path in the resulting alias.</p>\n\n<pre><code class=\"language-js prettyprint good\">import {Cat as BigCat} from './biganimals.js';\nimport {Cat as DomesticatedCat} from './domesticatedanimals.js';\n\nnew BigCat();\nnew DomesticatedCat();\n</code></pre>\n\n<p><span id=\"es6-module-exports\"></span></p>\n\n<h4 id=\"es-module-exports\">3.4.2 Exports</h4>\n\n<p>Symbols are only exported if they are meant to be used outside the module.\nNon-exported module-local symbols are not declared <code>@private</code>. There is no\nprescribed ordering for exported and module-local symbols.</p>\n\n<h5 id=\"named-vs-default-exports\">3.4.2.1 Named vs default exports</h5>\n\n<p>Use named exports in all code. You can apply the <code>export</code> keyword to a\ndeclaration, or use the <code>export {name};</code> syntax.</p>\n\n<p>Do not use default exports. Importing modules must give a name to these values,\nwhich can lead to inconsistencies in naming across modules.</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Do not use default exports:\nexport default class Foo { ... } // BAD!\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">// Use named exports:\nexport class Foo { ... }\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">// Alternate style named exports:\nclass Foo { ... }\n\nexport {Foo};\n</code></pre>\n\n<p><span id=\"es6-exports-mutability\"></span></p>\n\n<h5 id=\"esm-exports-mutability\">3.4.2.2 Mutability of exports</h5>\n\n<p>Exported variables must not be mutated outside of module initialization.</p>\n\n<p>There are alternatives if mutation is needed, including exporting a constant\nreference to an object that has mutable fields or exporting accessor functions for\nmutable data.</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Bad: both foo and mutateFoo are exported and mutated.\nexport let /** number */ foo = 0;\n\n/**\n * Mutates foo.\n */\nexport function mutateFoo() {\n  ++foo;\n}\n\n/**\n * @param {function(number): number} newMutateFoo\n */\nexport function setMutateFoo(newMutateFoo) {\n  // Exported classes and functions can be mutated!\n  mutateFoo = () =&gt; {\n    foo = newMutateFoo(foo);\n  };\n}\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">// Good: Rather than export the mutable variables foo and mutateFoo directly,\n// instead make them module scoped and export a getter for foo and a wrapper for\n// mutateFooFunc.\nlet /** number */ foo = 0;\nlet /** function(number): number */ mutateFooFunc = (foo) =&gt; foo + 1;\n\n/** @return {number} */\nexport function getFoo() {\n  return foo;\n}\n\nexport function mutateFoo() {\n  foo = mutateFooFunc(foo);\n}\n\n/** @param {function(number): number} mutateFoo */\nexport function setMutateFoo(mutateFoo) {\n  mutateFooFunc = mutateFoo;\n}\n</code></pre>\n\n<p><span id=\"es6-module-circular-dependencies\"></span></p>\n\n<h5 id=\"es-module-export-from\">3.4.2.3 export from</h5>\n\n<p><code>export from</code> statements must not be line wrapped and are therefore an\nexception to the 80-column limit. This applies to both <code>export from</code> flavors.</p>\n\n<pre><code class=\"language-js prettyprint good\">export {specificName} from './other.js';\nexport * from './another.js';\n</code></pre>\n\n<h4 id=\"es-module-circular-dependencies\">3.4.3 Circular Dependencies in ES modules</h4>\n\n<p>Do not create cycles between ES modules, even though the ECMAScript\nspecification allows this. Note that it is possible to create cycles with both\nthe <code>import</code> and <code>export</code> statements.</p>\n\n<pre><code class=\"language-js prettyprint bad\">// a.js\nimport './b.js';\n</code></pre>\n\n<pre><code class=\"language-js prettyprint bad\">// b.js\nimport './a.js';\n\n// `export from` can cause circular dependencies too!\nexport {x} from './c.js';\n</code></pre>\n\n<pre><code class=\"language-js prettyprint bad\">// c.js\nimport './b.js';\n\nexport let x;\n</code></pre>\n\n<p><span id=\"es6-module-closure-interop\"></span></p>\n\n<h4 id=\"es-module-closure-interop\">3.4.4 Interoperating with Closure</h4>\n\n<p><span id=\"es6-module-referencing-goog\"></span></p>\n\n<h5 id=\"es-module-referencing-goog\">3.4.4.1 Referencing goog</h5>\n\n<p>To reference the Closure <code>goog</code> namespace, import Closure's <code>goog.js</code>.</p>\n\n<pre><code class=\"language-js prettyprint good\">import * as goog from '../closure/goog/goog.js';\n\nconst {compute} = goog.require('a.name');\n\nexport const CONSTANT = compute();\n</code></pre>\n\n<p><code>goog.js</code> exports only a subset of properties from the global <code>goog</code> that can be\nused in ES modules.</p>\n\n<p><span id=\"goog-require-in-es6-module\"></span></p>\n\n<h5 id=\"goog-require-in-es-module\">3.4.4.2 goog.require in ES modules</h5>\n\n<p><code>goog.require</code> in ES modules works as it does in <code>goog.module</code> files. You can\nrequire any Closure namespace symbol (i.e., symbols created by <code>goog.provide</code> or\n<code>goog.module</code>) and <code>goog.require</code> will return the value.</p>\n\n<pre><code class=\"language-js prettyprint good\">import * as goog from '../closure/goog/goog.js';\nimport * as anEsModule from './anEsModule.js';\n\nconst GoogPromise = goog.require('goog.Promise');\nconst myNamespace = goog.require('my.namespace');\n</code></pre>\n\n<p><span id=\"closure-module-id-in-es6-module\"></span></p>\n\n<h5 id=\"closure-module-id-in-es-module\">3.4.4.3 Declaring Closure Module IDs in ES modules</h5>\n\n<p><code>goog.declareModuleId</code> can be used within ES modules to declare a\n<code>goog.module</code>-like module ID. This means that this module ID can be\n<code>goog.require</code>d, <code>goog.module.get</code>d etc. as if it were\na <code>goog.module</code> that did not call <code>goog.module.declareLegacyNamespace</code>. It does\nnot create the module ID as a globally available JavaScript symbol.</p>\n\n<p>A <code>goog.require</code> (or <code>goog.module.get</code>) for a module ID from\n<code>goog.declareModuleId</code> will always return the module object (as if it was\n<code>import *</code>'d). As a result, the argument to <code>goog.declareModuleId</code> should always\nend with a <code>lowerCamelCaseName</code>.</p>\n\n<p>Note: It is an error to call <code>goog.module.declareLegacyNamespace</code> in an ES\nmodule, it can only be called from <code>goog.module</code> files. There is no direct way\nto associate a <q>legacy</q> namespace with an ES module.</p>\n\n<p><code>goog.declareModuleId</code> should only be used to upgrade Closure files to ES\nmodules in place, where named exports are used.</p>\n\n<pre><code class=\"language-js prettyprint good\">import * as goog from '../closure/goog.js';\n\ngoog.declareModuleId('my.esm');\n\nexport class Class {};\n</code></pre>\n\n<h3 id=\"file-set-test-only\">3.5 <code>goog.setTestOnly</code></h3>\n\n<p>In a <code>goog.module</code> file the <code>goog.module</code> statement and, if present,\n<code>goog.module.declareLegacyNamespace()</code> statement may optionally be followed by a\ncall to <code>goog.setTestOnly()</code>.</p>\n\n<p>In an ES module the <code>import</code> statements may optionally be\nfollowed by a call to <code>goog.setTestOnly()</code>.</p>\n\n<h3 id=\"file-goog-require\">3.6 <code>goog.require</code> and <code>goog.requireType</code> statements</h3>\n\n<p>Imports are done with <code>goog.require</code> and <code>goog.requireType</code> statements. The\nnames imported by a <code>goog.require</code> statement may be used both in code and in\ntype annotations, while those imported by a <code>goog.requireType</code> may be used in\ntype annotations only.</p>\n\n<p>The <code>goog.require</code> and <code>goog.requireType</code> statements form a contiguous block\nwith no empty lines. This block follows the <code>goog.module</code> declaration separated\n<a href=\"#source-file-structure\">by a single empty line</a>. The entire argument to\n<code>goog.require</code> or <code>goog.requireType</code> is a namespace defined by a <code>goog.module</code>\nin a separate file. <code>goog.require</code> and <code>goog.requireType</code> statements may not\nappear anywhere else in the file.</p>\n\n<p>Each <code>goog.require</code> or <code>goog.requireType</code> is assigned to a single constant\nalias, or else destructured into several constant aliases. These aliases are the\nonly acceptable way to refer to dependencies in type annotations or code. Fully\nqualified namespaces must not be used anywhere, except as an argument to\n<code>goog.require</code> or <code>goog.requireType</code>.</p>\n\n<p><strong>Exception</strong>: Types, variables, and functions declared in externs files have to\nuse their fully qualified name in type annotations and code.</p>\n\n<p>When <code>goog.require</code> is assigned to a single constant alias, it must match the\nfinal dot-separated component of the imported module's namespace.</p>\n\n<p><strong>Exception</strong>: In certain cases, additional components of the namespace can be\nused to form a longer alias. The resulting alias must retain the original\nidentifier's casing such that it still correctly identifies its type. Longer\naliases may be used to disambiguate otherwise identical aliases, or if it\nsignificantly improves readability. In addition, a longer alias must be used to\nprevent masking native types such as <code>Element</code>, <code>Event</code>, <code>Error</code>, <code>Map</code>, and\n<code>Promise</code> (for a more complete list, see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects\">Standard Built-in Objects</a> and\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/API\">Web APIs</a> at MDN).</p>\nWhen renaming destructured aliases, a space must follow the colon\nas required in <a href=\"#formatting-horizontal-whitespace\">??</a>.</p>\n\n<p>A file should not contain both a <code>goog.require</code> and a <code>goog.requireType</code>\nstatement for the same namespace. If the imported name is used both in code and\nin type annotations, it should be imported by a single <code>goog.require</code> statement.</p>\n\n<p>If a module is imported only for its side effects, the call must be a\n<code>goog.require</code> (not a <code>goog.requireType</code>) and assignment may be omitted. A\ncomment is required to explain why this is needed and suppress a compiler\nwarning.</p>\n\n\n\n<p>The lines are sorted according to the following rules: All requires with a name\non the left hand side come first, sorted alphabetically by those names. Then\ndestructuring requires, again sorted by the names on the left hand side.\nFinally, any require calls that are standalone (generally these are for modules\nimported just for their side effects).</p>\n\n<p>Tip: There’s no need to memorize this order and enforce it manually. You can\nrely on your IDE to report requires\nthat are not sorted correctly.</p>\n\n<p>If a long alias or module name would cause a line to exceed the 80-column limit,\nit <strong>must not</strong> be wrapped: require lines are an exception to the 80-column\nlimit.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">// Standard alias style.\nconst asserts = goog.require('goog.asserts');\n// Namespace-based alias used to disambiguate.\nconst testingAsserts = goog.require('goog.testing.asserts');\n// Standard destructuring into aliases.\nconst {MyClass} = goog.require('some.package');\nconst {MyType} = goog.requireType('other.package');\nconst {clear, clone} = goog.require('goog.array');\nconst {Rgb} = goog.require('goog.color');\n// Namespace-based destructuring into aliases used to disambiguate.\nconst {MyClass: NsMyClass} = goog.require('other.ns');\nconst {SomeType: FooSomeType} = goog.requireType('foo.types');\nconst {clear: objectClear, clone: objectClone} = goog.require('goog.object');\n// Namespace-based destructuring into aliases used to prevent masking native type.\nconst {Element: RendererElement} = goog.require('web.renderer');\n// Out of sequence namespace-based aliases used to improve readability.\n// Also, require lines longer than 80 columns must not be wrapped.\nconst {SomeDataStructure: SomeDataStructureModel} = goog.requireType('identical.package.identifiers.models');\nconst {SomeDataStructure: SomeDataStructureProto} = goog.require('proto.identical.package.identifiers');\n// goog.require without an alias in order to trigger side effects.\n/** @suppress {extraRequire} Initializes MyFramework. */\ngoog.require('my.framework.initialization');\n</code></pre>\n\n<p>Discouraged:</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Some legacy code uses a \"default export\" style to export a single class, enum,\n// record type, etc. Do not use this pattern in new JS.\n// When using a \"default export\", prefer destructuring into aliases.\nconst MyClass = goog.require('some.package.MyClass');\nconst MyType = goog.requireType('some.package.MyType');\n</code></pre>\n\n<pre><code class=\"language-js prettyprint bad\">// If necessary to disambiguate, prefer PackageClass over SomeClass as it is\n// closer to the format of the module name.\nconst SomeClass = goog.require('some.package.Class');\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Extra terms must come from the namespace.\nconst MyClassForBizzing = goog.require('some.package.MyClass');\n// Alias must include the entire final namespace component.\nconst MyClass = goog.require('some.package.MyClassForBizzing');\n// Alias must not mask native type (should be `const JspbMap` here).\nconst Map = goog.require('jspb.Map');\n// Don't break goog.require lines over 80 columns.\nconst SomeDataStructure =\n    goog.require('proto.identical.package.identifiers.SomeDataStructure');\n// Alias must be based on the namespace.\nconst randomName = goog.require('something.else');\n// Missing a space after the colon.\nconst {Foo:FooProto} = goog.require('some.package.proto.Foo');\n// goog.requireType without an alias.\ngoog.requireType('some.package.with.a.Type');\n\n\n/**\n * @param {!some.unimported.Dependency} param All external types used in JSDoc\n *     annotations must be goog.require'd, unless declared in externs.\n */\nfunction someFunction(param) {\n  // goog.require lines must be at the top level before any other code.\n  const alias = goog.require('my.long.name.alias');\n  // ...\n}\n</code></pre>\n\n<h3 id=\"file-implementation\">3.7 The file’s implementation</h3>\n\n<p>The actual implementation follows after all dependency information is declared\n(separated by at least one blank line).</p>\n\n<p>This may consist of any module-local declarations (constants, variables,\nclasses, functions, etc), as well as any exported symbols.</p>\n\n<h2 id=\"formatting\">4 Formatting</h2>\n\n<p><strong>Terminology Note</strong>: <em>block-like construct</em> refers to the body of a class,\nfunction, method, or brace-delimited block of code. Note that, by\n<a href=\"#features-array-literals\">??</a> and <a href=\"#features-object-literals\">??</a>, any array or\nobject literal may optionally be treated as if it were a block-like construct.</p>\n\n<p>Tip: Use <code>clang-format</code>. The JavaScript community has invested effort to make\nsure clang-format <q>does the right thing</q> on JavaScript files. <code>clang-format</code> has\nintegration with several popular editors.</p>\n\n<h3 id=\"formatting-braces\">4.1 Braces</h3>\n\n<h4 id=\"formatting-braces-all\">4.1.1 Braces are used for all control structures</h4>\n\n<p>Braces are required for all control structures (i.e. <code>if</code>, <code>else</code>, <code>for</code>, <code>do</code>,\n<code>while</code>, as well as any others), even if the body contains only a single\nstatement. The first statement of a non-empty block must begin on its own line.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">if (someVeryLongCondition())\n  doSomething();\n\nfor (let i = 0; i &lt; foo.length; i++) bar(foo[i]);\n</code></pre>\n\n<p><strong>Exception</strong>: A simple if statement that can fit entirely on a single line with\nno wrapping (and that doesn’t have an else) may be kept on a single line with no\nbraces when it improves readability. This is the only case in which a control\nstructure may omit braces and newlines.</p>\n\n<pre><code class=\"language-js prettyprint good\">if (shortCondition()) foo();\n</code></pre>\n\n<h4 id=\"formatting-nonempty-blocks\">4.1.2 Nonempty blocks: K&amp;R style</h4>\n\n<p>Braces follow the Kernighan and Ritchie style (<q><a href=\"https://blog.codinghorror.com/new-programming-jargon/#3\">Egyptian brackets</a></q>) for\n<em>nonempty</em> blocks and block-like constructs:</p>\n\n<ul>\n<li>No line break before the opening brace.</li>\n<li>Line break after the opening brace.</li>\n<li>Line break before the closing brace.</li>\n<li>Line break after the closing brace <em>if</em> that brace terminates a statement or\nthe body of a function or class statement, or a class method. Specifically,\nthere is <em>no</em> line break after the brace if it is followed by <code>else</code>,\n<code>catch</code>, <code>while</code>, or a comma, semicolon, or right-parenthesis.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">class InnerClass {\n  constructor() {}\n\n  /** @param {number} foo */\n  method(foo) {\n    if (condition(foo)) {\n      try {\n        // Note: this might fail.\n        something();\n      } catch (err) {\n        recover();\n      }\n    }\n  }\n}\n</code></pre>\n\n<h4 id=\"formatting-empty-blocks\">4.1.3 Empty blocks: may be concise</h4>\n\n<p>An empty block or block-like construct <em>may</em> be closed immediately after it is\nopened, with no characters, space, or line break in between (i.e. <code>{}</code>),\n<strong>unless</strong> it is a part of a <em>multi-block statement</em> (one that directly contains\nmultiple blocks: <code>if</code>/<code>else</code> or <code>try</code>/<code>catch</code>/<code>finally</code>).</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">function doNothing() {}\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">if (condition) {\n  // …\n} else if (otherCondition) {} else {\n  // …\n}\n\ntry {\n  // …\n} catch (e) {}\n</code></pre>\n\n<h3 id=\"formatting-block-indentation\">4.2 Block indentation: +2 spaces</h3>\n\n<p>Each time a new block or block-like construct is opened, the indent increases by\ntwo spaces. When the block ends, the indent returns to the previous indent\nlevel. The indent level applies to both code and comments throughout the block.\n(See the example in <a href=\"#formatting-nonempty-blocks\">??</a>).</p>\n\n<h4 id=\"formatting-array-literals\">4.2.1 Array literals: optionally <q>block-like</q></h4>\n\n<p>Any array literal may optionally be formatted as if it were a “block-like\nconstruct.” For example, the following are all valid (<strong>not</strong> an exhaustive\nlist):</p>\n\n<pre><code class=\"language-js prettyprint good\">const a = [\n  0,\n  1,\n  2,\n];\n\nconst b =\n    [0, 1, 2];\n\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">const c = [0, 1, 2];\n\nsomeMethod(foo, [\n  0, 1, 2,\n], bar);\n</code></pre>\n\n<p>Other combinations are allowed, particularly when emphasizing semantic groupings\nbetween elements, but should not be used only to reduce the vertical size of\nlarger arrays.</p>\n\n<h4 id=\"formatting-object-literals\">4.2.2 Object literals: optionally <q>block-like</q></h4>\n\n<p>Any object literal may optionally be formatted as if it were a “block-like\nconstruct.” The same examples apply as <a href=\"#formatting-array-literals\">??</a>. For\nexample, the following are all valid (<strong>not</strong> an exhaustive list):</p>\n\n<pre><code class=\"language-js prettyprint good\">const a = {\n  a: 0,\n  b: 1,\n};\n\nconst b =\n    {a: 0, b: 1};\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">const c = {a: 0, b: 1};\n\nsomeMethod(foo, {\n  a: 0, b: 1,\n}, bar);\n</code></pre>\n\n<h4 id=\"formatting-class-literals\">4.2.3 Class literals</h4>\n\n<p>Class literals (whether declarations or expressions) are indented as blocks. Do\nnot add semicolons after methods, or after the closing brace of a class\n<em>declaration</em> (statements—such as assignments—that contain class <em>expressions</em>\nare still terminated with a semicolon). For inheritance, the <code>extends</code> keyword\nis sufficient unless the superclass is templatized. Subclasses of templatized\ntypes must explicitly specify the template type in an <code>@extends</code> JSDoc\nannotation, even if it is just passing along the same template name.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @template T */\nclass Foo {\n  /** @param {T} x */\n  constructor(x) {\n    /** @type {T} */\n    this.x = x;\n  }\n}\n\n/** @extends {Foo&lt;number&gt;} */\nclass Bar extends Foo {\n  constructor() {\n    super(42);\n  }\n}\n\nexports.Baz = class extends Bar {\n  /** @return {number} */\n  method() {\n    return this.x;\n  }\n};\n</code></pre>\n\n<pre><code class=\"language-js prettyprint bad\">/** @extends {Bar} */ // &lt;-- unnecessary @extends\nexports.Baz = class extends Bar {\n  /** @return {number} */\n  method() {\n    return this.x;\n  }\n};\n</code></pre>\n\n<h4 id=\"formatting-function-expressions\">4.2.4 Function expressions</h4>\n\n<p>When declaring an anonymous function in the list of arguments for a function\ncall, the body of the function is indented two spaces more than the preceding\nindentation depth.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">prefix.something.reallyLongFunctionName('whatever', (a1, a2) =&gt; {\n  // Indent the function body +2 relative to indentation depth\n  // of the 'prefix' statement one line above.\n  if (a1.equals(a2)) {\n    someOtherLongFunctionName(a1);\n  } else {\n    andNowForSomethingCompletelyDifferent(a2.parrot);\n  }\n});\n\nsome.reallyLongFunctionCall(arg1, arg2, arg3)\n    .thatsWrapped()\n    .then((result) =&gt; {\n      // Indent the function body +2 relative to the indentation depth\n      // of the '.then()' call.\n      if (result) {\n        result.use();\n      }\n    });\n</code></pre>\n\n<h4 id=\"formatting-switch-statements\">4.2.5 Switch statements</h4>\n\n<p>As with any other block, the contents of a switch block are indented +2.</p>\n\n\n\n<p>After a switch label, a newline appears, and the indentation level is increased\n+2, exactly as if a block were being opened. An explicit block may be used if\nrequired by lexical scoping. The following switch label returns to the previous\nindentation level, as if a block had been closed.</p>\n\n<p>A blank line is optional between a <code>break</code> and the following case.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">switch (animal) {\n  case Animal.BANDERSNATCH:\n    handleBandersnatch();\n    break;\n\n  case Animal.JABBERWOCK:\n    handleJabberwock();\n    break;\n\n  default:\n    throw new Error('Unknown animal');\n}\n</code></pre>\n\n<h3 id=\"formatting-statements\">4.3 Statements</h3>\n\n<h4 id=\"formatting-one-statement-perline\">4.3.1 One statement per line</h4>\n\n<p>Each statement is followed by a line-break.</p>\n\n<h4 id=\"formatting-semicolons-are-required\">4.3.2 Semicolons are required</h4>\n\n<p>Every statement must be terminated with a semicolon. Relying on automatic\nsemicolon insertion is forbidden.</p>\n\n<h3 id=\"formatting-column-limit\">4.4 Column limit: 80</h3>\n\n<p>JavaScript code has a column limit of 80 characters. Except as noted below, any\nline that would exceed this limit must be line-wrapped, as explained in\n<a href=\"#formatting-line-wrapping\">??</a>.</p>\n\n<p><strong>Exceptions:</strong></p>\n\n<ol>\n<li><code>goog.module</code>, <code>goog.require</code> and <code>goog.requireType</code> statements (see\n<a href=\"#file-goog-module\">??</a> and <a href=\"#file-goog-require\">??</a>).</li>\n<li>ES module <code>import</code> and <code>export from</code> statements (see\n<a href=\"#es-module-imports\">??</a> and <a href=\"#es-module-export-from\">??</a>).</li>\n<li>Lines where obeying the column limit is not possible or would hinder\ndiscoverability. Examples include:\n<ul>\n<li>A long URL which should be clickable in source.</li>\n<li>A shell command intended to be copied-and-pasted.</li>\n<li>A long string literal which may need to be copied or searched for wholly\n(e.g., a long file path).</li>\n</ul></li>\n</ol>\n\n<h3 id=\"formatting-line-wrapping\">4.5 Line-wrapping</h3>\n\n<p><strong>Terminology Note</strong>: <em>Line wrapping</em> is breaking a chunk of code into multiple\nlines to obey column limit, where the chunk could otherwise legally fit in a\nsingle line.</p>\n\n<p>There is no comprehensive, deterministic formula showing <em>exactly</em> how to\nline-wrap in every situation. Very often there are several valid ways to\nline-wrap the same piece of code.</p>\n\n<p>Note: While the typical reason for line-wrapping is to avoid overflowing the\ncolumn limit, even code that would in fact fit within the column limit may be\nline-wrapped at the author's discretion.</p>\n\n<p>Tip: Extracting a method or local variable may solve the problem without the\nneed to line-wrap.</p>\n\n<h4 id=\"formatting-where-to-break\">4.5.1 Where to break</h4>\n\n<p>The prime directive of line-wrapping is: prefer to break at a <strong>higher syntactic\nlevel</strong>. </p>\n\n<p>Preferred:</p>\n\n<pre><code class=\"language-js prettyprint good\">currentEstimate =\n    calc(currentEstimate + x * currentEstimate) /\n        2.0;\n</code></pre>\n\n<p>Discouraged:</p>\n\n<pre><code class=\"language-js prettyprint bad\">currentEstimate = calc(currentEstimate + x *\n    currentEstimate) / 2.0;\n</code></pre>\n\n<p>In the preceding example, the syntactic levels from highest to lowest are as\nfollows: assignment, division, function call, parameters, number constant.</p>\n\n<p>Operators are wrapped as follows:</p>\n\n<ol>\n<li>When a line is broken at an operator the break comes after the symbol. (Note\nthat this is not the same practice used in Google style for Java.)\n<ol>\n<li>This does not apply to the <q>dot</q> (<code>.</code>), which is not actually an\noperator.</li>\n</ol></li>\n<li>A method or constructor name stays attached to the open parenthesis (<code>(</code>)\nthat follows it.</li>\n<li>A comma (<code>,</code>) stays attached to the token that precedes it.</li>\n<li>A line break is never added between a return and the return value as this\nwould change the meaning of the code.</li>\n<li>JSDoc annotations with type names break after <q>{</q>. This is necessary as\nannotations with optional types (@const, @private, @param, etc) do not scan\nthe next line.</li>\n</ol>\n\n<blockquote>\n<p>Note: The primary goal for line wrapping is to have clear code, not\nnecessarily code that fits in the smallest number of lines.</p>\n</blockquote>\n\n<h4 id=\"formatting-indent\">4.5.2 Indent continuation lines at least +4 spaces</h4>\n\n<p>When line-wrapping, each line after the first (each <em>continuation line</em>) is\nindented at least +4 from the original line, unless it falls under the rules of\nblock indentation.</p>\n\n<p>When there are multiple continuation lines, indentation may be varied beyond +4\nas appropriate. In general, continuation lines at a deeper syntactic level are\nindented by larger multiples of 4, and two lines use the same indentation level\nif and only if they begin with syntactically parallel elements.</p>\n\n<p><a href=\"#formatting-horizontal-alignment\">??</a> addresses the discouraged practice of\nusing a variable number of spaces to align certain tokens with previous lines.</p>\n\n<h3 id=\"formatting-whitespace\">4.6 Whitespace</h3>\n\n<h4 id=\"formatting-vertical-whitespace\">4.6.1 Vertical whitespace</h4>\n\n<p>A single blank line appears:</p>\n\n<ol>\n<li>Between consecutive methods in a class or object literal\n<ol>\n<li>Exception: A blank line between two consecutive properties definitions\nin an object literal (with no other code between them) is optional. Such\nblank lines are used as needed to create <em>logical groupings</em> of fields.</li>\n</ol></li>\n<li>Within method bodies, sparingly to create <em>logical groupings</em> of statements.\nBlank lines at the start or end of a function body are not allowed.</li>\n<li><em>Optionally</em> before the first or after the last method in a class or object\nliteral (neither encouraged nor discouraged).</li>\n<li>As required by other sections of this document (e.g.\n<a href=\"#file-goog-require\">??</a>).</li>\n</ol>\n\n<p><em>Multiple</em> consecutive blank lines are permitted, but never required (nor\nencouraged).</p>\n\n<h4 id=\"formatting-horizontal-whitespace\">4.6.2 Horizontal whitespace</h4>\n\n<p>Use of horizontal whitespace depends on location, and falls into three broad\ncategories: <em>leading</em> (at the start of a line), <em>trailing</em> (at the end of a\nline), and <em>internal</em>. Leading whitespace (i.e., indentation) is addressed\nelsewhere. Trailing whitespace is forbidden.</p>\n\n<p>Beyond where required by the language or other style rules, and apart from\nliterals, comments, and JSDoc, a single internal ASCII space also appears in the\nfollowing places <strong>only</strong>.</p>\n\n<ol>\n<li>Separating any reserved word (such as <code>if</code>, <code>for</code>, or <code>catch</code>) except for\n<code>function</code> and <code>super</code>, from an open parenthesis (<code>(</code>) that follows it on\nthat line.</li>\n<li>Separating any reserved word (such as <code>else</code> or <code>catch</code>) from a closing\ncurly brace (<code>}</code>) that precedes it on that line.</li>\n<li>Before any open curly brace (<code>{</code>), with two exceptions:\n<ol>\n<li>Before an object literal that is the first argument of a function or the\nfirst element in an array literal (e.g. <code>foo({a: [{c: d}]})</code>).</li>\n<li>In a template expansion, as it is forbidden by the language (e.g. valid:\n<code>`ab${1 + 2}cd`</code>, invalid: <code class=\"badcode\">`xy$ {3}z`</code>).</li>\n</ol></li>\n<li>On both sides of any binary or ternary operator.</li>\n<li>After a comma (<code>,</code>) or semicolon (<code>;</code>). Note that spaces are <em>never</em> allowed\nbefore these characters.</li>\n<li>After the colon (<code>:</code>) in an object literal.</li>\n<li>On both sides of the double slash (<code>//</code>) that begins an end-of-line comment.\nHere, multiple spaces are allowed, but not required.</li>\n<li>After an open-block comment character and on both sides of close characters\n(e.g. for short-form type declarations, casts, and parameter name comments:\n<code>this.foo = /** @type {number} */ (bar)</code>; or <code>function(/** string */ foo)\n{</code>; or <code>baz(/* buzz= */ true)</code>).</li>\n</ol>\n\n<h4 id=\"formatting-horizontal-alignment\">4.6.3 Horizontal alignment: discouraged</h4>\n\n<p><strong>Terminology Note</strong>: <em>Horizontal alignment</em> is the practice of adding a\nvariable number of additional spaces in your code with the goal of making\ncertain tokens appear directly below certain other tokens on previous lines.</p>\n\n<p>This practice is permitted, but it is <strong>generally discouraged</strong> by Google Style.\nIt is not even required to <em>maintain</em> horizontal alignment in places where it\nwas already used.</p>\n\n<p>Here is an example without alignment, followed by one with alignment. Both are\nallowed, but the latter is discouraged:</p>\n\n<pre><code class=\"language-js prettyprint good\">{\n  tiny: 42, // this is great\n  longer: 435, // this too\n};\n\n{\n  tiny:   42,  // permitted, but future edits\n  longer: 435, // may leave it unaligned\n};\n</code></pre>\n\n<p>Tip: Alignment can aid readability, but it creates problems for future\nmaintenance. Consider a future change that needs to touch just one line. This\nchange may leave the formerly-pleasing formatting mangled, and that is allowed.\nMore often it prompts the coder (perhaps you) to adjust whitespace on nearby\nlines as well, possibly triggering a cascading series of reformattings. That\none-line change now has a <q>blast radius.</q> This can at worst result in pointless\nbusywork, but at best it still corrupts version history information, slows down\nreviewers and exacerbates merge conflicts.</p>\n\n<h4 id=\"formatting-function-arguments\">4.6.4 Function arguments</h4>\n\n<p>Prefer to put all function arguments on the same line as the function name. If\ndoing so would exceed the 80-column limit, the arguments must be line-wrapped in\na readable way. To save space, you may wrap as close to 80 as possible, or put\neach argument on its own line to enhance readability. Indentation should be four\nspaces. Aligning to the parenthesis is allowed, but discouraged. Below are the\nmost common patterns for argument wrapping:</p>\n\n<pre><code class=\"language-js prettyprint good\">// Arguments start on a new line, indented four spaces. Preferred when the\n// arguments don't fit on the same line with the function name (or the keyword\n// \"function\") but fit entirely on the second line. Works with very long\n// function names, survives renaming without reindenting, low on space.\ndoSomething(\n    descriptiveArgumentOne, descriptiveArgumentTwo, descriptiveArgumentThree) {\n  // …\n}\n\n// If the argument list is longer, wrap at 80. Uses less vertical space,\n// but violates the rectangle rule and is thus not recommended.\ndoSomething(veryDescriptiveArgumentNumberOne, veryDescriptiveArgumentTwo,\n    tableModelEventHandlerProxy, artichokeDescriptorAdapterIterator) {\n  // …\n}\n\n// Four-space, one argument per line.  Works with long function names,\n// survives renaming, and emphasizes each argument.\ndoSomething(\n    veryDescriptiveArgumentNumberOne,\n    veryDescriptiveArgumentTwo,\n    tableModelEventHandlerProxy,\n    artichokeDescriptorAdapterIterator) {\n  // …\n}\n</code></pre>\n\n<h3 id=\"formatting-grouping-parentheses\">4.7 Grouping parentheses: recommended</h3>\n\n<p>Optional grouping parentheses are omitted only when the author and reviewer\nagree that there is no reasonable chance that the code will be misinterpreted\nwithout them, nor would they have made the code easier to read. It is <em>not</em>\nreasonable to assume that every reader has the entire operator precedence table\nmemorized.</p>\n\n<p>Do not use unnecessary parentheses around the entire expression following\n<code>delete</code>, <code>typeof</code>, <code>void</code>, <code>return</code>, <code>throw</code>, <code>case</code>, <code>in</code>, <code>of</code>, or <code>yield</code>.</p>\n\n<p>Parentheses are required for type casts: <code>/** @type {!Foo} */ (foo)</code>.</p>\n\n<h3 id=\"formatting-comments\">4.8 Comments</h3>\n\n<p>This section addresses <em>implementation comments</em>. JSDoc is addressed separately\nin <a href=\"#jsdoc\">??</a>.</p>\n\n<h4 id=\"formatting-block-comment-style\">4.8.1 Block comment style</h4>\n\n<p>Block comments are indented at the same level as the surrounding code. They may\nbe in <code>/* … */</code> or <code>//</code>-style. For multi-line <code>/* … */</code> comments, subsequent\nlines must start with <code>*</code> aligned with the <code>*</code> on the previous line, to make\ncomments obvious with no extra context.</p>\n\n<pre><code class=\"language-js prettyprint good\">/*\n * This is\n * okay.\n */\n\n// And so\n// is this.\n\n/* This is fine, too. */\n</code></pre>\n\n<p>Comments are not enclosed in boxes drawn with asterisks or other characters.</p>\n\n<p>Do not use JSDoc (<code>/** … */</code>) for implementation comments.</p>\n\n<h4 id=\"formatting-param-name-comments\">4.8.2 Parameter Name Comments</h4>\n\n<p>“Parameter name” comments should be used whenever the value and method name do\nnot sufficiently convey the meaning, and refactoring the method to be clearer is\ninfeasible .\nTheir preferred format is before the value with <q>=</q>:</p>\n\n<pre><code class=\"language-js prettyprint good\">someFunction(obviousParam, /* shouldRender= */ true, /* name= */ 'hello');\n</code></pre>\n\n<p>For consistency with surrounding code you may put them after the value without\n<q>=</q>:</p>\n\n<pre><code class=\"language-js prettyprint good\">someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);\n</code></pre>\n\n<h2 id=\"language-features\">5 Language features</h2>\n\n<p>JavaScript includes many dubious (and even dangerous) features. This section\ndelineates which features may or may not be used, and any additional constraints\non their use.</p>\n\n<p>Language features which are not discussed in this style guide may be used with\nno recommendations of their usage.</p>\n\n<h3 id=\"features-local-variable-declarations\">5.1 Local variable declarations</h3>\n\n<h4 id=\"features-use-const-and-let\">5.1.1 Use <code>const</code> and <code>let</code></h4>\n\n<p>Declare all local variables with either <code>const</code> or <code>let</code>. Use <code>const</code> by\ndefault, unless a variable needs to be reassigned. The <code class=\"badcode\">var</code> keyword\nmust not be used.</p>\n\n<h4 id=\"features-one-variable-per-declaration\">5.1.2 One variable per declaration</h4>\n\n<p>Every local variable declaration declares only one variable: declarations such\nas <code class=\"badcode\">let a = 1, b = 2;</code> are not used.</p>\n\n<h4 id=\"features-declared-when-needed\">5.1.3 Declared when needed, initialized as soon as possible</h4>\n\n<p>Local variables are <strong>not</strong> habitually declared at the start of their containing\nblock or block-like construct. Instead, local variables are declared close to\nthe point they are first used (within reason), to minimize their scope, and\ninitialized as soon as possible.</p>\n\n<h4 id=\"features-declare-types-as-needed\">5.1.4 Declare types as needed</h4>\n\n<p>JSDoc type annotations may be added either on the line above the declaration, or\nelse inline before the variable name if no other JSDoc is present.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">const /** !Array&lt;number&gt; */ data = [];\n\n/**\n * Some description.\n * @type {!Array&lt;number&gt;}\n */\nconst data = [];\n</code></pre>\n\n<p>Mixing inline and JSDoc styles is not allowed: the compiler will only process\nthe first JsDoc and the inline annotations will be lost.</p>\n\n<pre><code class=\"language-js prettyprint bad\">/** Some description. */\nconst /** !Array&lt;number&gt; */ data = [];\n</code></pre>\n\n<p>Tip: There are many cases where the compiler can infer a templatized type but\nnot its parameters. This is particularly the case when the initializing literal\nor constructor call does not include any values of the template parameter type\n(e.g., empty arrays, objects, <code>Map</code>s, or <code>Set</code>s), or if the variable is modified\nin a closure. Local variable type annotations are particularly helpful in these\ncases since otherwise the compiler will infer the template parameter as unknown.</p>\n\n<h3 id=\"features-array-literals\">5.2 Array literals</h3>\n\n<h4 id=\"features-arrays-trailing-comma\">5.2.1 Use trailing commas</h4>\n\n\n\n<p>Include a trailing comma whenever there is a line break between the final\nelement and the closing bracket.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">const values = [\n  'first value',\n  'second value',\n];\n</code></pre>\n\n<h4 id=\"features-arrays-ctor\">5.2.2 Do not use the variadic <code>Array</code> constructor</h4>\n\n<p>The constructor is error-prone if arguments are added or removed. Use a literal\ninstead.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">const a1 = new Array(x1, x2, x3);\nconst a2 = new Array(x1, x2);\nconst a3 = new Array(x1);\nconst a4 = new Array();\n</code></pre>\n\n<p>This works as expected except for the third case: if <code>x1</code> is a whole number then\n<code>a3</code> is an array of size <code>x1</code> where all elements are <code>undefined</code>. If <code>x1</code> is any\nother number, then an exception will be thrown, and if it is anything else then\nit will be a single-element array.</p>\n\n<p>Instead, write</p>\n\n<pre><code class=\"language-js prettyprint good\">const a1 = [x1, x2, x3];\nconst a2 = [x1, x2];\nconst a3 = [x1];\nconst a4 = [];\n</code></pre>\n\n<p>Explicitly allocating an array of a given length using <code>new Array(length)</code> is\nallowed when appropriate.</p>\n\n<h4 id=\"features-arrays-non-numeric-properties\">5.2.3 Non-numeric properties</h4>\n\n<p>Do not define or use non-numeric properties on an array (other than <code>length</code>).\nUse a <code>Map</code> (or <code>Object</code>) instead.</p>\n\n<h4 id=\"features-arrays-destructuring\">5.2.4 Destructuring</h4>\n\n<p>Array literals may be used on the left-hand side of an assignment to perform\ndestructuring (such as when unpacking multiple values from a single array or\niterable). A final <q>rest</q> element may be included (with no space between the\n<code>...</code> and the variable name). Elements should be omitted if they are unused.</p>\n\n<pre><code class=\"language-js prettyprint good\">const [a, b, c, ...rest] = generateResults();\nlet [, b,, d] = someArray;\n</code></pre>\n\n<p>Destructuring may also be used for function parameters (note that a parameter\nname is required but ignored). Always specify <code>[]</code> as the default value if a\ndestructured array parameter is optional, and provide default values on the left\nhand side:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @param {!Array&lt;number&gt;=} param1 */\nfunction optionalDestructuring([a = 4, b = 2] = []) { … };\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">function badDestructuring([a, b] = [4, 2]) { … };\n</code></pre>\n\n<p>Tip: For (un)packing multiple values into a function’s parameter or return,\nprefer object destructuring to array destructuring when possible, as it allows\nnaming the individual elements and specifying a different type for each.</p>\n\n<h4 id=\"features-arrays-spread-operator\">5.2.5 Spread operator</h4>\n\n<p>Array literals may include the spread operator (<code>...</code>) to flatten elements out\nof one or more other iterables. The spread operator should be used instead of\nmore awkward constructs with <code>Array.prototype</code>. There is no space after the\n<code>...</code>.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">[...foo]   // preferred over Array.prototype.slice.call(foo)\n[...foo, ...bar]   // preferred over foo.concat(bar)\n</code></pre>\n\n<h3 id=\"features-object-literals\">5.3 Object literals</h3>\n\n<h4 id=\"features-objects-use-trailing-comma\">5.3.1 Use trailing commas</h4>\n\n<p>Include a trailing comma whenever there is a line break between the final\nproperty and the closing brace.</p>\n\n<h4 id=\"features-objects-ctor\">5.3.2 Do not use the <code>Object</code> constructor</h4>\n\n<p>While <code>Object</code> does not have the same problems as <code>Array</code>, it is still\ndisallowed for consistency. Use an object literal (<code>{}</code> or <code>{a: 0, b: 1, c: 2}</code>)\ninstead.</p>\n\n<h4 id=\"features-objects-mixing-keys\">5.3.3 Do not mix quoted and unquoted keys</h4>\n\n<p>Object literals may represent either <em>structs</em> (with unquoted keys and/or\nsymbols) or <em>dicts</em> (with quoted and/or computed keys). Do not mix these key\ntypes in a single object literal.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">{\n  width: 42, // struct-style unquoted key\n  'maxWidth': 43, // dict-style quoted key\n}\n</code></pre>\n\n<p>This also extends to passing the property name to functions, like\n<code>hasOwnProperty</code>. In particular, doing so will break in compiled code because\nthe compiler cannot rename/obfuscate the string literal.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">/** @type {{width: number, maxWidth: (number|undefined)}} */\nconst o = {width: 42};\nif (o.hasOwnProperty('maxWidth')) {\n  ...\n}\n</code></pre>\n\n<p>This is best implemented as:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @type {{width: number, maxWidth: (number|undefined)}} */\nconst o = {width: 42};\nif (o.maxWidth != null) {\n  ...\n}\n</code></pre>\n\n<h4 id=\"features-objects-computed-property-names\">5.3.4 Computed property names</h4>\n\n<p>Computed property names (e.g., <code>{['key' + foo()]: 42}</code>) are allowed, and are\nconsidered dict-style (quoted) keys (i.e., must not be mixed with non-quoted\nkeys) unless the computed property is a\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\">symbol</a>\n(e.g., <code>[Symbol.iterator]</code>). Enum values may also be used for computed keys, but\nshould not be mixed with non-enum keys in the same literal.</p>\n\n<h4 id=\"features-objects-method-shorthand\">5.3.5 Method shorthand</h4>\n\n<p>Methods can be defined on object literals using the method shorthand (<code>{method()\n{… }}</code>) in place of a colon immediately followed by a <code>function</code> or arrow\nfunction literal.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">return {\n  stuff: 'candy',\n  method() {\n    return this.stuff;  // Returns 'candy'\n  },\n};\n</code></pre>\n\n<p>Note that <code>this</code> in a method shorthand or <code>function</code> refers to the object\nliteral itself whereas <code>this</code> in an arrow function refers to the scope outside\nthe object literal.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">class {\n  getObjectLiteral() {\n    this.stuff = 'fruit';\n    return {\n      stuff: 'candy',\n      method: () =&gt; this.stuff,  // Returns 'fruit'\n    };\n  }\n}\n</code></pre>\n\n<h4 id=\"features-objects-shorthand-properties\">5.3.6 Shorthand properties</h4>\n\n<p>Shorthand properties are allowed on object literals.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">const foo = 1;\nconst bar = 2;\nconst obj = {\n  foo,\n  bar,\n  method() { return this.foo + this.bar; },\n};\nassertEquals(3, obj.method());\n</code></pre>\n\n<h4 id=\"features-objects-destructuring\">5.3.7 Destructuring</h4>\n\n<p>Object destructuring patterns may be used on the left-hand side of an assignment\nto perform destructuring and unpack multiple values from a single object.</p>\n\n<p>Destructured objects may also be used as function parameters, but should be kept\nas simple as possible: a single level of unquoted shorthand properties. Deeper\nlevels of nesting and computed properties may not be used in parameter\ndestructuring. Specify any default values in the left-hand-side of the\ndestructured parameter (<code>{str = 'some default'} = {}</code>, rather than\n<code class=\"badcode\">{str} = {str: 'some default'}</code>), and if a\ndestructured object is itself optional, it must default to <code>{}</code>. The JSDoc for\nthe destructured parameter may be given any name (the name is unused but is\nrequired by the compiler).</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @param {string} ordinary\n * @param {{num: (number|undefined), str: (string|undefined)}=} param1\n *     num: The number of times to do something.\n *     str: A string to do stuff to.\n */\nfunction destructured(ordinary, {num, str = 'some default'} = {}) {}\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">/** @param {{x: {num: (number|undefined), str: (string|undefined)}}} param1 */\nfunction nestedTooDeeply({x: {num, str}}) {};\n/** @param {{num: (number|undefined), str: (string|undefined)}=} param1 */\nfunction nonShorthandProperty({num: a, str: b} = {}) {};\n/** @param {{a: number, b: number}} param1 */\nfunction computedKey({a, b, [a + b]: c}) {};\n/** @param {{a: number, b: string}=} param1 */\nfunction nontrivialDefault({a, b} = {a: 2, b: 4}) {};\n</code></pre>\n\n<p>Destructuring may also be used for <code>goog.require</code> statements, and in this case\nmust not be wrapped: the entire statement occupies one line, regardless of how\nlong it is (see <a href=\"#file-goog-require\">??</a>).</p>\n\n<h4 id=\"features-objects-enums\">5.3.8 Enums</h4>\n\n<p>Enumerations are defined by adding the <code>@enum</code> annotation to an object literal.\nEnums must be module-local or assigned directly on <code>exports</code>, not nested under a\ntype or object.</p>\n\n<p>Additional properties may not be added to an enum after it is defined. Enums\nmust be constant. All enum values must be either a string literal or a number.</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Supported temperature scales.\n * @enum {string}\n */\nconst TemperatureScale = {\n  CELSIUS: 'celsius',\n  FAHRENHEIT: 'fahrenheit',\n};\n\n/**\n * An enum with two values.\n * @enum {number}\n */\nconst Value = {\n  /** The value used shall have been the first. */\n  FIRST_VALUE: 1,\n  /** The second among two values. */\n  SECOND_VALUE: 2,\n};\n</code></pre>\n\n<p>For string enums, all values must be statically initialized and not computed\nusing arithmetic operators, template literal substitution, function calls or\neven a variable reference.</p>\n\n<pre><code class=\"language-js prettyprint bad\">const ABSOLUTE_ZERO = '-273°F';\n\n/**\n * Not supported computed values in string enum.\n * @enum {string}\n */\nconst TemperatureInFahrenheit = {\n  MIN_POSSIBLE: ABSOLUTE_ZERO,\n  ZERO_FAHRENHEIT: 0 + '°F',\n  ONE_FAHRENHEIT: `${Values.FIRST_VALUE}°F`,\n  TWO_FAHRENHEIT: Values.SECOND_VALUE + '°F',\n  SOME_FAHRENHEIT: getTemperatureInFahrenheit() + '°F',\n};\n</code></pre>\n\n<p>Note: Although TypeScript supports a few more patterns for enum values (e.g <code>A:\n'a'+'b'</code>, etc), the restriction of only allowing string literals and numbers for\nenum values is to aid migration to TypeScript. For complex values consider using\na const object without <code>@enum</code>. </p>\n\n<h3 id=\"features-classes\">5.4 Classes</h3>\n\n<h4 id=\"features-classes-constructors\">5.4.1 Constructors</h4>\n\n<p>Constructors are optional. Subclass constructors must call <code>super()</code> before\nsetting any fields or otherwise accessing <code>this</code>. Interfaces should declare\nnon-method properties in the constructor.</p>\n\n<h4 id=\"features-classes-fields\">5.4.2 Fields</h4>\n\n<p>Define all of a concrete object’s fields (i.e. all properties other than\nmethods) in the constructor. Annotate fields that are never reassigned with\n<code>@const</code> (these need not be deeply immutable). Annotate non-public fields with\nthe proper visibility annotation (<code>@private</code>, <code>@protected</code>, <code>@package</code>).\n<code>@private</code> fields' names may optionally end with an underscore. Fields must not\nbe defined within a nested scope in the constructor nor on a concrete class's\n<code>prototype</code>.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">class Foo {\n  constructor() {\n    /** @private @const {!Bar} */\n    this.bar_ = computeBar();\n\n    /** @protected @const {!Baz} */\n    this.baz = computeBaz();\n  }\n}\n</code></pre>\n\n<p>Tip: Properties should never be added to or removed from an instance after the\nconstructor is finished, since it significantly hinders VMs’ ability to\noptimize. If necessary, fields that are initialized later should be explicitly\nset to <code>undefined</code> in the constructor to prevent later shape changes. Adding\n<code>@struct</code> to an object will check that undeclared properties are not\nadded/accessed. Classes have this added by default.</p>\n\n<h4 id=\"features-classes-computed-properties\">5.4.3 Computed properties</h4>\n\n\n\n<p>Computed properties may only be used in classes when the property is a symbol.\nDict-style properties (that is, quoted or computed non-symbol keys, as defined\nin <a href=\"#features-objects-mixing-keys\">??</a>) are not allowed. A <code>[Symbol.iterator]</code>\nmethod should be defined for any classes that are logically iterable. Beyond\nthis, <code>Symbol</code> should be used sparingly.</p>\n\n<p>Tip: be careful of using any other built-in symbols (e.g.,\n<code>Symbol.isConcatSpreadable</code>) as they are not polyfilled by the compiler and will\ntherefore not work in older browsers.</p>\n\n<h4 id=\"features-classes-static-methods\">5.4.4 Static methods</h4>\n\n\n\n<p>Where it does not interfere with readability, prefer module-local functions over\nprivate static methods.</p>\n\n<p>Code should not rely on dynamic dispatch of static methods, because it\ninterferes with Closure Compiler optimizations. Static methods should only be\ncalled on the base class itself. Static methods should not be called on\nvariables containing a dynamic instance that may be either the constructor or a\nsubclass constructor (and must be defined with <code>@nocollapse</code> if this is done),\nand must not be called directly on a subclass that doesn’t define the method\nitself. Do not access <code>this</code> in static methods.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Context for the examples below; by itself this code is allowed.\nclass Base {\n  /** @nocollapse */ static foo() {}\n}\nclass Sub extends Base {}\n\n// discouraged: don't call static methods dynamically\nfunction callFoo(cls) { cls.foo(); }\n\n// Disallowed: don't call static methods on subclasses that don't define it themselves\nSub.foo();\n\n// Disallowed: don't access this in static methods.\nclass Clazz {\n  static foo() {\n    return this.staticField;\n  }\n}\nClass.staticField = 1;\n</code></pre>\n\n<h4 id=\"features-classes-old-style\">5.4.5 Old-style class declarations</h4>\n\n<p>While ES6 classes are preferred, there are cases where ES6 classes may not be\nfeasible. For example:</p>\n\n<ol>\n<li><p>If there exist or will exist subclasses, including frameworks that create\nsubclasses, that cannot be immediately changed to use ES6 class syntax. If\nsuch a class were to use ES6 syntax, all downstream subclasses not using ES6\nclass syntax would need to be modified.</p></li>\n<li><p>Frameworks that require a known <code>this</code> value before calling the superclass\nconstructor, since constructors with ES6 super classes do not have access to\nthe instance <code>this</code> value until the call to <code>super</code> returns.</p></li>\n</ol>\n\n<p>In all other ways the style guide still applies to this code: <code>let</code>, <code>const</code>,\ndefault parameters, rest, and arrow functions should all be used when\nappropriate.</p>\n\n<p><code>goog.defineClass</code> allows for a class-like definition similar to ES6 class\nsyntax:</p>\n\n<pre><code class=\"language-js prettyprint good\">let C = goog.defineClass(S, {\n  /**\n   * @param {string} value\n   */\n  constructor(value) {\n    S.call(this, 2);\n    /** @const */\n    this.prop = value;\n  },\n\n  /**\n   * @param {string} param\n   * @return {number}\n   */\n  method(param) {\n    return 0;\n  },\n});\n</code></pre>\n\n<p>Alternatively, while <code>goog.defineClass</code> should be preferred for all new code,\nmore traditional syntax is also allowed.</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n  * @constructor @extends {S}\n  * @param {string} value\n  */\nfunction C(value) {\n  S.call(this, 2);\n  /** @const */\n  this.prop = value;\n}\ngoog.inherits(C, S);\n\n/**\n * @param {string} param\n * @return {number}\n */\nC.prototype.method = function(param) {\n  return 0;\n};\n</code></pre>\n\n<p>Per-instance properties should be defined in the constructor after the call to\nthe super class constructor, if there is a super class. Methods should be\ndefined on the prototype of the constructor.</p>\n\n<p>Defining constructor prototype hierarchies correctly is harder than it first\nappears! For that reason, it is best to use <code>goog.inherits</code> from\n<a href=\"http://code.google.com/closure/library/\">the Closure Library </a>.</p>\n\n<h4 id=\"features-classes-prototypes\">5.4.6 Do not manipulate <code>prototype</code>s directly</h4>\n\n<p>The <code>class</code> keyword allows clearer and more readable class definitions than\ndefining <code>prototype</code> properties. Ordinary implementation code has no business\nmanipulating these objects, though they are still useful for defining classes as\ndefined in <a href=\"#features-classes-old-style\">??</a>. Mixins and modifying the\nprototypes of builtin objects are explicitly forbidden.</p>\n\n<p><strong>Exception</strong>: Framework code (such as Polymer, or Angular) may need to use <code>prototype</code>s, and should not resort\nto even-worse workarounds to avoid doing so.</p>\n\n<h4 id=\"features-classes-getters-and-setters\">5.4.7 Getters and Setters</h4>\n\n<p>Do not use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get\">JavaScript getter and setter properties</a>. They are potentially\nsurprising and difficult to reason about, and have limited support in the\ncompiler. Provide ordinary methods instead.</p>\n\n<p><strong>Exception</strong>: there are situations where defining a getter or setter is\nunavoidable (e.g. data binding frameworks such as Angular and Polymer, or for\ncompatibility with external APIs that cannot be adjusted). In these cases only,\ngetters and setters may be used <em>with caution</em>, provided they are defined with\nthe <code>get</code> and <code>set</code> shorthand method keywords or <code>Object.defineProperties</code> (not\n<code>Object.defineProperty</code>, which interferes with property renaming). Getters\n<strong>must not</strong> change observable state.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">class Foo {\n  get next() { return this.nextId++; }\n}\n</code></pre>\n\n<h4 id=\"features-classes-overriding-tostring\">5.4.8 Overriding toString</h4>\n\n<p>The <code>toString</code> method may be overridden, but must always succeed and never have\nvisible side effects.</p>\n\n<p>Tip: Beware, in particular, of calling other methods from toString, since\nexceptional conditions could lead to infinite loops.</p>\n\n<h4 id=\"features-classes-interfaces\">5.4.9 Interfaces</h4>\n\n<p>Interfaces may be declared with <code>@interface</code> or <code>@record</code>. Interfaces declared\nwith <code>@record</code> can be explicitly (i.e. via <code>@implements</code>) or implicitly\nimplemented by a class or object literal.</p>\n\n<p>All methods on an interface must be non-static and method bodies must be empty\nblocks. Fields must be declared as uninitialized members in the class\nconstructor.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Something that can frobnicate.\n * @record\n */\nclass Frobnicator {\n  constructor() {\n    /** @type {number} The number of attempts before giving up. */\n    this.attempts;\n  }\n\n  /**\n   * Performs the frobnication according to the given strategy.\n   * @param {!FrobnicationStrategy} strategy\n   */\n  frobnicate(strategy) {}\n}\n\n</code></pre>\n\n<h4 id=\"features-classes-abstract-classes\">5.4.10 Abstract Classes</h4>\n\n<p>Use abstract classes when appropriate. Abstract classes and methods must be\nannotated with <code>@abstract</code>. Do not use <code>goog.abstractMethod</code>. See\n<a href=\"https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\">abstract classes and methods</a>.</p>\n\n<h4 id=\"static-containers\">5.4.11 Do not create static container classes</h4>\n\n<p>Do not use container classes with only static methods or properties for the sake\nof namespacing.</p>\n\n<pre><code class=\"language-js prettyprint bad\">// container.js\n// Bad: Container is an exported class that has only static methods and fields.\nclass Container {\n  /** @return {number} */\n  static bar() {\n    return 1;\n  }\n}\n\n/** @const {number} */\nContainer.FOO = 1;\n\nexports = {Container};\n</code></pre>\n\n<p>Instead, export individual constants and functions:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @return {number} */\nexports.bar = () =&gt; {\n  return 1;\n}\n\n/** @const {number} */\nexports.FOO = 1;\n</code></pre>\n\n<h4 id=\"nested-namespaces\">5.4.12 Do not define nested namespaces</h4>\n\n<p>Do not define a nested type (e.g. class, typedef, enum, interface) on another\nmodule-local name. </p>\n\n<pre><code class=\"language-js prettyprint bad\">// foo.js\ngoog.module('my.namespace');\n\nclass Foo {...}\n\nFoo.Bar = class {...};\n\n/** @enum {number} */\nFoo.Baz = {...};\n\n/** @typedef {{value: number}} */\nFoo.Qux;\n\n/** @interface */\nFoo.Quuz = class {...}\n\nexports.Foo = Foo;\n</code></pre>\n\n<p>These values should be top-level exports. Choose clear names for these values\n(e.g. FooConverter for a Converter that could have been nested on Foo). However,\nwhen the module name is redundant with part of the class name, consider omitting\nthe redundancy: <code>foo.Foo</code> and <code>foo.Converter</code> rather than <code>foo.Foo</code> and\n<code>foo.FooConverter</code>. Importers can add the prefix when necessary for clarity\n(e.g. <code>import {Converter as FooConverter} from './foo';</code>) but cannot easily\nremove the redundancy when importing the entire module as a namespace.</p>\n\n<pre><code class=\"language-js prettyprint good\">// foo.js\ngoog.module('my.namespace');\n\nclass Foo {...}\n\nclass FooBar {...}\n\n/** @enum {string} */\nlet FooBaz = {...};\n\n/** @typedef {{value: number}} */\nlet FooQux;\n\n/** @interface */\nclass FooQuuz {...};\n\nexport = {\n  Foo,\n  FooBar,\n  FooBaz,\n  FooQux,\n  FooQuuz,\n};\n</code></pre>\n\n<h3 id=\"features-functions\">5.5 Functions</h3>\n\n<h4 id=\"features-functions-top-level-functions\">5.5.1 Top-level functions</h4>\n\n<p>Top-level functions may be defined directly on the <code>exports</code> object, or else\ndeclared locally and optionally exported. See <a href=\"#file-goog-module-exports\">??</a>\nfor more on exports.</p>\n\n<p>Examples:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @param {string} str */\nexports.processString = (str) =&gt; {\n  // Process the string.\n};\n</code></pre>\n\n<pre><code class=\"language-js prettyprint good\">/** @param {string} str */\nconst processString = (str) =&gt; {\n  // Process the string.\n};\n\nexports = {processString};\n</code></pre>\n\n<h4 id=\"features-functions-nested-functions\">5.5.2 Nested functions and closures</h4>\n\n<p>Functions may contain nested function definitions. If it is useful to give the\nfunction a name, it should be assigned to a local <code>const</code>.</p>\n\n<h4 id=\"features-functions-arrow-functions\">5.5.3 Arrow functions</h4>\n\n<p>Arrow functions provide a concise function syntax and simplify scoping <code>this</code>\nfor nested functions. Prefer arrow functions over the <code>function</code> keyword for\nnested functions (but see <a href=\"#features-objects-method-shorthand\">??</a>).</p>\n\n<p>Prefer arrow functions over other <code>this</code> scoping approaches such as\n<code>f.bind(this)</code>, <code>goog.bind(f, this)</code>, and <code>const self = this</code>. Arrow functions\nare particularly useful for calling into callbacks as they permit explicitly\nspecifying which parameters to pass to the callback whereas binding will blindly\npass along all parameters.</p>\n\n<p>The left-hand side of the arrow contains zero or more parameters. Parentheses\naround the parameters are optional if there is only a single non-destructured\nparameter. When parentheses are used, inline parameter types may be specified\n(see <a href=\"#jsdoc-method-and-function-comments\">??</a>).</p>\n\n<p>Tip: Always using parentheses even for single-parameter arrow functions can\navoid situations where adding parameters, but forgetting to add parentheses, may\nresult in parseable code which no longer works as intended.</p>\n\n<p>The right-hand side of the arrow contains the body of the function. By default\nthe body is a block statement (zero or more statements surrounded by curly\nbraces). The body may also be an implicitly returned single expression if\neither: the program logic requires returning a value, or the <code>void</code> operator\nprecedes a single function or method call (using <code>void</code> ensures <code>undefined</code> is\nreturned, prevents leaking values, and communicates intent). The single\nexpression form is preferred if it improves readability (e.g., for short or\nsimple expressions).</p>\n\n<p>Examples:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Arrow functions can be documented just like normal functions.\n * @param {number} numParam A number to add.\n * @param {string} strParam Another number to add that happens to be a string.\n * @return {number} The sum of the two parameters.\n */\nconst moduleLocalFunc = (numParam, strParam) =&gt; numParam + Number(strParam);\n\n// Uses the single expression syntax with `void` because the program logic does\n// not require returning a value.\ngetValue((result) =&gt; void alert(`Got ${result}`));\n\nclass CallbackExample {\n  constructor() {\n    /** @private {number} */\n    this.cachedValue_ = 0;\n\n    // For inline callbacks, you can use inline typing for parameters.\n    // Uses a block statement because the value of the single expression should\n    // not be returned and the expression is not a single function call.\n    getNullableValue((/** ?number */ result) =&gt; {\n      this.cachedValue_ = result == null ? 0 : result;\n    });\n  }\n}\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">/**\n * A function with no params and no returned value.\n * This single expression body usage is illegal because the program logic does\n * not require returning a value and we're missing the `void` operator.\n */\nconst moduleLocalFunc = () =&gt; anotherFunction();\n</code></pre>\n\n<h4 id=\"features-functions-generators\">5.5.4 Generators</h4>\n\n<p>Generators enable a number of useful abstractions and may be used as needed.</p>\n\n<p>When defining generator functions, attach the <code>*</code> to the <code>function</code> keyword when\npresent, and separate it with a space from the name of the function. When using\ndelegating yields, attach the <code>*</code> to the <code>yield</code> keyword.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @return {!Iterator&lt;number&gt;} */\nfunction* gen1() {\n  yield 42;\n}\n\n/** @return {!Iterator&lt;number&gt;} */\nconst gen2 = function*() {\n  yield* gen1();\n}\n\nclass SomeClass {\n  /** @return {!Iterator&lt;number&gt;} */\n  * gen() {\n    yield 42;\n  }\n}\n</code></pre>\n\n<h4 id=\"features-functions-parameter-return-types\">5.5.5 Parameter and return types</h4>\n\n<p>Function parameters and return types should usually be documented with JSDoc\nannotations. See <a href=\"#jsdoc-method-and-function-comments\">??</a> for more information.</p>\n\n<h5 id=\"features-functions-default-parameters\">5.5.5.1 Default parameters</h5>\n\n<p>Optional parameters are permitted using the equals operator in the parameter\nlist. Optional parameters must include spaces on both sides of the equals\noperator, be named exactly like required parameters (i.e., not prefixed with\n<code>opt_</code>), use the <code>=</code> suffix in their JSDoc type, come after required parameters,\nand not use initializers that produce observable side effects. All optional\nparameters for concrete functions must have default values, even if that value\nis <code>undefined</code>. In contrast to concrete functions, abstract and interface\nmethods must omit default parameter values.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @param {string} required This parameter is always needed.\n * @param {string=} optional This parameter can be omitted.\n * @param {!Node=} node Another optional parameter.\n */\nfunction maybeDoSomething(required, optional = '', node = undefined) {}\n\n/** @interface */\nclass MyInterface {\n  /**\n   * Interface and abstract methods must omit default parameter values.\n   * @param {string=} optional\n   */\n  someMethod(optional) {}\n}\n</code></pre>\n\n<p>Use default parameters sparingly. Prefer destructuring (as in\n<a href=\"#features-objects-destructuring\">??</a>) to create readable APIs when there are\nmore than a small handful of optional parameters that do not have a natural\norder.</p>\n\n<p>Note: Unlike Python's default parameters, it is okay to use initializers that\nreturn new mutable objects (such as <code>{}</code> or <code>[]</code>) because the initializer is\nevaluated each time the default value is used, so a single object won't be\nshared across invocations.</p>\n\n<p>Tip: While arbitrary expressions including function calls may be used as\ninitializers, these should be kept as simple as possible. Avoid initializers\nthat expose shared mutable state, as that can easily introduce unintended\ncoupling between function calls.</p>\n\n<h5 id=\"features-functions-rest-parameters\">5.5.5.2 Rest parameters</h5>\n\n<p>Use a <em>rest</em> parameter instead of accessing <code>arguments</code>. Rest parameters are\ntyped with a <code>...</code> prefix in their JSDoc. The rest parameter must be the last\nparameter in the list. There is no space between the <code>...</code> and the parameter\nname. Do not name the rest parameter <code>var_args</code>. Never name a local variable or\nparameter <code>arguments</code>, which confusingly shadows the built-in name.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @param {!Array&lt;string&gt;} array This is an ordinary parameter.\n * @param {...number} numbers The remainder of arguments are all numbers.\n */\nfunction variadic(array, ...numbers) {}\n</code></pre>\n\n<h4 id=\"features-functions-generics\">5.5.6 Generics</h4>\n\n<p>Declare generic functions and methods when necessary with <code>@template TYPE</code> in\nthe JSDoc above the function or method definition.</p>\n\n<h4 id=\"features-functions-spread-operator\">5.5.7 Spread operator</h4>\n\n<p>Function calls may use the spread operator (<code>...</code>). Prefer the spread operator\nto <code>Function.prototype.apply</code> when an array or iterable is unpacked into\nmultiple parameters of a variadic function. There is no space after the <code>...</code>.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">function myFunction(...elements) {}\nmyFunction(...array, ...iterable, ...generator());\n</code></pre>\n\n<h3 id=\"features-string-literals\">5.6 String literals</h3>\n\n<h4 id=\"features-strings-use-single-quotes\">5.6.1 Use single quotes</h4>\n\n<p>Ordinary string literals are delimited with single quotes (<code>'</code>), rather than\ndouble quotes (<code>\"</code>).</p>\n\n<p>Tip: if a string contains a single quote character, consider using a template\nstring to avoid having to escape the quote.</p>\n\n<p>Ordinary string literals may not span multiple lines.</p>\n\n<h4 id=\"features-strings-template-strings\">5.6.2 Template literals</h4>\n\n<p>Use template literals (delimited with <code>`</code>) over complex string\nconcatenation, particularly if multiple string literals are involved. Template\nliterals may span multiple lines.</p>\n\n<p>If a template literal spans multiple lines, it does not need to follow the\nindentation of the enclosing block, though it may if the added whitespace does\nnot matter.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">function arithmetic(a, b) {\n  return `Here is a table of arithmetic operations:\n${a} + ${b} = ${a + b}\n${a} - ${b} = ${a - b}\n${a} * ${b} = ${a * b}\n${a} / ${b} = ${a / b}`;\n}\n</code></pre>\n\n<h4 id=\"features-strings-no-line-continuations\">5.6.3 No line continuations</h4>\n\n<p>Do not use <em>line continuations</em> (that is, ending a line inside a string literal\nwith a backslash) in either ordinary or template string literals. Even though\nES5 allows this, it can lead to tricky errors if any trailing whitespace comes\nafter the slash, and is less obvious to readers.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">const longString = 'This is a very long string that far exceeds the 80 \\\n    column limit. It unfortunately contains long stretches of spaces due \\\n    to how the continued lines are indented.';\n</code></pre>\n\n<p>Instead, write</p>\n\n<pre><code class=\"language-js prettyprint good\">const longString = 'This is a very long string that far exceeds the 80 ' +\n    'column limit. It does not contain long stretches of spaces since ' +\n    'the concatenated strings are cleaner.';\n</code></pre>\n\n<h3 id=\"features-number-literals\">5.7 Number literals</h3>\n\n<p>Numbers may be specified in decimal, hex, octal, or binary. Use exactly <code>0x</code>,\n<code>0o</code>, and <code>0b</code> prefixes, with lowercase letters, for hex, octal, and binary,\nrespectively. Never include a leading zero unless it is immediately followed by\n<code>x</code>, <code>o</code>, or <code>b</code>.</p>\n\n<h3 id=\"features-control-structures\">5.8 Control structures</h3>\n\n<h4 id=\"features-for-loops\">5.8.1 For loops</h4>\n\n<p>With ES6, the language now has three different kinds of <code>for</code> loops. All may be\nused, though <code>for</code>-<code>of</code> loops should be preferred when possible.</p>\n\n<p><code>for</code>-<code>in</code> loops may only be used on dict-style objects (see\n<a href=\"#features-objects-mixing-keys\">??</a>), and should not be used to iterate over an\narray. <code>Object.prototype.hasOwnProperty</code> should be used in <code>for</code>-<code>in</code> loops to\nexclude unwanted prototype properties. Prefer <code>for</code>-<code>of</code> and <code>Object.keys</code> over\n<code>for</code>-<code>in</code> when possible.</p>\n\n<h4 id=\"features-exceptions\">5.8.2 Exceptions</h4>\n\n<p>Exceptions are an important part of the language and should be used whenever\nexceptional cases occur. Always throw <code>Error</code>s or subclasses of <code>Error</code>: never\nthrow string literals or other objects. Always use <code>new</code> when constructing an\n<code>Error</code>.</p>\n\n<p>This treatment extends to <code>Promise</code> rejection values as <code>Promise.reject(obj)</code> is\nequivalent to <code>throw obj;</code> in async functions.</p>\n\n<p>Custom exceptions provide a great way to convey additional error information\nfrom functions. They should be defined and used wherever the native <code>Error</code> type\nis insufficient.</p>\n\n<p>Prefer throwing exceptions over ad-hoc error-handling approaches (such as\npassing an error container reference type, or returning an object with an error\nproperty).</p>\n\n<h5 id=\"features-empty-catch-blocks\">5.8.2.1 Empty catch blocks</h5>\n\n<p>It is very rarely correct to do nothing in response to a caught exception. When\nit truly is appropriate to take no action whatsoever in a catch block, the\nreason this is justified is explained in a comment.</p>\n\n<pre><code class=\"language-js prettyprint good\">try {\n  return handleNumericResponse(response);\n} catch (ok) {\n  // it's not numeric; that's fine, just continue\n}\nreturn handleTextResponse(response);\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">  try {\n    shouldFail();\n    fail('expected an error');\n  } catch (expected) {\n  }\n</code></pre>\n\n<p>Tip: Unlike in some other languages, patterns like the above simply don’t work\nsince this will catch the error thrown by <code>fail</code>. Use <code>assertThrows()</code> instead.</p>\n\n<h4 id=\"features-switch-statements\">5.8.3 Switch statements</h4>\n\n<p>Terminology Note: Inside the braces of a switch block are one or more statement\ngroups. Each statement group consists of one or more switch labels (either <code>case\nFOO:</code> or <code>default:</code>), followed by one or more statements.</p>\n\n<h5 id=\"features-switch-fall-through\">5.8.3.1 Fall-through: commented</h5>\n\n<p>Within a switch block, each statement group either terminates abruptly (with a\n<code>break</code>, <code>return</code> or <code>throw</code>n exception), or is marked with a comment to\nindicate that execution will or might continue into the next statement group.\nAny comment that communicates the idea of fall-through is sufficient (typically\n<code>// fall through</code>). This special comment is not required in the last statement\ngroup of the switch block.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">switch (input) {\n  case 1:\n  case 2:\n    prepareOneOrTwo();\n  // fall through\n  case 3:\n    handleOneTwoOrThree();\n    break;\n  default:\n    handleLargeNumber(input);\n}\n</code></pre>\n\n<h5 id=\"features-switch-default-case\">5.8.3.2 The <code>default</code> case is present</h5>\n\n<p>Each switch statement includes a <code>default</code> statement group, even if it contains\nno code. The <code>default</code> statement group must be last.</p>\n\n<h3 id=\"features-this\">5.9 this</h3>\n\n<p>Only use <code>this</code> in class constructors and methods, in arrow functions defined\nwithin class constructors and methods, or in functions that have an explicit\n<code>@this</code> declared in the immediately-enclosing function’s JSDoc.</p>\n\n<p>Never use <code>this</code> to refer to the global object, the context of an <code>eval</code>, the\ntarget of an event, or unnecessarily <code>call()</code>ed or <code>apply()</code>ed functions.</p>\n\n<h3 id=\"features-equality-checks\">5.10 Equality Checks</h3>\n\n<p>Use identity operators (<code>===</code>/<code>!==</code>) except in the cases documented below.</p>\n\n<h4 id=\"features-equality-checks-exceptions\">5.10.1 Exceptions Where Coercion is Desirable</h4>\n\n<p>Catching both <code>null</code> and <code>undefined</code> values:</p>\n\n<pre><code class=\"language-js prettyprint good\">if (someObjectOrPrimitive == null) {\n  // Checking for null catches both null and undefined for objects and\n  // primitives, but does not catch other falsy values like 0 or the empty\n  // string.\n}\n</code></pre>\n\n<h3 id=\"disallowed-features\">5.11 Disallowed features</h3>\n\n<h4 id=\"disallowed-features-with\">5.11.1 with</h4>\n\n<p>Do not use the <code>with</code> keyword. It makes your code harder to understand and has\nbeen banned in strict mode since ES5.</p>\n\n<h4 id=\"disallowed-features-dynamic-code-evaluation\">5.11.2 Dynamic code evaluation</h4>\n\n<p>Do not use <code>eval</code> or the <code>Function(...string)</code> constructor (except for code\nloaders). These features are potentially dangerous and simply do not work in CSP\nenvironments.</p>\n\n<h4 id=\"disallowed-features-automatic-semicolon-insertion\">5.11.3 Automatic semicolon insertion</h4>\n\n<p>Always terminate statements with semicolons (except function and class\ndeclarations, as noted above).</p>\n\n<h4 id=\"disallowed-features-non-standard-features\">5.11.4 Non-standard features</h4>\n\n<p>Do not use non-standard features. This includes old features that have been\nremoved (e.g., <code>WeakMap.clear</code>), new features that are not yet standardized\n(e.g., the current TC39 working draft, proposals at any stage, or proposed but\nnot-yet-complete web standards), or proprietary features that are only\nimplemented in some browsers. Use only features defined in the current ECMA-262\nor WHATWG standards. (Note that projects writing against specific APIs, such as\nChrome extensions or Node.js, can obviously use those APIs). Non-standard\nlanguage “extensions” (such as those provided by some external transpilers) are\nforbidden.</p>\n\n<h4 id=\"disallowed-features-wrapper-objects\">5.11.5 Wrapper objects for primitive types</h4>\n\n<p>Never use <code>new</code> on the primitive object wrappers (<code>Boolean</code>, <code>Number</code>, <code>String</code>,\n<code>Symbol</code>), nor include them in type annotations.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">const /** Boolean */ x = new Boolean(false);\nif (x) alert(typeof x);  // alerts 'object' - WAT?\n</code></pre>\n\n<p>The wrappers may be called as functions for coercing (which is preferred over\nusing <code>+</code> or concatenating the empty string) or creating symbols.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">const /** boolean */ x = Boolean(0);\nif (!x) alert(typeof x);  // alerts 'boolean', as expected\n</code></pre>\n\n<h4 id=\"disallowed-features-modifying-builtin-objects\">5.11.6 Modifying builtin objects</h4>\n\n<p>Never modify builtin types, either by adding methods to their constructors or to\ntheir prototypes. Avoid depending on libraries that do this. Note that the\nJSCompiler’s runtime library will provide standards-compliant polyfills where\npossible; nothing else may modify builtin objects.</p>\n\n<p>Do not add symbols to the global object unless absolutely necessary (e.g.\nrequired by a third-party API).</p>\n\n<h4 id=\"disallowed-features-omitting-parents-with-new\">5.11.7 Omitting <code>()</code> when invoking a constructor</h4>\n\n<p>Never invoke a constructor in a <code>new</code> statement without using parentheses <code>()</code>.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">new Foo;\n</code></pre>\n\n<p>Use instead:</p>\n\n<pre><code class=\"language-js prettyprint good\">new Foo();\n</code></pre>\n\n<p>Omitting parentheses can lead to subtle mistakes. These two lines are not\nequivalent:</p>\n\n<pre><code class=\"language-js prettyprint good\">new Foo().Bar();\nnew Foo.Bar();\n</code></pre>\n\n<h2 id=\"naming\">6 Naming</h2>\n\n<h3 id=\"naming-rules-common-to-all-identifiers\">6.1 Rules common to all identifiers</h3>\n\n<p>Identifiers use only ASCII letters and digits, and, in a small number of cases\nnoted below, underscores and very rarely (when required by frameworks like\nAngular) dollar signs.</p>\n\n<p>Give as descriptive a name as possible, within reason. Do not worry about saving\nhorizontal space as it is far more important to make your code immediately\nunderstandable by a new reader. Do not use abbreviations that are ambiguous or\nunfamiliar to readers outside your project, and do not abbreviate by deleting\nletters within a word.</p>\n\n<pre><code class=\"language-js prettyprint good\">errorCount          // No abbreviation.\ndnsConnectionIndex  // Most people know what \"DNS\" stands for.\nreferrerUrl         // Ditto for \"URL\".\ncustomerId          // \"Id\" is both ubiquitous and unlikely to be misunderstood.\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">n                   // Meaningless.\nnErr                // Ambiguous abbreviation.\nnCompConns          // Ambiguous abbreviation.\nwgcConnections      // Only your group knows what this stands for.\npcReader            // Lots of things can be abbreviated \"pc\".\ncstmrId             // Deletes internal letters.\nkSecondsPerDay      // Do not use Hungarian notation.\n</code></pre>\n\n<p><strong>Exception</strong>: Variables that are in scope for 10 lines or fewer, including\narguments that are <em>not</em> part of an exported API, <em>may</em> use short (e.g. single\nletter) variable names.</p>\n\n<h3 id=\"naming-rules-by-identifier-type\">6.2 Rules by identifier type</h3>\n\n<h4 id=\"naming-package-names\">6.2.1 Package names</h4>\n\n<p>Package names are all <code>lowerCamelCase</code>. For example, <code>my.exampleCode.deepSpace</code>,\nbut not <code class=\"badcode\">my.examplecode.deepspace</code> or\n<code class=\"badcode\">my.example_code.deep_space</code>.</p>\n\n<p><strong>Exception</strong>: The package name may conform to TypeScript's path-based pattern. This is\ntypically all lower case with underscores where present in filenames.</p>\n\n<h4 id=\"naming-class-names\">6.2.2 Class names</h4>\n\n<p>Class, interface, record, and typedef names are written in <code>UpperCamelCase</code>.\nUnexported classes are simply locals: they are not marked <code>@private</code>.</p>\n\n<p>Type names are typically nouns or noun phrases. For example, <code>Request</code>,\n<code>ImmutableView</code>, or <code>VisibilityMode</code>. Additionally, interface names may\nsometimes be adjectives or adjective phrases instead (for example, <code>Readable</code>).</p>\n\n<h4 id=\"naming-method-names\">6.2.3 Method names</h4>\n\n<p>Method names are written in <code>lowerCamelCase</code>. Names for <code>@private</code> methods may\noptionally end with a trailing underscore.</p>\n\n<p>Method names are typically verbs or verb phrases. For example, <code>sendMessage</code> or\n<code>stop_</code>. Getter and setter methods for properties are never required, but if\nthey are used they should be named <code>getFoo</code> (or optionally <code>isFoo</code> or <code>hasFoo</code>\nfor booleans), or <code>setFoo(value)</code> for setters.</p>\n\n<p>Underscores may also appear in JsUnit test method names to separate logical\ncomponents of the name. One typical pattern is\n<code>test&lt;MethodUnderTest&gt;_&lt;state&gt;_&lt;expectedOutcome&gt;</code>, for example\n<code>testPop_emptyStack_throws</code>. There is no One Correct Way to name test methods.</p>\n\n<h4 id=\"naming-enum-names\">6.2.4 Enum names</h4>\n\n<p>Enum names are written in <code>UpperCamelCase</code>, similar to classes, and should\ngenerally be singular nouns. Individual items within the enum are named in\n<code>CONSTANT_CASE</code>.</p>\n\n<h4 id=\"naming-constant-names\">6.2.5 Constant names</h4>\n\n<p>Constant names use <code>CONSTANT_CASE</code>: all uppercase letters, with words separated\nby underscores. There is no reason for a constant to be named with a trailing\nunderscore, since private static properties can be replaced by (implicitly\nprivate) module locals.</p>\n\n<h5 id=\"naming-definition-of-constant\">6.2.5.1 Definition of “constant”</h5>\n\n<p>Every constant is a <code>@const</code> static property or a module-local <code>const</code>\ndeclaration, but not all <code>@const</code> static properties and module-local <code>const</code>s\nare constants. Before choosing constant case, consider whether the field really\nfeels like a <em>deeply immutable</em> constant. For example, if any of that instance's\nobservable state can change, it is almost certainly not a constant. Merely\nintending to never mutate the object is generally not enough.</p>\n\n<p>Examples:</p>\n\n<pre><code class=\"language-js prettyprint good\">// Constants\nconst NUMBER = 5;\n/** @const */ exports.NAMES = goog.debug.freeze(['Ed', 'Ann']);\n/** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' };\n\n// Not constants\nlet letVariable = 'non-const';\n\nclass MyClass {\n  constructor() { /** @const {string} */ this.nonStatic = 'non-static'; }\n};\n/** @type {string} */\nMyClass.staticButMutable = 'not @const, can be reassigned';\n\nconst /** Set&lt;string&gt; */ mutableCollection = new Set();\n\nconst /** MyImmutableContainer&lt;SomeMutableType&gt; */ stillMutable =\n    new MyImmutableContainer(mutableInner);\n\nconst {Foo} = goog.require('my.foo');  // mirrors imported name\n\nconst logger = log.getLogger('loggers.are.not.immutable');\n</code></pre>\n\n<p>Constants’ names are typically nouns or noun phrases.</p>\n\n<h5 id=\"naming-local-aliases\">6.2.5.2 Local aliases</h5>\n\n<p>Local aliases should be used whenever they improve readability over\nfully-qualified names. Follow the same rules as <code>goog.require</code>s\n(<a href=\"#file-goog-require\">??</a>), maintaining the last part of the aliased name.\nAliases may also be used within functions. Aliases must be <code>const</code>.</p>\n\n<p>Examples:</p>\n\n<pre><code class=\"language-js prettyprint good\">const staticHelper = importedNamespace.staticHelper;\nconst CONSTANT_NAME = ImportedClass.CONSTANT_NAME;\nconst {assert, assertInstanceof} = asserts;\n</code></pre>\n\n<h4 id=\"naming-non-constant-field-names\">6.2.6 Non-constant field names</h4>\n\n<p>Non-constant field names (static or otherwise) are written in <code>lowerCamelCase</code>,\nwith an optional trailing underscore for private fields.</p>\n\n<p>These names are typically nouns or noun phrases. For example, <code>computedValues</code>\nor <code>index_</code>.</p>\n\n<h4 id=\"naming-parameter-names\">6.2.7 Parameter names</h4>\n\n<p>Parameter names are written in <code>lowerCamelCase</code>. Note that this applies even if\nthe parameter expects a constructor.</p>\n\n<p>One-character parameter names should not be used in public methods.</p>\n\n<p><strong>Exception</strong>: When required by a third-party framework, parameter names may\nbegin with a <code>$</code>. This exception does not apply to any other identifiers (e.g.\nlocal variables or properties).</p>\n\n<h4 id=\"naming-local-variable-names\">6.2.8 Local variable names</h4>\n\n<p>Local variable names are written in <code>lowerCamelCase</code>, except for module-local\n(top-level) constants, as described above. Constants in function scopes are\nstill named in <code>lowerCamelCase</code>. Note that <code>lowerCamelCase</code> is used\neven if the variable holds a constructor.</p>\n\n<h4 id=\"naming-template-parameter-names\">6.2.9 Template parameter names</h4>\n\n<p>Template parameter names should be concise, single-word or single-letter\nidentifiers, and must be all-caps, such as <code>TYPE</code> or <code>THIS</code>.</p>\n\n<h4 id=\"naming-module-local-names\">6.2.10 Module-local names</h4>\n\n<p>Module-local names that are not exported are implicitly private. They are not\nmarked <code>@private</code>. This applies to classes, functions, variables, constants,\nenums, and other module-local identifiers.</p>\n\n<h3 id=\"naming-camel-case-defined\">6.3 Camel case: defined</h3>\n\n<p>Sometimes there is more than one reasonable way to convert an English phrase\ninto camel case, such as when acronyms or unusual constructs like <q>IPv6</q> or\n<q>iOS</q> are present. To improve predictability, Google Style specifies the\nfollowing (nearly) deterministic scheme.</p>\n\n<p>Beginning with the prose form of the name:</p>\n\n<ol>\n<li>Convert the phrase to plain ASCII and remove any apostrophes. For example,\n<q>Müller's algorithm</q> might become <q>Muellers algorithm</q>.</li>\n<li>Divide this result into words, splitting on spaces and any remaining\npunctuation (typically hyphens).\n<ol>\n<li>Recommended: if any word already has a conventional camel case\nappearance in common usage, split this into its constituent parts (e.g.,\n<q>AdWords</q> becomes <q>ad words</q>). Note that a word such as <q>iOS</q> is not\nreally in camel case per se; it defies any convention, so this\nrecommendation does not apply.</li>\n</ol></li>\n<li>Now lowercase everything (including acronyms), then uppercase only the first\ncharacter of:\n<ol>\n<li>… each word, to yield <code>UpperCamelCase</code>, or</li>\n<li>… each word except the first, to yield <code>lowerCamelCase</code></li>\n</ol></li>\n<li>Finally, join all the words into a single identifier.</li>\n</ol>\n\n<p>Note that the casing of the original words is almost entirely disregarded.</p>\n\n<p>Examples of <code>lowerCamelCase</code>:</p>\n\n<table>\n<thead>\n<tr>\n<th style=\"text-align: center\">Prose form</th>\n<th style=\"text-align: center\">Correct</th>\n<th style=\"text-align: center\">Incorrect</th>\n</tr>\n</thead>\n\n<tbody>\n<tr>\n<td style=\"text-align: center\"><q>XML HTTP request</q></td>\n<td style=\"text-align: center\"><code>xmlHttpRequest</code></td>\n<td style=\"text-align: center\"><code>XMLHTTPRequest</code></td>\n</tr>\n<tr>\n<td style=\"text-align: center\"><q>new customer ID</q></td>\n<td style=\"text-align: center\"><code>newCustomerId</code></td>\n<td style=\"text-align: center\"><code>newCustomerID</code></td>\n</tr>\n<tr>\n<td style=\"text-align: center\"><q>inner stopwatch</q></td>\n<td style=\"text-align: center\"><code>innerStopwatch</code></td>\n<td style=\"text-align: center\"><code>innerStopWatch</code></td>\n</tr>\n<tr>\n<td style=\"text-align: center\"><q>supports IPv6 on iOS?</q></td>\n<td style=\"text-align: center\"><code>supportsIpv6OnIos</code></td>\n<td style=\"text-align: center\"><code>supportsIPv6OnIOS</code></td>\n</tr>\n<tr>\n<td style=\"text-align: center\"><q>YouTube importer</q></td>\n<td style=\"text-align: center\"><code>youTubeImporter</code></td>\n<td style=\"text-align: center\"><code>youtubeImporter</code>*</td>\n</tr>\n</tbody>\n</table>\n\n<p>*Acceptable, but not recommended.</p>\n\n<p>For examples of <code>UpperCamelCase</code>, uppercase the first letter of each correct\n<code>lowerCamelCase</code> example.</p>\n\n<p>Note: Some words are ambiguously hyphenated in the English language: for example\n<q>nonempty</q> and <q>non-empty</q> are both correct, so the method names <code>checkNonempty</code>\nand <code>checkNonEmpty</code> are likewise both correct.</p>\n\n<h2 id=\"jsdoc\">7 JSDoc</h2>\n\n<p><a href=\"https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler\">JSDoc</a> is used on all classes, fields, and methods.</p>\n\n<h3 id=\"jsdoc-general-form\">7.1 General form</h3>\n\n<p>The basic formatting of JSDoc blocks is as seen in this example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Multiple lines of JSDoc text are written here,\n * wrapped normally.\n * @param {number} arg A number to do something to.\n */\nfunction doSomething(arg) { … }\n</code></pre>\n\n<p>or in this single-line example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @const @private {!Foo} A short bit of JSDoc. */\nthis.foo_ = foo;\n</code></pre>\n\n<p>If a single-line comment overflows into multiple lines, it must use the\nmulti-line style with <code>/**</code> and <code>*/</code> on their own lines.</p>\n\n<p>Many tools extract metadata from JSDoc comments to perform code validation and\noptimization. As such, these comments <strong>must</strong> be well-formed.</p>\n\n<h3 id=\"jsdoc-markdown\">7.2 Markdown</h3>\n\n<p>JSDoc is written in Markdown, though it may include HTML when necessary.</p>\n\n<p>Note that tools that automatically extract JSDoc (e.g. <a href=\"https://github.com/jleyba/js-dossier\">JsDossier</a>) will often\nignore plain text formatting, so if you did this:</p>\n\n<pre><code class=\"language-js prettyprint bad\">/**\n * Computes weight based on three factors:\n *   items sent\n *   items received\n *   last timestamp\n */\n</code></pre>\n\n<p>it would come out like this:</p>\n\n<pre><code>Computes weight based on three factors: items sent items received last timestamp\n</code></pre>\n\n<p>Instead, write a Markdown list:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Computes weight based on three factors:\n *\n *  - items sent\n *  - items received\n *  - last timestamp\n */\n</code></pre>\n\n<h3 id=\"jsdoc-tags\">7.3 JSDoc tags</h3>\n\n<p>Google style allows a subset of JSDoc tags. See\n<a href=\"#appendices-jsdoc-tag-reference\">??</a> for the complete list. Most tags must\noccupy their own line, with the tag at the beginning of the line.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-js prettyprint bad\">/**\n * The \"param\" tag must occupy its own line and may not be combined.\n * @param {number} left @param {number} right\n */\nfunction add(left, right) { ... }\n</code></pre>\n\n<p>Simple tags that do not require any additional data (such as <code>@private</code>,\n<code>@const</code>, <code>@final</code>, <code>@export</code>) may be combined onto the same line, along with an\noptional type when appropriate.</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Place more complex annotations (like \"implements\" and \"template\")\n * on their own lines. Multiple simple tags (like \"export\" and \"final\")\n * may be combined in one line.\n * @export @final\n * @implements {Iterable&lt;TYPE&gt;}\n * @template TYPE\n */\nclass MyClass {\n  /**\n   * @param {!ObjType} obj Some object.\n   * @param {number=} num An optional number.\n   */\n  constructor(obj, num = 42) {\n    /** @private @const {!Array&lt;!ObjType|number&gt;} */\n    this.data_ = [obj, num];\n  }\n}\n</code></pre>\n\n<p>There is no hard rule for when to combine tags, or in which order, but be\nconsistent.</p>\n\n<p>For general information about annotating types in JavaScript see\n<a href=\"https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler\">Annotating JavaScript for the Closure Compiler</a> and\n<a href=\"https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System\">Types in the Closure Type System</a>.</p>\n\n<h3 id=\"jsdoc-line-wrapping\">7.4 Line wrapping</h3>\n\n<p>Line-wrapped block tags are indented four spaces. Wrapped description text may\nbe lined up with the description on previous lines, but this horizontal\nalignment is discouraged.</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Illustrates line wrapping for long param/return descriptions.\n * @param {string} foo This is a param with a description too long to fit in\n *     one line.\n * @return {number} This returns something that has a description too long to\n *     fit in one line.\n */\nexports.method = function(foo) {\n  return 5;\n};\n</code></pre>\n\n<p>Do not indent when wrapping a <code>@desc</code> or <code>@fileoverview</code> description.</p>\n\n<h3 id=\"jsdoc-top-file-level-comments\">7.5 Top/file-level comments</h3>\n\n<p>A file may have a top-level file overview. A copyright notice, author information,\nand default <a href=\"#jsdoc-visibility-annotations\">visibility level</a> are optional.\nFile overviews are generally recommended whenever a\nfile consists of more than a single class definition. The top level comment is\ndesigned to orient readers unfamiliar with the code to what is in this file. If\npresent, it may provide a description of the file's contents and any\ndependencies or compatibility information. Wrapped lines are not indented.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @fileoverview Description of file, its uses and information\n * about its dependencies.\n * @package\n */\n</code></pre>\n\n<h3 id=\"jsdoc-class-comments\">7.6 Class comments</h3>\n\n<p>Classes, interfaces and records must be documented with a description and any\ntemplate parameters, implemented interfaces, visibility, or other appropriate\ntags. The class description should provide the reader with enough information to\nknow how and when to use the class, as well as any additional considerations\nnecessary to correctly use the class. Textual descriptions may be omitted on the\nconstructor. When defining a class <code>@constructor</code> and <code>@extends</code> annotations are\nnot used with the <code>class</code> keyword unless it extends a generic class. When\ndefining an <code>@interface</code> or a <code>@record</code>, the <code>@extends</code> annotation is used when\ndefining a subclass and the <code>extends</code> keyword is never used.</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * A fancier event target that does cool things.\n * @implements {Iterable&lt;string&gt;}\n */\nclass MyFancyTarget extends EventTarget {\n  /**\n   * @param {string} arg1 An argument that makes this more interesting.\n   * @param {!Array&lt;number&gt;} arg2 List of numbers to be processed.\n   */\n  constructor(arg1, arg2) {\n    // ...\n  }\n};\n\n/**\n * Records are also helpful.\n * @extends {Iterator&lt;TYPE&gt;}\n * @record\n * @template TYPE\n */\nclass Listable {\n  /** @return {TYPE} The next item in line to be returned. */\n  next() {}\n}\n</code></pre>\n\n<h3 id=\"jsdoc-enum-and-typedef-comments\">7.7 Enum and typedef comments</h3>\n\n<p>All enums and typedefs must be documented with appropriate JSDoc tags\n(<code>@typedef</code> or <code>@enum</code>) on the preceding line. Public enums and typedefs must\nalso have a description. Individual enum items may be documented with a JSDoc\ncomment on the preceding line.</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * A useful type union, which is reused often.\n * @typedef {!FruitType|!FruitTypeEnum}\n */\nlet CoolUnionType;\n \n/**\n * Types of fruits.\n * @enum {string}\n */\nconst FruitTypeEnum = {\n  /** This kind is very sour. */\n  SOUR: 'sour',\n  /** The less-sour kind. */\n  SWEET: 'sweet',\n};\n</code></pre>\n\n<p>Typedefs are useful for defining short record types, or aliases for unions,\ncomplex functions, or generic types. Typedefs should be avoided for record types\nwith many fields, since they do not allow documenting individual fields, nor\nusing templates or recursive references. For large record types, prefer\n<code>@record</code>.</p>\n\n<h3 id=\"jsdoc-method-and-function-comments\">7.8 Method and function comments</h3>\n\n<p>In methods and named functions, parameter and return types must be documented,\neven in the case of same-signature <code>@override</code>s. The <code>this</code> type should be\ndocumented when necessary. Return type may be omitted if the function has no\nnon-empty <code>return</code> statements.</p>\n\n<p>Method, parameter, and return descriptions (but not types) may be omitted if\nthey are obvious from the rest of the method’s JSDoc or from its signature.</p>\n\n<p>Method descriptions begin with a verb phrase that describes what the method\ndoes. This phrase is not an imperative sentence, but instead is written in the\nthird person, as if there is an implied <q>This method ...</q> before it.</p>\n\n<p>If a method overrides a superclass method, it must include an <code>@override</code>\nannotation. For overridden methods, all <code>@param</code> and <code>@return</code> annotations must\nbe specified explicitly even if no type from the superclass method is refined.\nThis is to align with TypeScript.</p>\n\n<pre><code class=\"language-js prettyprint good\">/** A class that does something. */\nclass SomeClass extends SomeBaseClass {\n  /**\n   * Operates on an instance of MyClass and returns something.\n   * @param {!MyClass} obj An object that for some reason needs detailed\n   *     explanation that spans multiple lines.\n   * @param {!OtherClass} obviousOtherClass\n   * @return {boolean} Whether something occurred.\n   */\n  someMethod(obj, obviousOtherClass) { ... }\n\n  /**\n   * @param {string} param\n   * @return {string}\n   * @override\n   */\n  overriddenMethod(param) { ... }\n}\n\n/**\n * Demonstrates how top-level functions follow the same rules.  This one\n * makes an array.\n * @param {TYPE} arg\n * @return {!Array&lt;TYPE&gt;}\n * @template TYPE\n */\nfunction makeArray(arg) { ... }\n</code></pre>\n\n<p>If you only need to document the param and return types of a function, you may\noptionally use inline JSDocs in the function's signature. These inline JSDocs\nspecify the return and param types without tags.</p>\n\n<pre><code class=\"language-js prettyprint good\">function /** string */ foo(/** number */ arg) {...}\n</code></pre>\n\n<p>If you need descriptions or tags, use a single JSDoc comment above the method.\nFor example, methods which return values need a <code>@return</code> tag.</p>\n\n<pre><code class=\"language-js prettyprint good\">class MyClass {\n  /**\n   * @param {number} arg\n   * @return {string}\n   */\n  bar(arg) {...}\n}\n</code></pre>\n\n<pre><code class=\"language-js prettyprint bad\">// Illegal inline JSDocs.\n\nclass MyClass {\n  /** @return {string} */ foo() {...}\n}\n\n/** No function description allowed inline here. */ function bar() {...}\n\nfunction /** Function description is also illegal here. */ baz() {...}\n</code></pre>\n\n\n\n<p>In anonymous functions annotations are generally optional. If the automatic type\ninference is insufficient or explicit annotation improves readability, then\nannotate param and return types like this:</p>\n\n<pre><code class=\"language-js prettyprint good\">promise.then(\n    /** @return {string} */\n    (/** !Array&lt;string&gt; */ items) =&gt; {\n      doSomethingWith(items);\n      return items[0];\n    });\n</code></pre>\n\n<p>For function type expressions, see <a href=\"#jsdoc-function-types\">??</a>.</p>\n\n<h3 id=\"jsdoc-property-comments\">7.9 Property comments</h3>\n\n<p>Property types must be documented. The description may be omitted for private\nproperties, if name and type provide enough documentation for understanding the\ncode.</p>\n\n<p>Publicly exported constants are commented the same way as properties.</p>\n\n<pre><code class=\"language-js prettyprint good\">/** My class. */\nclass MyClass {\n  /** @param {string=} someString */\n  constructor(someString = 'default string') {\n    /** @private @const {string} */\n    this.someString_ = someString;\n\n    /** @private @const {!OtherType} */\n    this.someOtherThing_ = functionThatReturnsAThing();\n\n    /**\n     * Maximum number of things per pane.\n     * @type {number}\n     */\n    this.someProperty = 4;\n  }\n}\n\n/**\n * The number of times we'll try before giving up.\n * @const {number}\n */\nMyClass.RETRY_COUNT = 33;\n</code></pre>\n\n<h3 id=\"jsdoc-type-annotations\">7.10 Type annotations</h3>\n\n<p>Type annotations are found on <code>@param</code>, <code>@return</code>, <code>@this</code>, and <code>@type</code> tags,\nand optionally on <code>@const</code>, <code>@export</code>, and any visibility tags. Type annotations\nattached to JSDoc tags must always be enclosed in braces.</p>\n\n<h4 id=\"jsdoc-nullability\">7.10.1 Nullability</h4>\n\n<p>The type system defines modifiers <code>!</code> and <code>?</code> for non-null and nullable,\nrespectively. These modifiers must precede the type.</p>\n\n<p>Nullability modifiers have different requirements for different types, which\nfall into two broad categories:</p>\n\n<ol>\n<li>Type annotations for primitives (<code>string</code>, <code>number</code>, <code>boolean</code>, <code>symbol</code>,\n<code>undefined</code>, <code>null</code>) and literals (<code>{function(...): ...}</code> and <code>{{foo:\nstring...}}</code>) are always non-nullable by default. Use the <code>?</code> modifier to\nmake it nullable, but omit the redundant <code>!</code>.</li>\n<li>Reference types (generally, anything in <code>UpperCamelCase</code>, including\n<code>some.namespace.ReferenceType</code>) refer to a class, enum, record, or typedef\ndefined elsewhere. Since these types may or may not be nullable, it is\nimpossible to tell from the name alone whether it is nullable or not. Always\nuse explicit <code>?</code> and <code>!</code> modifiers for these types to prevent ambiguity at\nuse sites.</li>\n</ol>\n\n<p>Bad:</p>\n\n<pre><code class=\"language-js prettyprint bad\">const /** MyObject */ myObject = null; // Non-primitive types must be annotated.\nconst /** !number */ someNum = 5; // Primitives are non-nullable by default.\nconst /** number? */ someNullableNum = null; // ? should precede the type.\nconst /** !{foo: string, bar: number} */ record = ...; // Already non-nullable.\nconst /** MyTypeDef */ def = ...; // Not sure if MyTypeDef is nullable.\n\n// Not sure if object (nullable), enum (non-nullable, unless otherwise\n// specified), or typedef (depends on definition).\nconst /** SomeCamelCaseName */ n = ...;\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code class=\"language-js prettyprint good\">const /** ?MyObject */ myObject = null;\nconst /** number */ someNum = 5;\nconst /** ?number */ someNullableNum = null;\nconst /** {foo: string, bar: number} */ record = ...;\nconst /** !MyTypeDef */ def = ...;\nconst /** ?SomeCamelCaseName */ n = ...;\n</code></pre>\n\n<h4 id=\"jsdoc-type-casts\">7.10.2 Type Casts</h4>\n\n<p>In cases where the compiler doesn't accurately infer the type of an expression,\nand the assertion functions in\n<a href=\"https://google.github.io/closure-library/api/goog.asserts.html\">goog.asserts</a>\ncannot remedy it, it is\npossible to tighten the type by adding a type annotation comment and enclosing\nthe expression in parentheses. Note that the parentheses are required.</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @type {number} */ (x)\n</code></pre>\n\n<h4 id=\"jsdoc-template-parameter-types\">7.10.3 Template Parameter Types</h4>\n\n<p>Always specify template parameters. This way compiler can do a better job and it\nmakes it easier for readers to understand what code does.</p>\n\n<p>Bad:</p>\n\n<pre><code class=\"language-js prettyprint bad\">const /** !Object */ users = {};\nconst /** !Array */ books = [];\nconst /** !Promise */ response = ...;\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code class=\"language-js prettyprint good\">const /** !Object&lt;string, !User&gt; */ users = {};\nconst /** !Array&lt;string&gt; */ books = [];\nconst /** !Promise&lt;!Response&gt; */ response = ...;\n\nconst /** !Promise&lt;undefined&gt; */ thisPromiseReturnsNothingButParameterIsStillUseful = ...;\nconst /** !Object&lt;string, *&gt; */ mapOfEverything = {};\n</code></pre>\n\n<p>Cases when template parameters should not be used:</p>\n\n<ul>\n<li><code>Object</code> is used for type hierarchy and not as map-like structure.</li>\n</ul>\n\n<h4 id=\"jsdoc-function-types\">7.10.4 Function type expressions</h4>\n\n<p><strong>Terminology Note</strong>: <em>function type expression</em> refers to a type annotation for\nfunction types with the keyword <code>function</code> in the annotation (see examples\nbelow).</p>\n\n<p>Where the function definition is given, do not use a function type expression.\nSpecify parameter and return types with <code>@param</code> and <code>@return</code>, or with inline\nannotations (see <a href=\"#jsdoc-method-and-function-comments\">??</a>). This includes\nanonymous functions and functions defined and assigned to a const (where the\nfunction jsdoc appears above the whole assignment expression).</p>\n\n<p>Function type expressions are needed, for example, inside <code>@typedef</code>, <code>@param</code>\nor <code>@return</code>. Use it also for variables or properties of function type, if they\nare not immediately initialized with the function definition.</p>\n\n<pre><code class=\"language-js prettyprint good\">  /** @private {function(string): string} */\n  this.idGenerator_ = googFunctions.identity;\n</code></pre>\n\n<p>When using a function type expression, always specify the return type\nexplicitly. Otherwise the default return type is <q>unknown</q> (<code>?</code>), which leads to\nstrange and unexpected behavior, and is rarely what is actually desired.</p>\n\n<p>Bad - type error, but no warning given:</p>\n\n<pre><code class=\"language-js prettyprint bad\">/** @param {function()} generateNumber */\nfunction foo(generateNumber) {\n  const /** number */ x = generateNumber();  // No compile-time type error here.\n}\n\nfoo(() =&gt; 'clearly not a number');\n</code></pre>\n\n<p>Good:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @param {function(): *} inputFunction1 Can return any type.\n * @param {function(): undefined} inputFunction2 Definitely doesn't return\n *      anything.\n * NOTE: the return type of `foo` itself is safely implied to be {undefined}.\n */\nfunction foo(inputFunction1, inputFunction2) {...}\n</code></pre>\n\n<h4 id=\"jsdoc-whitespace\">7.10.5 Whitespace</h4>\n\n<p>Within a type annotation, a single space or line break is required after each\ncomma or colon. Additional line breaks may be inserted to improve readability or\navoid exceeding the column limit. These breaks should be chosen and indented\nfollowing the applicable guidelines (e.g. <a href=\"#formatting-line-wrapping\">??</a> and\n<a href=\"#formatting-block-indentation\">??</a>). No other whitespace is allowed in type\nannotations.</p>\n\n<p>Good:</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @type {function(string): number} */\n\n/** @type {{foo: number, bar: number}} */\n\n/** @type {number|string} */\n\n/** @type {!Object&lt;string, string&gt;} */\n\n/** @type {function(this: Object&lt;string, string&gt;, number): string} */\n\n/**\n * @type {function(\n *     !SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak,\n *     !OtherVeryLongTypedef): string}\n */\n\n/**\n * @type {!SuperDuperReallyReallyLongTypedefThatForcesTheLineBreak|\n *     !OtherVeryLongTypedef}\n */\n</code></pre>\n\n<p>Bad:</p>\n\n<pre><code class=\"language-js prettyprint bad\">// Only put a space after the colon\n/** @type {function(string) : number} */\n\n// Put spaces after colons and commas\n/** @type {{foo:number,bar:number}} */\n\n// No space in union types\n/** @type {number | string} */\n</code></pre>\n\n<h3 id=\"jsdoc-visibility-annotations\">7.11 Visibility annotations</h3>\n\n<p>Visibility annotations (<code>@private</code>, <code>@package</code>, <code>@protected</code>) may be specified\nin a <code>@fileoverview</code> block, or on any exported symbol or property. Do not\nspecify visibility for local variables, whether within a function or at the top\nlevel of a module. <code>@private</code> names may optionally end with an underscore.</p>\n\n<h2 id=\"policies\">8 Policies</h2>\n\n<h3 id=\"policies-be-consistent\">8.1 Issues unspecified by Google Style: Be Consistent!</h3>\n\n<p>For any style question that isn't settled definitively by this specification,\nprefer to do what the other code in the same file is already doing. If that\ndoesn't resolve the question, consider emulating the other files in the same\npackage.</p>\n\n<h3 id=\"policies-compiler-warnings\">8.2 Compiler warnings</h3>\n\n<h4 id=\"policies-use-a-standard-warning-set\">8.2.1 Use a standard warning set</h4>\n\n<p>As far as possible projects should use\n<code>--warning_level=VERBOSE</code>.</p>\n\n<h4 id=\"policies-how-to-handle-a-warning\">8.2.2 How to handle a warning</h4>\n\n<p>Before doing anything, make sure you understand exactly what the warning is\ntelling you. If you're not positive why a warning is appearing, ask for help\n.</p>\n\n<p>Once you understand the warning, attempt the following solutions in order:</p>\n\n<ol>\n<li><strong>First, fix it or work around it.</strong> Make a strong attempt to actually\naddress the warning, or find another way to accomplish the task that avoids\nthe situation entirely.</li>\n<li><strong>Otherwise, determine if it's a false alarm.</strong> If you are convinced that\nthe warning is invalid and that the code is actually safe and correct, add a\ncomment to convince the reader of this fact and apply the <code>@suppress</code>\nannotation.</li>\n<li><strong>Otherwise, leave a TODO comment.</strong> This is a <strong>last resort</strong>.\n If you do this, <strong>do\nnot suppress the warning.</strong> The warning should be visible until it can be\ntaken care of properly.</li>\n</ol>\n\n<h4 id=\"policies-suppress-a-warning-at-the-narrowest-reasonable-scope\">8.2.3 Suppress a warning at the narrowest reasonable scope</h4>\n\n<p>Warnings are suppressed at the narrowest reasonable scope, usually that of a\nsingle local variable or very small method. Often a variable or method is\nextracted for that reason alone.</p>\n\n<p>Example</p>\n\n<pre><code class=\"language-js prettyprint good\">/** @suppress {uselessCode} Unrecognized 'use asm' declaration */\nfunction fn() {\n  'use asm';\n  return 0;\n}\n</code></pre>\n\n<p>Even a large number of suppressions in a class is still better than blinding the\nentire class to this type of warning.</p>\n\n<h3 id=\"policies-deprecation\">8.3 Deprecation</h3>\n\n<p>Mark deprecated methods, classes or interfaces with <code>@deprecated</code> annotations. A\ndeprecation comment must include simple, clear directions for people to fix\ntheir call sites.</p>\n\n<h3 id=\"policies-code-not-in-google-style\">8.4 Code not in Google Style</h3>\n\n<p>You will occasionally encounter files in your codebase that are not in proper\nGoogle Style. These may have come from an acquisition, or may have been written\nbefore Google Style took a position on some issue, or may be in non-Google Style\nfor any other reason.</p>\n\n<h4 id=\"policies-reformatting-existing-code\">8.4.1 Reformatting existing code</h4>\n\n<p>When updating the style of existing code, follow these guidelines.</p>\n\n<ol>\n<li>It is not required to change all existing code to meet current style\nguidelines. Reformatting existing code is a trade-off between code churn and\nconsistency. Style rules evolve over time and these kinds of tweaks to\nmaintain compliance would create unnecessary churn. However, if significant\nchanges are being made to a file it is expected that the file will be in\nGoogle Style.</li>\n<li>Be careful not to allow opportunistic style fixes to muddle the focus of a\nCL. If you find yourself making a lot of style changes that aren’t critical\nto the central focus of a CL, promote those changes to a separate CL.</li>\n</ol>\n\n<h4 id=\"policies-newly-added-code-use-google-style\">8.4.2 Newly added code: use Google Style</h4>\n\n<p>Brand new files use Google Style, regardless of the style choices of other files\nin the same package.</p>\n\n<p>When adding new code to a file that is not in Google Style, reformatting the\nexisting code first is recommended, subject to the advice in\n<a href=\"#policies-reformatting-existing-code\">??</a>.</p>\n\n<p>If this reformatting is not done, then new code should be as consistent as\npossible with existing code in the same file, but must not violate the style\nguide.</p>\n\n<h3 id=\"policies-local-style-rules\">8.5 Local style rules</h3>\n\n<p>Teams and projects may adopt additional style rules beyond those in this\ndocument, but must accept that cleanup changes may not abide by these additional\nrules, and must not block such cleanup changes due to violating any additional\nrules. Beware of excessive rules which serve no purpose. The style guide does\nnot seek to define style in every possible scenario and neither should you.</p>\n\n<h3 id=\"policies-generated-code-mostly-exempt\">8.6 Generated code: mostly exempt</h3>\n\n<p>Source code generated by the build process is not required to be in Google\nStyle. However, any generated identifiers that will be referenced from\nhand-written source code must follow the naming requirements. As a special\nexception, such identifiers are allowed to contain underscores, which may help\nto avoid conflicts with hand-written identifiers.</p>\n\n<h2 id=\"appendices\">9 Appendices</h2>\n\n<h3 id=\"appendices-jsdoc-tag-reference\">9.1 JSDoc tag reference</h3>\n\n<p>JSDoc serves multiple purposes in JavaScript. In addition to being used to\ngenerate documentation it is also used to control tooling. The best known are\nthe Closure Compiler type annotations.</p>\n\n<h4 id=\"appendices-type-annotations\">9.1.1 Type annotations and other Closure Compiler annotations</h4>\n\n<p>Documentation for JSDoc used by the Closure Compiler is described in\n<a href=\"https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler\">Annotating JavaScript for the Closure Compiler</a> and\n<a href=\"https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System\">Types in the Closure Type System</a>.</p>\n\n<h4 id=\"appendices-documentation-annotations\">9.1.2 Documentation annotations</h4>\n\n<p>In addition to the JSDoc described in\n<a href=\"https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler\">Annotating JavaScript for the Closure Compiler</a> the following tags are common\nand well supported by various documentation generation tools (such as\n<a href=\"https://github.com/jleyba/js-dossier\">JsDossier</a>) for purely documentation purposes.</p>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.1 <code>@author</code> or <code>@owner</code> - <em>Not recommended.</em></h5>\n\n<p><strong>Not recommended.</strong></p>\n\n<p>Syntax: <code>@author username@google.com (First Last)</code></p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @fileoverview Utilities for handling textareas.\n * @author kuth@google.com (Uthur Pendragon)\n */\n</code></pre>\n\n<p>Documents the author of a file or the owner of a test, generally only used in\nthe <code>@fileoverview</code> comment. The <code>@owner</code> tag is used by the unit test dashboard\nto determine who owns the test results.</p>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.2 <code>@bug</code></h5>\n\n<p>Syntax: <code>@bug bugnumber</code></p>\n\n<pre><code class=\"language-js prettyprint good\">/** @bug 1234567 */\nfunction testSomething() {\n  // …\n}\n\n/**\n * @bug 1234568\n * @bug 1234569\n */\nfunction testTwoBugs() {\n  // …\n}\n</code></pre>\n\n<p>Indicates what bugs the given test function regression tests.</p>\n\n<p>Multiple bugs should each have their own <code>@bug</code> line, to make searching for\nregression tests as easy as possible.</p>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.3 <code>@code</code> - <em>Deprecated. Do not use.</em></h5>\n\n<p><strong>Deprecated. Do not use. Use Markdown backticks instead.</strong></p>\n\n<p>Syntax: <code>{@code ...}</code></p>\n\n<p>Historically, <code>`BatchItem`</code> was written as\n<code class=\"badcode\">{@code BatchItem}</code>.</p>\n\n<pre><code class=\"language-js prettyprint good\">/** Processes pending `BatchItem` instances. */\nfunction processBatchItems() {}\n</code></pre>\n\n<p>Indicates that a term in a JSDoc description is code so it may be correctly\nformatted in generated documentation.</p>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.4 <code>@desc</code></h5>\n\n<p>Syntax: <code>@desc Message description</code></p>\n\n<pre><code class=\"language-js prettyprint good\">/** @desc Notifying a user that their account has been created. */\nexports.MSG_ACCOUNT_CREATED = goog.getMsg(\n    'Your account has been successfully created.');\n</code></pre>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.5 <code>@link</code></h5>\n\n<p>Syntax: <code>{@link ...}</code></p>\n\n<p>This tag is used to generate cross-reference links within generated\ndocumentation.</p>\n\n<pre><code class=\"language-js prettyprint good\">/** Processes pending {@link BatchItem} instances. */\nfunction processBatchItems() {}\n</code></pre>\n\n<p><strong>Historical note:</strong> @link tags have also been used to create external links in\ngenerated documentation. For external links, always use Markdown's link syntax\ninstead:</p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * This class implements a useful subset of the\n * [native Event interface](https://dom.spec.whatwg.org/#event).\n */\nclass ApplicationEvent {}\n</code></pre>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.6 <code>@see</code></h5>\n\n<p>Syntax: <code>@see Link</code></p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * Adds a single item, recklessly.\n * @see #addSafely\n * @see goog.Collect\n * @see goog.RecklessAdder#add\n */\n</code></pre>\n\n<p>Reference a lookup to another class function or method.</p>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.2.7 <code>@supported</code></h5>\n\n<p>Syntax: <code>@supported Description</code></p>\n\n<pre><code class=\"language-js prettyprint good\">/**\n * @fileoverview Event Manager\n * Provides an abstracted interface to the browsers' event systems.\n * @supported IE10+, Chrome, Safari\n */\n</code></pre>\n\n<p>Used in a fileoverview to indicate what browsers are supported by the file.</p>\n\n</section>\n\n<p>You may also see other types of JSDoc annotations in third-party code. These\nannotations appear in the <a href=\"http://code.google.com/p/jsdoc-toolkit/wiki/TagReference\">JSDoc Toolkit Tag Reference</a> but are not considered\npart of valid Google style.</p>\n\n<h4 id=\"appendices-framework-specific-annotations\">9.1.3 Framework specific annotations</h4>\n\n<p>The following annotations are specific to a particular framework.</p>\n\n<section class=\"zippy\">\n\n<h5>9.1.3.1 <code>@ngInject</code> for Angular 1</h5>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.3.2 <code>@polymerBehavior</code> for Polymer</h5>\n\n\n\n<p><a href=\"https://github.com/google/closure-compiler/wiki/Polymer-Pass\">https://github.com/google/closure-compiler/wiki/Polymer-Pass</a>\n</p>\n\n</section>\n\n<section class=\"zippy\">\n\n</section>\n\n<h4 id=\"appendices-notes-about-standard-closure-compiler-annotations\">9.1.4 Notes about standard Closure Compiler annotations</h4>\n\n<p>The following tags used to be standard but are now deprecated.</p>\n\n<section class=\"zippy\">\n\n<h5>9.1.4.1 <code>@expose</code> - <em>Deprecated. Do not use.</em></h5>\n\n<p><strong>Deprecated. Do not use. Use <code>@export</code> and/or <code>@nocollapse</code> instead.</strong></p>\n\n</section>\n\n<section class=\"zippy\">\n\n<h5>9.1.4.2 <code>@inheritDoc</code> - <em>Deprecated. Do not use.</em></h5>\n\n<p><strong>Deprecated. Do not use. Use <code>@override</code> instead.</strong></p>\n\n</section>\n\n<h3 id=\"appendices-commonly-misunderstood-style-rules\">9.2 Commonly misunderstood style rules</h3>\n\n<p>Here is a collection of lesser-known or commonly misunderstood facts about\nGoogle Style for JavaScript. (The following are true statements; this is not a\nlist of <q>myths.</q>)</p>\n\n<ul>\n<li>Neither a copyright statement nor <code>@author</code> credit is required in a source\nfile. (Neither is explicitly recommended, either.)</li>\n<li>There is no <q>hard and fast</q> rule governing how to order the members of a\nclass (<a href=\"#features-classes\">??</a>).</li>\n<li>Empty blocks can usually be represented concisely as <code>{}</code>, as detailed in\n(<a href=\"#formatting-empty-blocks\">??</a>).</li>\n<li>The prime directive of line-wrapping is: prefer to break at a higher\nsyntactic level (<a href=\"#formatting-where-to-break\">??</a>).</li>\n<li>Non-ASCII characters are allowed in string literals, comments and JSDoc, and\nin fact are recommended when they make the code easier to read than the\nequivalent Unicode escape would (<a href=\"#non-ascii-characters\">??</a>).</li>\n</ul>\n\n<h3 id=\"appendices-style-related-tools\">9.3 Style-related tools</h3>\n\n<p>The following tools exist to support various aspects of Google Style.</p>\n\n<h4 id=\"appendices-tools-closure-compiler\">9.3.1 Closure Compiler</h4>\n\n<p>This program performs type checking and\nother checks, optimizations and other transformations (such as lowering code to\nECMAScript 5).</p>\n\n<h4 id=\"appendices-clang-format\">9.3.2 <code>clang-format</code></h4>\n\n<p>This program  reformats\nJavaScript source code into Google Style, and also follows a number of\nnon-required but frequently readability-enhancing formatting practices. The\noutput produced by <code>clang-format</code> is compliant with the style guide.\n</p>\n\n<p><code>clang-format</code> is not required. Authors are allowed to change its output, and\nreviewers are allowed to ask for such changes; disputes are worked out in the\nusual way. However, subtrees may choose to opt in to such enforcement locally.</p>\n\n<h4 id=\"appendices-closure-compiler-linter\">9.3.3 Closure compiler linter</h4>\n\n<p>This program  checks for a\nvariety of missteps and anti-patterns.</p>\n\n<h4 id=\"appendices-conformance-framework\">9.3.4 Conformance framework</h4>\n\n<p>The JS Conformance Framework is a tool that is part of the Closure Compiler that\nprovides developers a simple means to specify a set of additional checks to be\nrun against their code base above the standard checks. Conformance checks can,\nfor example, forbid access to a certain property, or calls to a certain\nfunction, or missing type information (unknowns).</p>\n\n<p>These rules are commonly used to enforce critical restrictions (such as defining\nglobals, which could break the codebase) and security patterns (such as using\n<code>eval</code> or assigning to <code>innerHTML</code>), or more loosely to improve code quality.</p>\n\n<p>For additional information see the official documentation for the\n<a href=\"https://github.com/google/closure-compiler/wiki/JS-Conformance-Framework\">JS Conformance Framework</a>.</p>\n\n<h3 id=\"appendices-legacy-exceptions\">9.4 Exceptions for legacy platforms</h3>\n\n<h4 id=\"appendices-legacy-exceptions-overview\">9.4.1 Overview</h4>\n\n<p>This section describes exceptions and additional rules to be followed when\nmodern ECMAScript syntax is not available to the code authors. Exceptions to the\nrecommended style are required when modern ECMAScript syntax is not possible and\nare outlined here:</p>\n\n<ul>\n<li>Use of <code>var</code> declarations is allowed</li>\n<li>Use of <code>arguments</code> is allowed</li>\n<li>Optional parameters without default values are allowed</li>\n</ul>\n\n<h4 id=\"appendices-legacy-exceptions-var\">9.4.2 Use <code>var</code></h4>\n\n<h5 id=\"appendices-legacy-exceptions-var-scope\">9.4.2.1 <code>var</code> declarations are NOT block-scoped</h5>\n\n<p><code>var</code> declarations are scoped to the beginning of the nearest enclosing\nfunction, script or module, which can cause unexpected behavior, especially with\nfunction closures that reference <code>var</code> declarations inside of loops. The\nfollowing code gives an example:</p>\n\n<pre><code class=\"language-js prettyprint bad\">for (var i = 0; i &lt; 3; ++i) {\n  var iteration = i;\n  setTimeout(function() { console.log(iteration); }, i*1000);\n}\n\n// logs 2, 2, 2 -- NOT 0, 1, 2\n// because `iteration` is function-scoped, not local to the loop.\n\n</code></pre>\n\n<h5 id=\"appendices-legacy-exceptions-var-declare\">9.4.2.2 Declare variables as close as possible to first use</h5>\n\n<p>Even though <code>var</code> declarations are scoped to the beginning of the enclosing\nfunction, <code>var</code> declarations should be as close as possible to their first use,\nfor readability purposes. However, do not put a <code>var</code> declaration inside a block\nif that variable is referenced outside the block. For example:</p>\n\n<pre><code class=\"language-js prettyprint good\">function sillyFunction() {\n  var count = 0;\n  for (var x in y) {\n    // \"count\" could be declared here, but don't do that.\n    count++;\n  }\n  console.log(count + ' items in y');\n}\n</code></pre>\n\n<h5 id=\"appendices-legacy-exceptions-var-const\">9.4.2.3 Use @const for constants variables</h5>\n\n<p>For global declarations where the <code>const</code> keyword would be used, if it were\navailable, annotate the <code>var</code> declaration with <code>@const</code> instead (this is\noptional for local variables).</p>\n\n<h4 id=\"appendices-legacy-exceptions-function\">9.4.3 Do not use block scoped functions declarations</h4>\n\n<p>Do <strong>not</strong> do this:</p>\n\n<pre><code class=\"language-js prettyprint bad\">if (x) {\n  function foo() {}\n}\n</code></pre>\n\n<p>While most JavaScript VMs implemented before ECMAScript 6 support function\ndeclarations within blocks it was not standardized. Implementations were\ninconsistent with each other and with the now-standard ECMAScript behavior for\nblock scoped function declaration. The ECMAScript 5 standard and prior only\nallow for function declarations in the root statement list of a script or\nfunction and explicitly ban them in block scopes in strict mode.</p>\n\n<p>To get consistent behavior, instead use a <code>var</code> initialized with a function\nexpression to define a function within a block:</p>\n\n<pre><code class=\"language-js prettyprint good\">if (x) {\n  var foo = function() {};\n}\n</code></pre>\n\n<h4 id=\"appendices-legacy-exceptions-goog-provide\">9.4.4 Dependency management with <code>goog.provide</code>/<code>goog.require</code></h4>\n\n<h5 id=\"appendices-legacy-exceptions-goog-provide-summary\">9.4.4.1 Summary</h5>\n\n<p><strong>WARNING: <code>goog.provide</code> dependency management is deprecated.</strong> All new files,\neven in projects using <code>goog.provide</code> for older files, should use\n<a href=\"#source-file-structure\"><code>goog.module</code></a>. The following rules are for\npre-existing <code>goog.provide</code> files only.</p>\n\n<ul>\n<li>Place all <code>goog.provide</code>s first, <code>goog.require</code>s second. Separate provides\nfrom requires with an empty line.</li>\n<li>Sort the entries alphabetically (uppercase first).</li>\n<li>Don't wrap <code>goog.provide</code> and <code>goog.require</code> statements. Exceed 80 columns\nif necessary.</li>\n<li>Only provide top-level symbols.</li>\n</ul>\n\n<p><code>goog.provide</code> statements should be grouped together and placed first. All\n<code>goog.require</code> statements should follow. The two lists should be separated with\nan empty line.</p>\n\n<p>Similar to import statements in other languages, <code>goog.provide</code> and\n<code>goog.require</code> statements should be written in a single line, even if they\nexceed the 80 column line length limit.</p>\n\n<p>The lines should be sorted alphabetically, with uppercase letters coming first:</p>\n\n<pre><code class=\"language-js prettyprint good\">goog.provide('namespace.MyClass');\ngoog.provide('namespace.helperFoo');\n\ngoog.require('an.extremelyLongNamespace.thatSomeoneThought.wouldBeNice.andNowItIsLonger.Than80Columns');\ngoog.require('goog.dom');\ngoog.require('goog.dom.TagName');\ngoog.require('goog.dom.classes');\ngoog.require('goog.dominoes');\n\n</code></pre>\n\n<p>All members defined on a class should be in the same file. Only top-level\nclasses should be provided in a file that contains multiple members defined on\nthe same class (e.g. enums, inner classes, etc).</p>\n\n<p>Do this:</p>\n\n<pre><code class=\"language-js prettyprint good\">goog.provide('namespace.MyClass');\n</code></pre>\n\n<p>Not this:</p>\n\n<pre><code class=\"language-js prettyprint bad\">goog.provide('namespace.MyClass');\ngoog.provide('namespace.MyClass.CONSTANT');\ngoog.provide('namespace.MyClass.Enum');\ngoog.provide('namespace.MyClass.InnerClass');\ngoog.provide('namespace.MyClass.TypeDef');\ngoog.provide('namespace.MyClass.staticMethod');\n</code></pre>\n\n<p>Members on namespaces may also be provided:</p>\n\n<pre><code class=\"language-js prettyprint good\">goog.provide('foo.bar');\ngoog.provide('foo.bar.CONSTANT');\ngoog.provide('foo.bar.method');\n</code></pre>\n\n<h5 id=\"appendices-legacy-exceptions-goog-scope\">9.4.4.2 Aliasing with <code>goog.scope</code></h5>\n\n<p><strong>WARNING: <code>goog.scope</code> is deprecated.</strong> New files should not use <code>goog.scope</code>\neven in projects with existing <code>goog.scope</code> usage.</p>\n\n<p><code>goog.scope</code> may be used to shorten references to namespaced symbols in code\nusing <code>goog.provide</code>/<code>goog.require</code> dependency management.</p>\n\n<p>Only one <code>goog.scope</code> invocation may be added per file. Always place it in the\nglobal scope.</p>\n\n<p>The opening <code>goog.scope(function() {</code> invocation must be preceded by exactly one\nblank line and follow any <code>goog.provide</code> statements, <code>goog.require</code> statements,\nor top-level comments. The invocation must be closed on the last line in the\nfile. Append <code>// goog.scope</code> to the closing statement of the scope. Separate the\ncomment from the semicolon by two spaces.</p>\n\n<p>Similar to C++ namespaces, do not indent under <code>goog.scope</code> declarations.\nInstead, continue from the 0 column.</p>\n\n<p>Only make aliases for names that will not be re-assigned to another object\n(e.g., most constructors, enums, and namespaces). Do not do this (see below for\nhow to alias a constructor):</p>\n\n<pre><code class=\"language-js prettyprint bad\">goog.scope(function() {\nvar Button = goog.ui.Button;\n\nButton = function() { ... };\n...\n</code></pre>\n\n<p>Names must be the same as the last property of the global that they are\naliasing.</p>\n\n<pre><code class=\"language-js prettyprint good\">goog.provide('my.module.SomeType');\n\ngoog.require('goog.dom');\ngoog.require('goog.ui.Button');\n\ngoog.scope(function() {\nvar Button = goog.ui.Button;\nvar dom = goog.dom;\n\n// Alias new types after the constructor declaration.\nmy.module.SomeType = function() { ... };\nvar SomeType = my.module.SomeType;\n\n// Declare methods on the prototype as usual:\nSomeType.prototype.findButton = function() {\n  // Button as aliased above.\n  this.button = new Button(dom.getElement('my-button'));\n};\n...\n});  // goog.scope\n</code></pre>\n\n<h5 id=\"appendices-legacy-exceptions-forward-declare\">9.4.4.3 <code>goog.forwardDeclare</code></h5>\n\n<p>Prefer to use <code>goog.requireType</code> instead of <code>goog.forwardDeclare</code> to break\ncircular dependencies between files in the same library. Unlike <code>goog.require</code>,\na <code>goog.requireType</code> statement is allowed to import a namespace before it is\ndefined.</p>\n\n<p><code>goog.forwardDeclare</code> statements must follow the same style rules as\n<code>goog.require</code> and <code>goog.requireType</code>. The entire block of\n<code>goog.forwardDeclare</code>, <code>goog.require</code> and <code>goog.requireType</code> statements is\nsorted alphabetically.</p>\n\n<p><code>goog.forwardDeclare</code> is used in legacy code to break circular references\nspanning <em>across library boundaries</em>. This pattern however is poorly supported\nby build tools and should not be used. Code should be organized to avoid\ncircular dependencies across libraries (by splitting/merging libraries).</p>\n\n<h5 id=\"appendices-legacy-exceptions-module-get\">9.4.4.4 <code>goog.module.get(name)</code></h5>\n\n<p>If a <code>goog.provide</code> file depends on a <code>goog.module</code> file, the <code>goog.provide</code>\nfile can not normally refer to the module's exports via a global name. Instead,\nin addition to <code>goog.require()</code>ing the module, the <code>goog.provide</code> file must\nfetch the module's export object by calling <code>goog.module.get('module.name')</code>.</p>\n\n<p>Note: Only calling <code>goog.module.get('module.name')</code> does not create a build-time\ndependency of your code on the module. The <code>goog.require</code> is needed for the\nbuild dependency.</p>\n\n<h5 id=\"appendices-legacy-exceptions-declareLegacyNamespace\">9.4.4.5 <code>goog.module.declareLegacyNamespace()</code></h5>\n\n<p><strong>WARNING: <code>goog.module.declareLegacyNamespace</code> is only for transitional use.</strong></p>\n\n<p><code>goog.module.declareLegacyNamespace</code> is only for use while migrating a\nJavaScript file and its consumers from <code>goog.provide</code> to <code>goog.module</code>\n. Update consumers of\nyour <a href=\"#source-file-structure\"><code>goog.module</code></a> to use <code>goog.module</code> themselves.\nRemove calls to <code>goog.module.declareLegacyNamespace</code> whenever possible.\n</p>\n\n<p>If you can't update consumers of a legacy namespace from <code>goog.provide</code> to\n<code>goog.module</code> soon, please wrap the contents of your file in a call to\n<code>goog.scope</code>, use <code>goog.module.get</code> to import the legacy namespace--and then\ndelete the call to <code>goog.module.declareLegacyNamespace</code> in your <code>goog.module</code>.</p>\n\n<p>Calling <code>goog.module.declareLegacyNamespace()</code> inside a <code>goog.module(name)</code> will\ndeclare the module's namespace as a global name just like a <code>goog.provide()</code>\ncall does. This allows a non <code>goog.module</code> namespace to access the module's\nexports without calling <code>goog.module.get(name)</code>.</p>\n\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "jsoncstyleguide.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <meta charset=\"utf8\">\n  <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">\n  <meta http-equiv=\"refresh\" content=\"1; url=jsoncstyleguide.xml\">\n  <title>Redirecting</title>\n</head>\n<!-- The BODY onLoad redirect is the best: it preserves #fragments and\n     ?queries.  But it requires javascript.  If that fails, the\n     meta-refresh kicks in; it works more generally, but loses fragments\n     and queries, takes a second, and pollutes the browser history.\n     If they both fail, we let the user manually click on the new link.\n-->\n <body onload=\"location.replace(location.href.replace('.html', '.xml'))\">\n  Redirecting you to <a href=\"jsoncstyleguide.xml\">jsoncstyleguide.xml</a>.\n</body>\n</html>\n"
  },
  {
    "path": "jsoncstyleguide.xml",
    "content": "<?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google JSON Style Guide\">\n\n<p align=\"right\">\nRevision 0.9\n</p>\n\n<address>\n</address>\n\n<OVERVIEW>\n<CATEGORY title=\"Important Note\">\n<STYLEPOINT title=\"Display Hidden Details in this Guide\">\n<SUMMARY>\nThis style guide contains many details that are initially hidden from view.  They are marked by the triangle icon, which you see here on your left.  Click it now.  You should see \"Hooray\" appear below.\n</SUMMARY>\n<BODY>\n<p>Hooray!  Now you know you can expand points to get more details.  Alternatively, there's an \"expand all\" at the top of this document.</p>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Introduction\">\n<p>This style guide documents guidelines and recommendations for building JSON APIs at Google.  In general, JSON APIs should follow the spec found at <a href=\"https://www.json.org\">JSON.org</a>.  This style guide clarifies and standardizes specific cases so that JSON APIs from Google have a standard look and feel.  These guidelines are applicable to JSON requests and responses in both RPC-based and REST-based APIs.</p>\n</CATEGORY>\n<CATEGORY title=\"Definitions\">\n<p>For the purposes of this style guide, we define the following terms:</p><ul><li><b>property</b> - a name/value pair inside a JSON object.</li><li><b>property name</b> - the name (or key) portion of the property.</li><li><b>property value</b> - the value portion of the property.</li></ul>\n<CODE_SNIPPET>\n{\n  // The name/value pair together is a \"property\".\n  \"propertyName\": \"propertyValue\"\n}\n\n</CODE_SNIPPET>\n<p>Javascript's <code>number</code> type encompasses all floating-point numbers, which is a broad designation.  In this guide, <code>number</code> will refer to JavaScript's <code>number</code> type, while <code>integer</code> will refer to integers.</p>\n</CATEGORY>\n</OVERVIEW>\n<CATEGORY title=\"General Guidelines\">\n<STYLEPOINT title=\"Comments\">\n<SUMMARY>\nNo comments in JSON objects.\n</SUMMARY>\n<BODY>\n<p>Comments should not be included in JSON objects.  Some of the examples in this style guide include comments.  However this is only to clarify the examples.</p>\n<BAD_CODE_SNIPPET>\n{\n  // You may see comments in the examples below,\n  // But don't include comments in your JSON.\n  \"propertyName\": \"propertyValue\"\n}\n\n</BAD_CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Double Quotes\">\n<SUMMARY>\nUse double quotes.\n</SUMMARY>\n<BODY>\n<p>If a property requires quotes, double quotes must be used.  All property names must be surrounded by double quotes.  Property values of type string must be surrounded by double quotes.  Other value types (like boolean or number) should not be surrounded by double quotes.</p>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Flattened data vs Structured Hierarchy\">\n<SUMMARY>\nData should not be arbitrarily grouped for convenience.\n</SUMMARY>\n<BODY>\n<p>Data elements should be \"flattened\" in the JSON representation.  Data should not be arbitrarily grouped for convenience.</p><p>In some cases, such as a collection of properties that represents a single structure, it may make sense to keep the structured hierarchy.  These cases should be carefully considered, and only used if it makes semantic sense.  For example, an address could be represented two ways, but the structured way probably makes more sense for developers:</p>\n<p>Flattened Address:</p>\n<CODE_SNIPPET>\n{\n  \"company\": \"Google\",\n  \"website\": \"https://www.google.com/\",\n  \"addressLine1\": \"111 8th Ave\",\n  \"addressLine2\": \"4th Floor\",\n  \"state\": \"NY\",\n  \"city\": \"New York\",\n  \"zip\": \"10011\"\n}\n</CODE_SNIPPET>\n<p>Structured Address:</p>\n<CODE_SNIPPET>\n{\n  \"company\": \"Google\",\n  \"website\": \"https://www.google.com/\",\n  \"address\": {\n    \"line1\": \"111 8th Ave\",\n    \"line2\": \"4th Floor\",\n    \"state\": \"NY\",\n    \"city\": \"New York\",\n    \"zip\": \"10011\"\n  }\n}\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Property Name Guidelines\">\n<STYLEPOINT title=\"Property Name Format\">\n<SUMMARY>\nChoose meaningful property names.\n</SUMMARY>\n<BODY>\n<p>Property names must conform to the following guidelines:</p><ul><li>Property names should be meaningful names with defined semantics.</li><li>Property names must be camel-cased, ascii strings.</li><li>The first character must be a letter, an underscore (_) or a dollar sign ($).</li><li>Subsequent characters can be a letter, a digit, an underscore, or a dollar sign.</li><li>Reserved JavaScript keywords should be avoided (A list of reserved JavaScript keywords can be found below).</li></ul><p>These guidelines mirror the guidelines for naming JavaScript identifiers.  This allows JavaScript clients to access properties using dot notation.  (for example, <code>result.thisIsAnInstanceVariable</code>).  Here's an example of an object with one property:</p>\n<CODE_SNIPPET>\n{\n  \"thisPropertyIsAnIdentifier\": \"identifier value\"\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Key Names in JSON Maps\">\n<SUMMARY>\nJSON maps can use any Unicode character in key names.\n</SUMMARY>\n<BODY>\n<p>The property name naming rules do not apply when a JSON object is used as a map.  A map (also referred to as an associative array) is a data type with arbitrary key/value pairs that use the keys to access the corresponding values.  JSON objects and JSON maps look the same at runtime; this distinction is relevant to the design of the API.  The API documentation should indicate when JSON objects are used as maps.</p><p>The keys of a map do not have to obey the naming guidelines for property names.  Map keys may contain any Unicode characters.  Clients can access these properties using the square bracket notation familiar for maps (for example, <code>result.thumbnails[\"72\"]</code>).</p>\n<CODE_SNIPPET>\n{\n  // The \"address\" property is a sub-object\n  // holding the parts of an address.\n  \"address\": {\n    \"addressLine1\": \"123 Anystreet\",\n    \"city\": \"Anytown\",\n    \"state\": \"XX\",\n    \"zip\": \"00000\"\n  },\n  // The \"thumbnails\" property is a map that maps\n  // a pixel size to the thumbnail url of that size.\n  \"thumbnails\": {\n    \"72\": \"https://url.to.72px.thumbnail\",\n    \"144\": \"https://url.to.144px.thumbnail\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Reserved Property Names\">\n<SUMMARY>\nCertain property names are reserved for consistent use across services.\n</SUMMARY>\n<BODY>\n<p>Details about reserved property names, along with the full list, can be found later on in this guide.  Services should avoid using these property names for anything other than their defined semantics.</p>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Singular vs Plural Property Names\">\n<SUMMARY>\nArray types should have plural property names.  All other property names should be singular.\n</SUMMARY>\n<BODY>\n<p>Arrays usually contain multiple items, and a plural property name reflects this.  An example of this can be seen in the reserved names below.  The <code>items</code> property name is plural because it represents an array of item objects.  Most of the other fields are singular.</p><p>There may be exceptions to this, especially when referring to numeric property values.  For example, in the reserved names, <code>totalItems</code> makes more sense than <code>totalItem</code>.  However, technically, this is not violating the style guide, since <code>totalItems</code> can be viewed as <code>totalOfItems</code>, where <code>total</code> is singular (as per the style guide), and <code>OfItems</code> serves to qualify the total.  The field name could also be changed to <code>itemCount</code> to look singular.</p>\n<CODE_SNIPPET>\n{\n  // Singular\n  \"author\": \"lisa\",\n  // An array of siblings, plural\n  \"siblings\": [ \"bart\", \"maggie\"],\n  // \"totalItem\" doesn't sound right\n  \"totalItems\": 10,\n  // But maybe \"itemCount\" is better\n  \"itemCount\": 10,\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Naming Conflicts\">\n<SUMMARY>\nAvoid naming conflicts by choosing a new property name or versioning the API.\n</SUMMARY>\n<BODY>\n<p>New properties may be added to the reserved list in the future.  There is no concept of JSON namespacing.  If there is a naming conflict, these can usually be resolved by choosing a new property name or by versioning.  For example, suppose we start with the following JSON object:</p>\n<CODE_SNIPPET>\n{\n  \"apiVersion\": \"1.0\",\n  \"data\": {\n    \"recipeName\": \"pizza\",\n    \"ingredients\": [\"tomatoes\", \"cheese\", \"sausage\"]\n  }\n}\n\n</CODE_SNIPPET>\n<p>If in the future we wish to make <code>ingredients</code> a reserved word, we can do one of two things:</p><p>1) Choose a different name:</p>\n<CODE_SNIPPET>\n{\n  \"apiVersion\": \"1.0\",\n  \"data\": {\n    \"recipeName\": \"pizza\",\n    \"ingredientsData\": \"Some new property\",\n    \"ingredients\": [\"tomatoes\", \"cheese\", \"sausage\"]\n  }\n}\n\n</CODE_SNIPPET>\n<p>2) Rename the property on a major version boundary:</p>\n<CODE_SNIPPET>\n{\n  \"apiVersion\": \"2.0\",\n  \"data\": {\n    \"recipeName\": \"pizza\",\n    \"ingredients\": \"Some new property\",\n    \"recipeIngredients\": [\"tomatos\", \"cheese\", \"sausage\"]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Property Value Guidelines\">\n<STYLEPOINT title=\"Property Value Format\">\n<SUMMARY>\nProperty values must be booleans, numbers, Unicode strings, objects, arrays, or <code>null</code>.\n</SUMMARY>\n<BODY>\n<p>The spec at <a href=\"https://www.json.org\">JSON.org</a> specifies exactly what type of data is allowed in a property value. This includes booleans, numbers, Unicode strings, objects, arrays, and <code>null</code>. JavaScript expressions are not allowed. APIs should support that spec for all values, and should choose the data type most appropriate for a particular property (numbers to represent numbers, etc.).</p><p>Good:</p>\n<CODE_SNIPPET>\n{\n  \"canPigsFly\": null,     // null\n  \"areWeThereYet\": false, // boolean\n  \"answerToLife\": 42,     // number\n  \"name\": \"Bart\",         // string\n  \"moreData\": {},         // object\n  \"things\": []            // array\n}\n\n</CODE_SNIPPET>\n<p>Bad:</p>\n<BAD_CODE_SNIPPET>\n{\n  \"aVariableName\": aVariableName,         // Bad - JavaScript identifier\n  \"functionFoo\": function() { return 1; } // Bad - JavaScript function\n}\n\n</BAD_CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Empty/Null Property Values\">\n<SUMMARY>\nConsider removing empty or <code>null</code> values.\n</SUMMARY>\n<BODY>\n<p>If a property is optional or has an empty or <code>null</code> value, consider dropping the property from the JSON, unless there's a strong semantic reason for its existence.</p>\n<CODE_SNIPPET>\n{\n  \"volume\": 10,\n\n  // Even though the \"balance\" property's value is zero, it should be left in,\n  // since \"0\" signifies \"even balance\" (the value could be \"-1\" for left\n  // balance and \"+1\" for right balance.\n  \"balance\": 0,\n\n  // The \"currentlyPlaying\" property can be left out since it is null.\n  // \"currentlyPlaying\": null\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Enum Values\">\n<SUMMARY>\nEnum values should be represented as strings.\n</SUMMARY>\n<BODY>\n<p>As APIs grow, enum values may be added, removed or changed. Using strings as enum values ensures that downstream clients can gracefully handle changes to enum values.</p><p>Java code:</p>\n<CODE_SNIPPET>\npublic enum Color {\n  WHITE,\n  BLACK,\n  RED,\n  YELLOW,\n  BLUE\n}\n\n</CODE_SNIPPET>\n<p>JSON object:</p>\n<CODE_SNIPPET>\n{\n  \"color\": \"WHITE\"\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Property Value Data Types\">\n<p>As mentioned above, property value types must be booleans, numbers, strings, objects, arrays, or <code>null</code>.  However, it is useful define a set of standard data types when dealing with certain values.  These data types will always be strings, but they will be formatted in a specific manner so that they can be easily parsed.</p>\n<STYLEPOINT title=\"Date Property Values\">\n<SUMMARY>\nDates should be formatted as recommended by RFC 3339.\n</SUMMARY>\n<BODY>\n<p>Dates should be strings formatted as recommended by <a href=\"https://www.ietf.org/rfc/rfc3339.txt\">RFC 3339</a></p>\n<CODE_SNIPPET>\n{\n  \"lastUpdate\": \"2007-11-06T16:34:41.000Z\"\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Time Duration Property Values\">\n<SUMMARY>\nTime durations should be formatted as recommended by ISO 8601.\n</SUMMARY>\n<BODY>\n<p>Time duration values should be strings formatted as recommended by <a href=\"https://en.wikipedia.org/wiki/ISO_8601#Durations\">ISO 8601</a>.</p>\n<CODE_SNIPPET>\n{\n  // three years, six months, four days, twelve hours,\n  // thirty minutes, and five seconds\n  \"duration\": \"P3Y6M4DT12H30M5S\"\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Latitude/Longitude Property Values\">\n<SUMMARY>\nLatitudes/Longitudes should be formatted as recommended by ISO 6709.\n</SUMMARY>\n<BODY>\n<p>Latitude/Longitude should be strings formatted as recommended by <a href=\"https://en.wikipedia.org/wiki/ISO_6709\">ISO 6709</a>.  Furthermore, they should favor the ±DD.DDDD±DDD.DDDD degrees format.</p>\n<CODE_SNIPPET>\n{\n  // The latitude/longitude location of the statue of liberty.\n  \"statueOfLiberty\": \"+40.6894-074.0447\"\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"JSON Structure &amp; Reserved Property Names\">\n<p>In order to maintain a consistent interface across APIs, JSON objects should follow the structure outlined below.  This structure applies to both requests and responses made with JSON.  Within this structure, there are certain property names that are reserved for specific uses.  These properties are NOT required; in other words, each reserved property may appear zero or one times.  But if a service needs these properties, this naming convention is recommended.  Here is a schema of the JSON structure, represented in <a href=\"https://www.google.com/url?sa=D&amp;q=http%3A%2F%2Forderly-json.org%2F\">Orderly</a> format (which in turn can be compiled into a <a href=\"https://www.google.com/url?sa=D&amp;q=http%3A%2F%2Fjson-schema.org%2F\">JSONSchema</a>).  You can few examples of the JSON structure at the end of this guide.</p>\n<CODE_SNIPPET>\nobject {\n  string apiVersion?;\n  string context?;\n  string id?;\n  string method?;\n  object {\n    string id?\n  }* params?;\n  object {\n    string kind?;\n    string fields?;\n    string etag?;\n    string id?;\n    string lang?;\n    string updated?; # date formatted RFC 3339\n    boolean deleted?;\n    integer currentItemCount?;\n    integer itemsPerPage?;\n    integer startIndex?;\n    integer totalItems?;\n    integer pageIndex?;\n    integer totalPages?;\n    string pageLinkTemplate /^https?:/ ?;\n    object {}* next?;\n    string nextLink?;\n    object {}* previous?;\n    string previousLink?;\n    object {}* self?;\n    string selfLink?;\n    object {}* edit?;\n    string editLink?;\n    array [\n      object {}*;\n    ] items?;\n  }* data?;\n  object {\n    integer code?;\n    string message?;\n    array [\n      object {\n        string domain?;\n        string reason?;\n        string message?;\n        string location?;\n        string locationType?;\n        string extendedHelp?;\n        string sendReport?;\n      }*;\n    ] errors?;\n  }* error?;\n}*;\n\n</CODE_SNIPPET>\n<p>The JSON object has a few top-level properties, followed by either a <code>data</code> object or an <code>error</code> object, but not both.  An explanation of each of these properties can be found below.</p>\n</CATEGORY>\n<CATEGORY title=\"Top-Level Reserved Property Names\">\n<p>The top-level of the JSON object may contain the following properties.</p>\n<STYLEPOINT title=\"apiVersion\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>Represents the desired version of the service API in a request, and the version of the service API that's served in the response.  <code>apiVersion</code> should always be present.  This is not related to the version of the data.  Versioning of data should be handled through some other mechanism such as etags.</p><p>Example:</p>\n<CODE_SNIPPET>\n{ \"apiVersion\": \"2.1\" }\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"context\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>Client sets this value and server echos data in the response.   This is useful in JSON-P and batch situations , where the user can use the <code>context</code> to correlate responses with requests.  This property is a top-level property because the <code>context</code> should present regardless of whether the response was successful or an error.  <code>context</code> differs from <code>id</code> in that <code>context</code> is specified by the user while <code>id</code> is assigned by the service.</p><p>Example:</p><p>Request #1:</p>\n<CODE_SNIPPET>\nhttps://www.google.com/myapi?context=bart\n\n</CODE_SNIPPET>\n<p>Request #2:</p>\n<CODE_SNIPPET>\nhttps://www.google.com/myapi?context=lisa\n\n</CODE_SNIPPET>\n<p>Response #1:</p>\n<CODE_SNIPPET>\n{\n  \"context\": \"bart\",\n  \"data\": {\n    \"items\": []\n  }\n}\n\n</CODE_SNIPPET>\n<p>Response #2:</p>\n<CODE_SNIPPET>\n{\n  \"context\": \"lisa\",\n  \"data\": {\n    \"items\": []\n  }\n}\n\n</CODE_SNIPPET>\n<p>Common JavaScript handler code to process both responses:</p>\n<CODE_SNIPPET>\nfunction handleResponse(response) {\n  if (response.result.context == \"bart\") {\n    // Update the \"Bart\" section of the page.\n  } else if (response.result.context == \"lisa\") {\n    // Update the \"Lisa\" section of the page.\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"id\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>A server supplied identifier for the response (regardless of whether the response is a success or an error).  This is useful for correlating server logs with individual responses received at a client.</p><p>Example:</p>\n<CODE_SNIPPET>\n{ \"id\": \"1\" }\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"method\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>Represents the operation to perform, or that was performed, on the data.  In the case of a JSON request, the <code>method</code> property can be used to indicate which operation to perform on the data.  In the case of a JSON response, the <code>method</code> property can indicate the operation performed on the data.</p><p>One example of this is in JSON-RPC requests, where <code>method</code> indicates the operation to perform on the <code>params</code> property:</p>\n<CODE_SNIPPET>\n{\n  \"method\": \"people.get\",\n  \"params\": {\n    \"userId\": \"@me\",\n    \"groupId\": \"@self\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"params\">\n<SUMMARY>\nProperty Value Type: object<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>This object serves as a map of input parameters to send to an RPC request.  It can be used in conjunction with the <code>method</code> property to execute an RPC function.  If an RPC function does not need parameters, this property can be omitted.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"method\": \"people.get\",\n  \"params\": {\n    \"userId\": \"@me\",\n    \"groupId\": \"@self\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data\">\n<SUMMARY>\nProperty Value Type: object<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>Container for all the data from a response.  This property itself has many reserved property names, which are described below.  Services are free to add their own data to this object.  A JSON response should contain either a <code>data</code> object or an <code>error</code> object, but not both.  If both <code>data</code> and <code>error</code> are present, the <code>error</code> object takes precedence.</p>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error\">\n<SUMMARY>\nProperty Value Type: object<br />Parent: -\n</SUMMARY>\n<BODY>\n<p>Indicates that an error has occurred, with details about the error.  The error format supports either one or more errors returned from the service.  A JSON response should contain either a <code>data</code> object or an <code>error</code> object, but not both.  If both <code>data</code> and <code>error</code> are present, the <code>error</code> object takes precedence.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"apiVersion\": \"2.0\",\n  \"error\": {\n    \"code\": 404,\n    \"message\": \"File Not Found\",\n    \"errors\": [{\n      \"domain\": \"Calendar\",\n      \"reason\": \"ResourceNotFoundException\",\n      \"message\": \"File Not Found\"\n    }]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Reserved Property Names in the data object\">\n<p>The <code>data</code> property of the JSON object may contain the following properties.</p>\n<STYLEPOINT title=\"data.kind\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The <code>kind</code> property serves as a guide to what type of information this particular object stores.  It can be present at the <code>data</code> level, or at the <code>items</code> level, or in any object where its helpful to distinguish between various types of objects.  If the <code>kind</code> object is present, it should be the first property in the object (See the \"Property Ordering\" section below for more details).</p><p>Example:</p>\n<CODE_SNIPPET>\n// \"Kind\" indicates an \"album\" in the Picasa API.\n{\"data\": {\"kind\": \"album\"}}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.fields\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>Represents the fields present in the response when doing a partial GET, or the fields present in a request when doing a partial PATCH.  This property should only exist during a partial GET/PATCH, and should not be empty.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"kind\": \"user\",\n    \"fields\": \"author,id\",\n    \"id\": \"bart\",\n    \"author\": \"Bart\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.etag\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>Represents the etag for the response.  Details about ETags in the GData APIs can be found here: <a href=\"https://code.google.com/apis/gdata/docs/2.0/reference.html#ResourceVersioning\">https://code.google.com/apis/gdata/docs/2.0/reference.html#ResourceVersioning</a></p><p>Example:</p>\n<CODE_SNIPPET>\n{\"data\": {\"etag\": \"W/\"C0QBRXcycSp7ImA9WxRVFUk.\"\"}}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.id\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>A globally unique string used to reference the object.  The specific details of the <code>id</code> property are left up to the service.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\"data\": {\"id\": \"12345\"}}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.lang\">\n<SUMMARY>\nProperty Value Type: string (formatted as specified in BCP 47)<br />Parent: <code>data (or any child element)</code>\n</SUMMARY>\n<BODY>\n<p>Indicates the language of the rest of the properties in this object.  This property mimics HTML's <code>lang</code> property and XML's <code>xml:lang</code> properties.  The value should be a language value as defined in <a href=\"https://www.rfc-editor.org/rfc/bcp/bcp47.txt\">BCP 47</a>.  If a single JSON object contains data in multiple languages, the service is responsible for developing and documenting an appropriate location for the <code>lang</code> property.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\"data\": {\n  \"items\": [\n    { \"lang\": \"en\",\n      \"title\": \"Hello world!\" },\n    { \"lang\": \"fr\",\n      \"title\": \"Bonjour monde!\" }\n  ]}\n}\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.updated\">\n<SUMMARY>\nProperty Value Type: string (formatted as specified in RFC 3339)<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>Indicates the last date/time (<a href=\"https://www.ietf.org/rfc/rfc3339.txt\">RFC 3339</a>) the item was updated, as defined by the service.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\"data\": {\"updated\": \"2007-11-06T16:34:41.000Z\"}}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.deleted\">\n<SUMMARY>\nProperty Value Type: boolean<br />Parent: <code>data (or any child element)</code>\n</SUMMARY>\n<BODY>\n<p>A marker element, that, when present, indicates the containing entry is deleted.  If deleted is present, its value must be <code>true</code>; a value of <code>false</code> can cause confusion and should be avoided.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\"data\": {\n  \"items\": [\n    { \"title\": \"A deleted entry\",\n      \"deleted\": true\n    }\n  ]}\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.items\">\n<SUMMARY>\nProperty Value Type: array<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The property name <code>items</code> is reserved to represent an array of items (for example, photos in Picasa, videos in YouTube).  This construct is intended to provide a standard location for collections related to the current result.  For example, the JSON output could be plugged into a generic pagination system that knows to page on the <code>items</code> array.  If <code>items</code> exists, it should be the last property in the <code>data</code> object (See the \"Property Ordering\" section below for more details).</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"items\": [\n      { /* Object #1 */ },\n      { /* Object #2 */ },\n      ...\n    ]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Reserved Property Names for Paging\">\n<p>The following properties are located in the <code>data</code> object, and help page through a list of items.  Some of the language and concepts are borrowed from the <a href=\"https://www.opensearch.org/\">OpenSearch specification</a>.</p><p>The paging properties below allow for various styles of paging, including:</p><ul><li>Previous/Next paging - Allows user's to move forward and backward through a list, one page at a time.  The <code>nextLink</code> and <code>previousLink</code> properties (described in the \"Reserved Property Names for Links\" section below) are used for this style of paging.</li><li>Index-based paging - Allows user's to jump directly to a specific item position within a list of items.  For example, to load 10 items starting at item 200, the developer may point the user to a url with the query string <code>?startIndex=200</code>.</li><li>Page-based paging - Allows user's to jump directly to a specific page within the items.  This is similar to index-based paging, but saves the developer the extra step of having to calculate the item index for a new page of items.  For example, rather than jump to item number 200, the developer could jump to page 20.  The urls during page-based paging could use the query string <code>?page=1</code> or <code>?page=20</code>.  The <code>pageIndex</code> and <code>totalPages</code> properties are used for this style of paging.</li></ul><p>An example of how to use these properties to implement paging can be found at the end of this guide.</p>\n<STYLEPOINT title=\"data.currentItemCount\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The number of items in this result set.  Should be equivalent to items.length, and is provided as a convenience property.  For example, suppose a developer requests a set of search items, and asks for 10 items per page.  The total set of that search has 14 total items.  The first page of items will have 10 items in it, so both <code>itemsPerPage</code> and <code>currentItemCount</code> will equal \"10\".  The next page of items will have the remaining 4 items; <code>itemsPerPage</code> will still be \"10\", but <code>currentItemCount</code> will be \"4\".</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    // \"itemsPerPage\" does not necessarily match \"currentItemCount\"\n    \"itemsPerPage\": 10,\n    \"currentItemCount\": 4\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.itemsPerPage\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The number of items in the result.  This is not necessarily the size of the data.items array; if we are viewing the last page of items, the size of data.items may be less than <code>itemsPerPage</code>.  However the size of data.items should not exceed <code>itemsPerPage</code>.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"itemsPerPage\": 10\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.startIndex\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The index of the first item in data.items.  For consistency, <code>startIndex</code> should be 1-based.  For example, the first item in the first set of items should have a <code>startIndex</code> of 1.  If the user requests the next set of data, the <code>startIndex</code> may be 10.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"startIndex\": 1\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.totalItems\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The total number of items available in this set.  For example, if a user has 100 blog posts, the response may only contain 10 items, but the <code>totalItems</code> would be 100.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"totalItems\": 100\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.pagingLinkTemplate\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>A URI template indicating how users can calculate subsequent paging links.  The URI template also has some reserved variable names: <code>{index}</code> representing the item number to load, and <code>{pageIndex}</code>, representing the page number to load.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"pagingLinkTemplate\": \"https://www.google.com/search/hl=en&amp;q=chicago+style+pizza&amp;start={index}&amp;sa=N\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.pageIndex\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The index of the current page of items.  For consistency, <code>pageIndex</code> should be 1-based.  For example, the first page of items has a <code>pageIndex</code> of 1.  <code>pageIndex</code> can also be calculated from the item-based paging properties: <code>pageIndex = floor(startIndex / itemsPerPage) + 1</code>.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"pageIndex\": 1\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.totalPages\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The total number of pages in the result set.  <code>totalPages</code> can also be calculated from the item-based paging properties above: <code>totalPages = ceiling(totalItems / itemsPerPage)</code>.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"totalPages\": 50\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Reserved Property Names for Links\">\n<p>The following properties are located in the <code>data</code> object, and represent references to other resources.  There are two forms of link properties: 1) objects, which can contain any sort of reference (such as a JSON-RPC object), and 2) URI strings, which represent URIs to resources (and will always be suffixed with \"Link\").</p>\n<STYLEPOINT title=\"data.self / data.selfLink\">\n<SUMMARY>\nProperty Value Type: object / string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The self link can be used to retrieve the item's data.  For example, in a list of a user's Picasa album, each album object in the <code>items</code> array could contain a <code>selfLink</code> that can be used to retrieve data related to that particular album.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"self\": { },\n    \"selfLink\": \"https://www.google.com/feeds/album/1234\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.edit / data.editLink\">\n<SUMMARY>\nProperty Value Type: object / string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The edit link indicates where a user can send update or delete requests.  This is useful for REST-based APIs.  This link need only be present if the user can update/delete this item.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"edit\": { },\n    \"editLink\": \"https://www.google.com/feeds/album/1234/edit\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.next / data.nextLink\">\n<SUMMARY>\nProperty Value Type: object / string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The next link indicates how more data can be retrieved.  It points to the location to load the next set of data.  It can be used in conjunction with the <code>itemsPerPage</code>, <code>startIndex</code> and <code>totalItems</code> properties in order to page through data.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"next\": { },\n    \"nextLink\": \"https://www.google.com/feeds/album/1234/next\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"data.previous / data.previousLink\">\n<SUMMARY>\nProperty Value Type: object / string<br />Parent: <code>data</code>\n</SUMMARY>\n<BODY>\n<p>The previous link indicates how more data can be retrieved.  It points to the location to load the previous set of data.  It can be used in conjunction with the <code>itemsPerPage</code>, <code>startIndex</code> and <code>totalItems</code> properties in order to page through data.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"data\": {\n    \"previous\": { },\n    \"previousLink\": \"https://www.google.com/feeds/album/1234/next\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Reserved Property Names in the error object\">\n<p>The <code>error</code> property of the JSON object may contain the following properties.</p>\n<STYLEPOINT title=\"error.code\">\n<SUMMARY>\nProperty Value Type: integer<br />Parent: <code>error</code>\n</SUMMARY>\n<BODY>\n<p>Represents the code for this error.  This property value will usually represent the HTTP response code.  If there are multiple errors, <code>code</code> will be the error code for the first error.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"code\": 404\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.message\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error</code>\n</SUMMARY>\n<BODY>\n<p>A human readable message providing more details about the error.  If there are multiple errors, <code>message</code> will be the message for the first error.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"message\": \"File Not Found\"\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors\">\n<SUMMARY>\nProperty Value Type: array<br />Parent: <code>error</code>\n</SUMMARY>\n<BODY>\n<p>Container for any additional information regarding the error.  If the service returns multiple errors, each element in the <code>errors</code> array represents a different error.</p><p>Example:</p>\n<CODE_SNIPPET>\n{ \"error\": { \"errors\": [] } }\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].domain\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>Unique identifier for the service raising this error.  This helps distinguish service-specific errors (i.e. error inserting an event in a calendar) from general protocol errors (i.e. file not found).</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"errors\": [{\"domain\": \"Calendar\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].reason\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>Unique identifier for this error.  Different from the <code>error.code</code> property in that this is not an http response code.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"errors\": [{\"reason\": \"ResourceNotFoundException\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].message\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>A human readable message providing more details about the error.  If there is only one error, this field will match <code>error.message</code>.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"code\": 404,\n    \"message\": \"File Not Found\",\n    \"errors\": [{\"message\": \"File Not Found\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].location\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>The location of the error (the interpretation of its value depends on <code>locationType</code>).</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"errors\": [{\"location\": \"\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].locationType\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>Indicates how the <code>location</code> property should be interpreted.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"errors\": [{\"locationType\": \"\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].extendedHelp\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>A URI for a help text that might shed some more light on the error.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"errors\": [{\"extendedHelper\": \"https://url.to.more.details.example.com/\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"error.errors[].sendReport\">\n<SUMMARY>\nProperty Value Type: string<br />Parent: <code>error.errors</code>\n</SUMMARY>\n<BODY>\n<p>A URI for a report form used by the service to collect data about the error condition. This URI should be preloaded with parameters describing the request.</p><p>Example:</p>\n<CODE_SNIPPET>\n{\n  \"error\":{\n    \"errors\": [{\"sendReport\": \"https://report.example.com/\"}]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Property Ordering\">\n<p>Properties can be in any order within the JSON object.  However, in some cases the ordering of properties can help parsers quickly interpret data and lead to better performance.  One example is a pull parser in a mobile environment, where performance and memory are critical, and unnecessary parsing should be avoided.</p>\n<STYLEPOINT title=\"Kind Property\">\n<SUMMARY>\n<code>kind</code> should be the first property\n</SUMMARY>\n<BODY>\n<p>Suppose a parser is responsible for parsing a raw JSON stream into a specific object.  The <code>kind</code> property guides the parser to instantiate the appropriate object.  Therefore it should be the first property in the JSON object.  This only applies when objects have a <code>kind</code> property (usually found in the <code>data</code> and <code>items</code> properties).</p>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Items Property\">\n<SUMMARY>\n<code>items</code> should be the last property in the <code>data</code> object\n</SUMMARY>\n<BODY>\n<p>This allows all of the collection's properties to be read before reading each individual item.  In cases where there are a lot of items, this avoids unnecessarily parsing those items when the developer only needs fields from the data.</p>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Property Ordering Example\">\n<BODY>\n<CODE_SNIPPET>\n// The \"kind\" property distinguishes between an \"album\" and a \"photo\".\n// \"Kind\" is always the first property in its parent object.\n// The \"items\" property is the last property in the \"data\" object.\n{\n  \"data\": {\n    \"kind\": \"album\",\n    \"title\": \"My Photo Album\",\n    \"description\": \"An album in the user's account\",\n    \"items\": [\n      {\n        \"kind\": \"photo\",\n        \"title\": \"My First Photo\"\n      }\n    ]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Examples\">\n<STYLEPOINT title=\"YouTube JSON API\">\n<SUMMARY>\nHere's an example of the YouTube JSON API's response object.  You can learn more about YouTube's JSON API here: <a href=\"https://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html\">https://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html</a>.\n</SUMMARY>\n<BODY>\n<CODE_SNIPPET>\n{\n  \"apiVersion\": \"2.0\",\n  \"data\": {\n    \"updated\": \"2010-02-04T19:29:54.001Z\",\n    \"totalItems\": 6741,\n    \"startIndex\": 1,\n    \"itemsPerPage\": 1,\n    \"items\": [\n      {\n        \"id\": \"BGODurRfVv4\",\n        \"uploaded\": \"2009-11-17T20:10:06.000Z\",\n        \"updated\": \"2010-02-04T06:25:57.000Z\",\n        \"uploader\": \"docchat\",\n        \"category\": \"Animals\",\n        \"title\": \"From service dog to SURFice dog\",\n        \"description\": \"Surf dog Ricochets inspirational video ...\",\n        \"tags\": [\n          \"Surf dog\",\n          \"dog surfing\",\n          \"dog\",\n          \"golden retriever\",\n        ],\n        \"thumbnail\": {\n          \"default\": \"https://i.ytimg.com/vi/BGODurRfVv4/default.jpg\",\n          \"hqDefault\": \"https://i.ytimg.com/vi/BGODurRfVv4/hqdefault.jpg\"\n        },\n        \"player\": {\n          \"default\": \"https://www.youtube.com/watch?v=BGODurRfVv4&amp;feature=youtube_gdata\",\n          \"mobile\": \"https://m.youtube.com/details?v=BGODurRfVv4\"\n        },\n        \"content\": {\n          \"1\": \"rtsp://v5.cache6.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp\",\n          \"5\": \"https://www.youtube.com/v/BGODurRfVv4?f=videos&amp;app=youtube_gdata\",\n          \"6\": \"rtsp://v7.cache7.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp\"\n        },\n        \"duration\": 315,\n        \"rating\": 4.96,\n        \"ratingCount\": 2043,\n        \"viewCount\": 1781691,\n        \"favoriteCount\": 3363,\n        \"commentCount\": 1007,\n        \"commentsAllowed\": true\n      }\n    ]\n  }\n}\n\n</CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n<STYLEPOINT title=\"Paging Example\">\n<SUMMARY>\nThis example demonstrates how the Google search items could be represented as a JSON object, with special attention to the paging variables.\n</SUMMARY>\n<BODY>\n<p>This sample is for illustrative purposes only.  The API below does not actually exist.</p><p>Here's a sample Google search results page:<br /><img src=\"jsoncstyleguide_example_01.png\" /><br /><img src=\"jsoncstyleguide_example_02.png\" /></p><p>Here's a sample JSON representation of this page:</p>\n<CODE_SNIPPET>\n{\n  \"apiVersion\": \"2.1\",\n  \"id\": \"1\",\n  \"data\": {\n    \"query\": \"chicago style pizza\",\n    \"time\": \"0.1\",\n    \"currentItemCount\": 10,\n    \"itemsPerPage\": 10,\n    \"startIndex\": 11,\n    \"totalItems\": 2700000,\n    \"nextLink\": \"https://www.google.com/search?hl=en&amp;q=chicago+style+pizza&amp;start=20&amp;sa=N\"\n    \"previousLink\": \"https://www.google.com/search?hl=en&amp;q=chicago+style+pizza&amp;start=0&amp;sa=N\",\n    \"pagingLinkTemplate\": \"https://www.google.com/search/hl=en&amp;q=chicago+style+pizza&amp;start={index}&amp;sa=N\",\n    \"items\": [\n      {\n        \"title\": \"Pizz'a Chicago Home Page\"\n        // More fields for the search results\n      }\n      // More search results\n    ]\n  }\n}\n\n</CODE_SNIPPET>\n<p>Here's how each of the colored boxes from the screenshot would be represented (the background colors correspond to the colors in the images above):</p><ul><li>Results <span style=\"background-color:rgb(180, 167, 214)\">11</span> - 20 of about 2,700,000 = startIndex</li><li>Results 11 - <span style=\"background-color:rgb(255, 217, 102)\">20</span> of about 2,700,000 = startIndex + currentItemCount - 1</li><li>Results 11 - 20 of about <span style=\"background-color:rgb(246, 178, 107)\">2,700,000</span> = totalItems</li><li><span style=\"background-color:rgb(234, 153, 153)\">Search results</span> = items (formatted appropriately)</li><li><span style=\"background-color:rgb(182, 215, 168)\">Previous/Next</span> = previousLink / nextLink</li><li><span style=\"background-color:rgb(159, 197, 232)\">Numbered links in \"Gooooooooooogle\"</span> = Derived from \"pageLinkTemplate\".  The developer is responsible for calculating the values for {index} and substituting those values into the \"pageLinkTemplate\".  The pageLinkTemplate's {index} variable is calculated as follows:<ul><li>Index #1 = 0 * itemsPerPage = 0</li><li>Index #2 = 2 * itemsPerPage = 10</li><li>Index #3 = 3 * itemsPerPage = 20</li><li>Index #N = N * itemsPerPage</li></ul></li></ul>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Appendix\">\n<STYLEPOINT title=\"Appendix A: Reserved JavaScript Words\">\n<SUMMARY>\nA list of reserved JavaScript words that should be avoided in property names.\n</SUMMARY>\n<BODY>\n<p>The words below are reserved by the JavaScript language and cannot be referred to using dot notation.  The list represents best knowledge of keywords at this time; the list may change or vary based on your specific execution environment.</p><p>From the <a href=\"https://www.google.com/url?sa=D&amp;q=http%3A%2F%2Fwww.ecma-international.org%2Fpublications%2Fstandards%2FEcma-262.htm\">ECMAScript Language Specification 5th Edition</a></p>\n<BAD_CODE_SNIPPET>\nabstract\nboolean break byte\ncase catch char class const continue\ndebugger default delete do double\nelse enum export extends\nfalse final finally float for function\ngoto\nif implements import in instanceof int interface\nlet long\nnative new null\npackage private protected public\nreturn\nshort static super switch synchronized\nthis throw throws transient true try typeof\nvar volatile void\nwhile with\nyield\n</BAD_CODE_SNIPPET>\n</BODY>\n</STYLEPOINT>\n</CATEGORY>\n<HR/>\n\n<p align=\"center\">\nExcept as otherwise <a href=\"https://code.google.com/policies.html\">noted</a>, the content of this page is licensed under the <a href=\"https://creativecommons.org/licenses/by/3.0/\">Creative Commons Attribution 3.0 License</a>, and code samples are licensed under the <a href=\"https://www.apache.org/licenses/LICENSE-2.0\">Apache 2.0 License</a>.\n</p>\n<p align=\"right\">\nRevision 0.9\n</p>\n\n<address>\n</address>\n\n</GUIDE>\n"
  },
  {
    "path": "lispguide.xml",
    "content": "<?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google Common Lisp Style Guide\">\n\n\n<p align=\"right\">\n\nRevision 1.28\n</p>\n\n\n<address>\nRobert Brown\n</address>\n<address>\n  <a HREF=\"mailto:tunes@google.com\">François-René Rideau</a>\n</address>\n\n<address>\n   In memoriam Dan Weinreb\n</address>\n\n<p align=\"center\">\n<cite>Patterns mean \"I have run out of language.\"</cite> — Rich Hickey\n</p>\n\n\n<OVERVIEW>\n<CATEGORY title=\"Important Note\">\n  <STYLEPOINT title=\"Note: Displaying Hidden Details in this Guide\">\n     <SUMMARY>\n       This style guide contains many details\n       that are initially hidden from view.\n       They are marked by the triangle icon, which you see here on your left.\n       Click it now. You should see \"Hooray\" appear below.\n     </SUMMARY>\n     <BODY>\n       <p>\n        Hooray!  Now you know you can expand points to get more details.\n        Alternatively, there's an \"expand all\" at the top of this document.\n       </p>\n     </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Background\">\n  <p>\n    Common Lisp is a powerful multiparadigm programming language.\n    With great power comes great responsibility.\n  </p>\n  <p>\n    This guide recommends formatting and stylistic choices\n    designed to make your code easier for other people to understand.\n    For those internal applications and free software libraries that\n    we develop at Google,\n    you should keep within these guidelines when making changes.\n    Note however that each project has its own rules and customs\n    that complement or override these general guidelines;\n    the speed-oriented QPX low fare search engine notably\n    has a very different style and feel from the QRes reservation system.\n  </p>\n  <p>\n    If you're writing Common Lisp code outside Google,\n    we invite you to consider these guidelines.\n    You may find some of them useful\n    where they don't conflict with other priorities you have.\n    We welcome remarks and constructive feedback\n    on how to improve our guide, and\n    on what alternate styles work for you and why.\n  </p>\n  \n  <p>\n    This guide is not a Common Lisp tutorial.\n    For basic information about the language, please consult\n    <a HREF=\"http://www.gigamonkeys.com/book/\">Practical Common Lisp</a>.\n    For a language reference, please consult the\n    <a HREF=\"http://www.lispworks.com/documentation/HyperSpec/Front/index.htm\">Common Lisp HyperSpec</a>.\n    For more detailed style guidance, take (with a pinch of salt)\n    a look at Peter Norvig and Kent Pitman's\n    <a HREF=\"http://norvig.com/luv-slides.ps\">style guide</a>.\n  </p>\n</CATEGORY>\n</OVERVIEW>\n<CATEGORY title=\"Meta-Guide\">\n  <STYLEPOINT title=\"Must, Should, May, or Not\">\n    <SUMMARY>\n      Each guideline's level of importance is indicated\n      by use of the following keywords and phrases, adapted from\n      <a href=\"https://www.ietf.org/rfc/rfc2119.txt\">RFC 2119</a>.\n    </SUMMARY>\n    <BODY>\n      <table>\n        <tr>\n          <th valign=\"top\">MUST</th>\n          <td>\n            <p>\n              This word, or the terms \"REQUIRED\" or \"SHALL\",\n              means that the guideline is an absolute requirement.\n              You must ask permission to violate a MUST.\n            </p>\n          </td>\n        </tr>\n        <tr>\n          <th valign=\"top\">MUST NOT</th>\n          <td>\n            <p>\n              This phrase, or the phrase \"SHALL NOT\",\n              means that the guideline is an absolute prohibition.\n              You must ask permission to violate a MUST NOT.\n            </p>\n          </td>\n        </tr>\n        <tr>\n          <th valign=\"top\">SHOULD</th>\n          <td>\n            <p>\n              This word, or the adjective \"RECOMMENDED\", means that\n              there may exist valid reasons in particular circumstances\n              to ignore the demands of the guideline, but\n              the full implications must be understood and carefully weighed\n              before choosing a different course.\n              You must ask forgiveness for violating a SHOULD.\n            </p>\n          </td>\n        </tr>\n        <tr>\n          <th valign=\"top\">SHOULD NOT</th>\n          <td>\n            <p>\n              This phrase, or the phrase \"NOT RECOMMENDED\", means that\n              there may exist valid reasons in particular circumstances\n              to ignore the prohibitions of this guideline, but\n              the full implications should be understood and carefully weighed\n              before choosing a different course.\n              You must ask forgiveness for violating a SHOULD NOT.\n            </p>\n          </td>\n        </tr>\n        <tr>\n          <th valign=\"top\">MAY</th>\n          <td>\n            <p>\n              This word, or the adjective \"OPTIONAL\",\n              means that an item is truly optional.\n            </p>\n          </td>\n        </tr>\n      </table>\n      <p>\n        Unlike RFCs, we don't capitalize every instance of one of the above\n        keywords when it is used.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Permission and Forgiveness\">\n    <SUMMARY>\n      There are cases where transgression of some of these rules\n      is useful or even necessary.\n      In some cases, you must seek permission or obtain forgiveness\n      from the proper people.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Permission comes from the owners of your project.\n      </p>\n      \n      <p>\n        Forgiveness is requested in a comment\n        near the point of guideline violation,\n        and is granted by your code reviewer.\n        The original comment should be signed by you, and\n        the reviewer should add a signed approval to the comment at review time.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Conventions\">\n    <SUMMARY>\n      You MUST follow conventions. They are not optional.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Some of these guidelines are motivated by universal principles of good programming.\n        Some guidelines are motivated by technical peculiarities of Common Lisp.\n        Some guidelines were once motivated by a technical reason,\n        but the guideline remained after the reason subsided.\n        Some guidelines, such those about as comments and indentation,\n        are based purely on convention, rather than on clear technical merit.\n        Whatever the case may be, you must still follow these guidelines,\n        as well as other conventional guidelines\n        that have not been formalized in this document.\n      </p>\n      <p>\n        You MUST follow conventions.\n        They are important for readability.\n        When conventions are followed by default,\n        violations of the convention are a signal\n        that something notable is happening and deserves attention.\n        When conventions are systematically violated,\n        violations of the convention are a distracting noise\n        that needs to be ignored.\n      </p>\n      <p>\n        Conventional guidelines <em>are</em> indoctrination.\n        Their purpose is to make you follow the mores of the community,\n        \n        so you can more effectively cooperate with existing members.\n        It is still useful to distinguish the parts that are technically motivated\n        from the parts that are mere conventions,\n        so you know when best to defy conventions for good effect,\n        and when not to fall into the pitfalls that the conventions are there to help avoid.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Old Code\">\n    <SUMMARY>\n      Fix old code as you go.\n    </SUMMARY>\n    <BODY>\n      <p>\n        A lot of our code was written before these guidelines existed.\n        You should fix violations as you encounter them\n        in the course of your normal coding.\n      </p>\n      <p>\n        You must not fix violations en masse\n        without warning other developers and coordinating with them,\n        so as not to make the merging of large branches\n        more difficult than it already is.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Future Topics\">\n    <SUMMARY>\n      There are many topics for additional standardization\n      not covered by current version of this document,\n      but deferred to future versions.\n    </SUMMARY>\n    <BODY>\n      <ul>\n        <li>\n          File and directory structure\n        </li>\n        <li>\n          Packages and modularity\n        </li>\n        <li>\n          Threads and locking\n        </li>\n        <li>\n          How to add configurable components\n        </li>\n        <li>\n          CLOS style: initforms, slot and accessor names, etc.\n        </li>\n        <li>\n          Recommendations on max number of slots per class.\n        </li>\n        <li>\n          More concrete examples of good code:\n          <ul>\n            <li>\n              exceptions\n            </li>\n            <li>\n              transactions, with retry\n            </li>\n            <li>\n              XML\n            </li>\n            <li>\n              typing\n            </li>\n            <li>\n              encapsulation / abstraction\n            </li>\n            <li>\n              class and slot names\n            </li>\n            <li>\n              etc.\n            </li>\n          </ul>\n        </li>\n        <li>\n          When (not) to use conditional compilation:\n          <ul>\n            <li>\n              modifying the product\n            </li>\n            <li>\n              conditional debugging/console output/etc.\n            </li>\n            <li>\n              \"temporarily\" commenting-out blocks of code\n            </li>\n            <li>\n              etc.\n            </li>\n          </ul>\n        </li>\n      </ul>\n    </BODY>\n  </STYLEPOINT>\n  </CATEGORY>\n<CATEGORY title=\"General Guidelines\">\n  <STYLEPOINT title=\"Principles\">\n    <SUMMARY>\n      There are some basic principles for team software development\n      that every developer must keep in mind.\n      Whenever the detailed guidelines are inadequate, confusing or contradictory,\n      refer back to these principles for guidance:\n      <ul>\n        <li>\n          Every developer's code must be easy for another developer\n          to read, understand, and modify\n          — even if the first developer isn't around to explain it.\n          (This is the \"hit by a truck\" principle.)\n        </li>\n        <li>\n          Everybody's code should look the same.\n          Ideally, there should be no way to look at lines of code\n          and recognize it as \"Fred's code\" by its style.\n        </li>\n        <li>\n          Be precise.\n        </li>\n        <li>\n          Be concise.\n        </li>\n        <li>\n          KISS — Keep It Simple, Stupid.\n        </li>\n        <li>\n          Use the smallest hammer for the job.\n        </li>\n        <li>\n          Use common sense.\n        </li>\n        <li>\n          Keep related code together.\n          Minimize the amount of jumping around\n          someone has to do to understand an area of code.\n        </li>\n      </ul>\n    </SUMMARY>\n    <BODY>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Priorities\">\n    <SUMMARY>\n      <p>\n        When making decisions about how to write a given piece of\n        code, aim for the following -ilities in this priority order:\n      </p>\n      <ul>\n        <li>\n          Usability by the customer\n        </li>\n        <li>\n          Debuggability/Testability\n        </li>\n        <li>\n          Readability/Comprehensibility\n        </li>\n        <li>\n          Extensibility/Modifiability\n        </li>\n        <li>\n          Efficiency (of the Lisp code at runtime)\n        </li>\n      </ul>\n    </SUMMARY>\n    <BODY>\n      <p>\n        Most of these are obvious.\n      </p>\n      <p>\n        Usability by the customer means that the system has to do what the\n        customer requires; it has to handle the customer's transaction\n        volumes, uptime requirements; etc.\n      </p>\n      <p>\n        For the Lisp efficiency point,\n        given two options of equivalent complexity,\n        pick the one that performs better.\n        (This is often the same as the one that conses less,\n        i.e. allocates less storage from the heap.)\n      </p>\n      <p>\n        Given two options where one is more complex than the other,\n        pick the simpler option and revisit the decision only if\n        profiling shows it to be a performance bottleneck.\n      </p>\n      <p>\n        However, avoid premature optimization.\n        Don't add complexity to speed up something that runs rarely,\n        since in the long run, it matters less whether such code is fast.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Architecture\">\n    <SUMMARY>\n      To build code that is robust and maintainable,\n      it matters a lot how the code is divided into components,\n      how these components communicate,\n      how changes propagate as they evolve,\n      and more importantly\n      how the programmers who develop these components communicate\n      as these components evolve.\n    </SUMMARY>\n    <BODY>\n      <p>\n        If your work affects other groups, might be reusable across groups,\n        adds new components, has an impact on other groups\n        (including QA or Ops), or otherwise isn't purely local,\n        you must write it up using at least a couple of paragraphs,\n        and get a design approval from the other parties involved\n        before starting to write code — or be ready to scratch what you have\n        when they object.\n      </p>\n      <p>\n        If you don't know or don't care about these issues,\n        ask someone who does.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Using Libraries\">\n    <SUMMARY>\n      Often, the smallest hammer is to use an existing library.\n      Or one that doesn't exist yet.\n      In such cases, you are encouraged to use or develop such a library,\n      but you must take appropriate precautions.\n    </SUMMARY>\n    <BODY>\n      <ul>\n        <li>\n          You MUST NOT start a new library\n          unless you established that none is already available\n          that can be fixed or completed into becoming what you need.\n          That's a rule against the NIH syndrome (\"Not Invented Here\"),\n          which is particularly strong amongst Lisp hackers.\n        </li>\n        <li>\n          Whichever library, old or new, you pick, you MUST get permission\n          to incorporate third-party code into the code base.\n          You must discuss the use of such library\n          in the appropriate mailing-list,\n          and have your code reviewed by people knowledgeable in the domain\n          and/or the Lisp library ecosystem (if any).\n          Please be ready to argue why this particular solution makes sense\n          as compared to other available libraries.\n        </li>\n        <li>\n          Some libraries are distributed under licenses not compatible\n          with the software you're writing, and\n          must not be considered available for use.\n          Be aware of these issues, or consult with people who are.\n        </li>\n      </ul>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Open-Sourcing Code\">\n    <SUMMARY>\n      <p>\n        If you write a general-purpose library,\n        or modify an existing open-source library,\n        you are encouraged to publish the result\n        separate from your main project and then\n        have your project import it like any other open-source library.\n      </p>\n      \n    </SUMMARY>\n    <BODY>\n      <p>\n        Use your judgment to distinguish\n        general-purpose versus business-specific code,\n        and open-source the general-purpose parts,\n        while keeping the business-specific parts a trade secret.\n      </p>\n      \n      <p>\n        Open-Sourcing code has many advantages,\n        including being able to leverage third parties for development,\n        letting the development of features be user-directed,\n        and keeping you honest with respect to code quality.\n        Whatever code you write, you will have to maintain anyway,\n        and make sure its quality is high enough to sustain use in production.\n        There should therefore be no additional burden to Open-Sourcing,\n        even of code that (at least initially)\n        is not directly usable by third parties.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Development Process\">\n    <SUMMARY>\n      Development process is outside the scope of this document.\n      However, developers should remember at least these bits:\n      get reviewed, write tests, eliminate warnings, run tests, avoid mass-changes.\n    </SUMMARY>\n    <BODY>\n      <p>\n      </p>\n      <ul>\n        <li>\n          All code changes must be reviewed.\n          You should expect that your code will be reviewed by other hackers,\n          and that you will be assigned other hackers' code to review.\n          Part of the review criteria will be that code obeys\n          the coding standards in this document.\n        </li>\n        <li>\n          You must write and check-in tests for new code that you write and old bugs you fix.\n          There must be a unit test for every API function,\n          and any previously failing case.\n          Your work is not truly done until this activity is complete.\n          Estimating tasks must include the time it takes to produce such tests.\n        </li>\n        <li>\n          Your code must compile\n          without any compilation error or warning messages whatsoever.\n          If the compiler issues warnings that should be ignored,\n          muffle those warnings using the\n          <code>UIOP:WITH-MUFFLED-COMPILER-CONDITIONS</code> and\n          <code>UIOP:*UNINTERESTING-COMPILER-CONDITIONS*</code>\n          framework (part of <code>UIOP</code>, part of <code>ASDF 3</code>),\n          either around the entire project, or around individual files\n          (using <code>ASDF</code>'s <code>:around-compile</code> hooks).\n        </li>\n        <li>\n          All code should be checked in an appropriate source control system,\n          in a way that allows for complete reproducibility of\n          build, test and execution of\n          the code that is, has been or may be deployed.\n        </li>\n        <li>\n          You must run the \"precheckin\" tests, and each component must pass\n          its unit tests successfully before you commit any code.\n        </li>\n        <li>\n          You should incorporate code coverage into your testing process.\n          Tests are not sufficient\n          if they do not cover all new and updated code;\n          code that for whatever reason cannot be included in coverage results\n          should be clearly marked as such including the reason.\n        </li>\n        <li>\n          Many people develop on branches.\n          You must get permission to undertake mass-changes\n          (e.g. mass reindentations)\n          so that we can coordinate in advance,\n          and give branch residents time to get back on the mainline\n        </li>\n      </ul>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n<CATEGORY title=\"Formatting\">\n  <STYLEPOINT title=\"Spelling and Abbreviations\">\n    <SUMMARY>\n      <p>\n        You must use correct spelling in your comments,\n        and most importantly in your identifiers.\n      </p>\n      <p>\n        When several correct spellings exist (including American vs English),\n        and there isn't a consensus amongst developers as which to use,\n        you should choose the shorter spelling.\n      </p>\n      <p>\n        You must use only common and domain-specific abbreviations, and\n        must be consistent with these abbreviations.  You may abbreviate\n        lexical variables of limited scope in order to avoid overly-long\n        symbol names.\n      </p>\n    </SUMMARY>\n    <BODY>\n      <p>\n        If you're not sure, consult a dictionary,\n        Google for alternative spellings,\n        or ask a local expert.\n      </p>\n      <p>\n        Here are examples of choosing the correct spelling:\n      </p>\n      <ul>\n        <li>\n          Use \"complimentary\" in the sense of a meal or beverage\n          that is not paid for by the recipient, not \"complementary\".\n        </li>\n        <li>\n          Use \"existent\" and \"nonexistent\", not \"existant\".\n          Use \"existence\", not \"existance\".\n        </li>\n        <li>\n          Use \"hierarchy\" not \"heirarchy\".\n        </li>\n        <li>\n          Use \"precede\" not \"preceed\".\n        </li>\n        <li>\n          Use \"weird\", not \"wierd\".\n        </li>\n      </ul>\n      <p>\n        Here are examples of choosing the shorter spelling:\n      </p>\n      <ul>\n        <li>\n          Use \"canceled\", not \"cancelled\"\n        </li>\n        <li>\n          Use \"queuing\", not \"queueing\".\n        </li>\n        <li>\n          Use \"signaled\", not \"signalled\";\n        </li>\n        <li>\n          Use \"traveled\", not \"travelled\".\n        </li>\n        <li>\n          Use \"aluminum\", not \"aluminium\"\n        </li>\n        <li>\n          Use \"oriented\", not \"orientated\"\n        </li>\n        <li>\n          Use \"color\", not \"colour\"\n        </li>\n        <li>\n          Use \"behavior\", not \"behaviour\"\n        </li>\n      </ul>\n      <p>\n        Make appropriate exceptions for industry standard nomenclature/jargon,\n        including plain misspellings.\n        For instance:\n      </p>\n      <ul>\n        <li>\n          Use \"referer\", not \"referrer\", in the context of the HTTP protocol.\n        </li>\n      </ul>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Line length\">\n    <SUMMARY>\n      You should format source code so that no line is longer than 100 characters.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Some line length restriction is better than none at all.\n        While old text terminals used to make 80 columns the standard,\n        these days, allowing 100 columns seems better,\n        since good style encourages the use of\n        descriptive variables and function names.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Indentation\">\n    <SUMMARY>\n      <p>\n        Indent your code the way a properly configured GNU Emacs does.\n      </p>\n      <p>\n        Maintain a consistent indentation style throughout a project.\n      </p>\n      <p>\n        Indent carefully to make the code easier to understand.\n      </p>\n    </SUMMARY>\n    <BODY>\n      <p>\n        Common Lisp indentation in Emacs is provided by the cl-indent library.\n        The latest version of cl-indent is packaged with\n        <a HREF=\"https://www.common-lisp.net/project/slime/\">SLIME</a>\n        (under contrib/slime-cl-indent.el). After installing SLIME, set up Emacs\n        to load SLIME automatically using\n        <a HREF=\"https://www.common-lisp.net/project/slime/doc/html/Loading-Contribs.html\">these instructions</a>, adding slime-indentation to the list of\n        contrib libraries to be loaded in the call to slime-setup.\n     </p>\n     <p>\n        Ideally, use the default indentation settings provided by\n        slime-indentation. If necessary, customize indentation parameters to\n        maintain a consistent indentation style throughout an existing project.\n        Parameters can be customized using the :variables setting in\n        define-common-lisp-style. Indentation of specific forms can be\n        customized using the :indentation setting of define-common-lisp-style.\n        This is particularly useful when creating forms that behave like macros\n        or special operators that are indented differently than standard\n        function calls (e.g. defun, labels, or let). Add a\n        <a HREF=\"https://www.gnu.org/software/emacs/manual/html_node/emacs/Hooks.html\">hook</a> to 'lisp-mode-hook that calls common-lisp-set-style to set\n        the appropriate style automatically.\n      </p>\n      \n      \n      <p>\n        Use indentation to make complex function applications easier to read.\n        When an application does not fit on one line\n        or the function takes many arguments,\n        consider inserting newlines between the arguments\n        so that each one is on a separate line.\n        However, do not insert newlines in a way that makes it hard to tell\n        how many arguments the function takes\n        or where an argument form starts and ends.\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (do-something first-argument second-argument (lambda (x)\n            (frob x)) fourth-argument last-argument)\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (do-something first-argument\n                      second-argument\n                      #'(lambda (x) (frob x))\n                      fourth-argument\n                      last-argument)\n      </CODE_SNIPPET>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"File Header\">\n    <SUMMARY>\n      <p>\n        You should include a description at the top of each source file.\n      </p>\n      <p>\n        You should include neither authorship nor copyright information in a source file.\n      </p>\n    </SUMMARY>\n    <BODY>\n      <p>\n        Every source file should begin with a brief description\n        of the contents of that file.\n      </p>\n      <p>\n        After that description, every file should start the code itself with an\n        <code>(in-package #:<em>package-name</em>)</code> form.\n      </p>\n      <p>\n        After that <code>in-package</code> form,\n        every file should follow with any file-specific\n        <code>(declaim (optimize ...))</code> declaration\n        that is not covered by an <code>ASDF</code> <code>:around-compile</code> hook.\n      </p>\n      <CODE_SNIPPET>\n        ;;;; Variable length encoding for integers and floating point numbers.\n\n        (in-package #:varint)\n        (declaim #.*optimize-default*)\n      </CODE_SNIPPET>\n      <p>\n        You should not include authorship information at the top of a file:\n        better information is available from version control,\n        and such a mention will only cause confusion and grief.\n        Indeed, whoever was the main author at the time such a mention was included\n        might not be who eventually made the most significant contributions to the file,\n        and even less who is responsible for the file at the moment.\n        \n      </p>\n      <p>\n        You should not include copyright information in individual source code files.\n        An exception is made for files meant to be disseminated as standalone.\n      </p>\n      \n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Vertical white space\">\n    <SUMMARY>\n      Vertical white space: one blank line between top-level forms.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should include one blank line between top-level forms,\n        such as function definitions.\n        Exceptionally, blank lines can be omitted\n        between simple, closely related defining forms of the same kind,\n        such as a group of related type declarations or constant definitions.\n      </p>\n      <CODE_SNIPPET>\n        (defconstant +mix32+ #x12b9b0a1 \"pi, an arbitrary number\")\n        (defconstant +mix64+ #x2b992ddfa23249d6 \"more digits of pi\")\n\n        (defconstant +golden-ratio32+ #x9e3779b9 \"the golden ratio\")\n        (defconstant +golden-ratio64+ #xe08c1d668b756f82 \"more digits of the golden ratio\")\n\n        (defmacro incf32 (x y)\n          \"Like INCF, but for integers modulo 2**32\"\n          `(setf ,x (logand (+ ,x ,y) #xffffffff)))\n        (defmacro incf64 (x y)\n          \"Like INCF, but for integers modulo 2**64\"\n          `(setf ,x (logand (+ ,x ,y) #xffffffffffffffff)))\n      </CODE_SNIPPET>\n      <p>\n        Blank lines can be used to separate parts of a complicated function.\n        Generally, however, you should break a large function into smaller ones\n        instead of trying to make it more readable by adding vertical space.\n        If you can't, you should document with a <code>;;</code> comment\n        what each of the separated parts of the function does.\n      </p>\n      <p>\n        You should strive to keep top-level forms,\n        including comments but excluding the documentation string, of\n        appropriate length; preferably short.  Forms extending beyond a\n        single page should be rare and their use should be justified.\n        This applies to each of the forms in an <code>eval-when</code>,\n        rather than to the <code>eval-when</code> itself.\n        Additionally, <code>defpackage</code> forms may be longer,\n        since they may include long lists of symbols.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Horizontal white space\">\n    <SUMMARY>\n      Horizontal white space: none around parentheses. No tabs.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You must not include extra horizontal whitespace\n        before or after parentheses or around symbols.\n      </p>\n      <p>\n        You must not place right parentheses by themselves on a line.\n        A set of consecutive trailing parentheses must appear on the same line.\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Very Bad\n        ( defun factorial ( limit )\n          ( let (( product 1 ))\n            ( loop for i from 1 upto limit\n                  do (setf product ( * product i ) ) )\n            product\n          )\n        )\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (defun factorial (limit)\n          (let ((product 1))\n            (loop for i from 1 upto limit\n                  do (setf product (* product i)))\n            product))\n      </CODE_SNIPPET>\n      <p>\n        You should use only one space between forms.\n      </p>\n      <p>\n        You should not use spaces to vertically align forms\n        in the middle of consecutive lines.\n        An exception is made when the code possesses\n        an important yet otherwise not visible symmetry\n        that you want to emphasize.\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (let* ((low    1)\n               (high   2)\n               (sum    (+ (* low low) (* high high))))\n          ...)\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (let* ((low 1)\n               (high 2)\n               (sum (+ (* low low) (* high high))))\n          ...))\n      </CODE_SNIPPET>\n      <p>\n        You must align nested forms if they occur across more than one line.\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (defun munge (a b c)\n        (* (+ a b)\n        c))\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (defun munge (a b c)\n          (* (+ a b)\n             c))\n      </CODE_SNIPPET>\n      <p>\n        The convention is that the body of a binding form\n        is indented two spaces after the form.\n        Any binding data before the body is usually indented four spaces.\n        Arguments to a function call are aligned with the first argument;\n        if the first argument is on its own line,\n        it is aligned with the function name.\n      </p>\n      <CODE_SNIPPET>\n        (multiple-value-bind (a b c d)\n            (function-returning-four-values x y)\n          (declare (ignore c))\n          (something-using a)\n          (also-using b d))\n      </CODE_SNIPPET>\n      <p>\n        An exception to the rule against lonely parentheses\n        is made for an <code>eval-when</code> form around several definitions;\n        in this case, include a comment <code>; eval-when</code>\n        after the closing parenthesis.\n      </p>\n      <p>\n        You must set your editor to\n        avoid inserting tab characters in the files you edit.\n        Tabs cause confusion when editors disagree\n        on how many spaces they represent.\n        In Emacs, do <code>(setq-default indent-tabs-mode nil)</code>.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Documentation\">\n  <STYLEPOINT title=\"Document everything\">\n    <SUMMARY>\n      You should use document strings on all visible functions\n      to explain how to use your code.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Unless some bit of code is painfully self-explanatory,\n        document it with a documentation string (also known as docstring).\n      </p>\n      <p>\n        Documentation strings are destined to be read\n        by the programmers who use your code.\n        They can be extracted from functions, types, classes, variables and macros,\n        and displayed by programming tools, such as IDEs,\n        or by REPL queries such as <code>(describe 'foo)</code>;\n        web-based documentation or other reference works\n        can be created based on them.\n        Documentation strings are thus the perfect locus to document your API.\n        They should describe how to use the code\n        (including what pitfalls to avoid),\n        as opposed to how the code works (and where more work is needed),\n        which is what you'll put in comments.\n      </p>\n      <p>\n        Supply a documentation string when defining\n        top-level functions, types, classes, variables and macros.\n        Generally, add a documentation string wherever the language allows.\n      </p>\n      <p>\n        For functions, the docstring should describe the function's contract:\n        what the function does,\n        what the arguments mean,\n        what values are returned,\n        what conditions the function can signal.\n        It should be expressed at the appropriate level of abstraction,\n        explaining the intended meaning rather than, say, just the syntax.\n        In documentation strings, capitalize the names of Lisp symbols,\n        such as function arguments.\n        For example, \"The value of LENGTH should be an integer.\"\n      </p>\n      <CODE_SNIPPET>\n        (defun small-prime-number-p (n)\n          \"Return T if N, an integer, is a prime number. Otherwise, return NIL.\"\n          (cond ((or (&lt; n 2))\n                 nil)\n                ((= n 2)\n                 t)\n                ((divisorp 2 n)\n                 nil)\n                (t\n                 (loop for i from 3 upto (sqrt n) by 2\n                       never (divisorp i n)))))\n      </CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (defgeneric table-clear (table)\n          (:documentation\n            \"Like clrhash, empties the TABLE of all\n            associations, and returns the table itself.\"))\n      </CODE_SNIPPET>\n      <p>\n        A long docstring may usefully\n        begin with a short, single-sentence summary,\n        followed by the larger body of the docstring.\n      </p>\n      <p>\n        When the name of a type is used,\n        the symbol may be quoted by surrounding it with\n        a back quote at the beginning and a single quote at the end.\n        Emacs will highlight the type, and the highlighting serves\n        as a cue to the reader that <kbd>M-.</kbd>\n        will lead to the symbol's definition.\n      </p>\n      <CODE_SNIPPET>\n        (defun bag-tag-expected-itinerary (bag-tag)\n          \"Return a list of `legacy-pnr-pax-segment' objects representing\n          the expected itinerary of the `bag-tag' object, BAG-TAG.\"\n          ...)\n      </CODE_SNIPPET>\n      <p>\n        Every method of a generic function should be independently documented\n        when the specialization affects what the method does,\n        beyond what is described in its generic function's docstring.\n      </p>\n      <p>\n        When you fix a bug,\n        consider whether what the fixed code does is obviously correct or not;\n        if not, you must add a comment explaining\n        the reason for the code in terms of fixing the bug.\n        Adding the bug number, if any, is also recommended.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Comment semicolons\">\n    <SUMMARY>\n      You must use the appropriate number of semicolons to introduce comments.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Comments are explanations to the future maintainers of the code.\n        Even if you're the only person who will ever see and touch the code,\n        even if you're either immortal and never going to quit,\n        or unconcerned with what happens after you leave\n        (and have your code self-destruct in such an eventuality),\n        you may find it useful to comment your code.\n        Indeed, by the time you revisit your code,\n        weeks, months or years later,\n        you will find yourself a different person from the one who wrote it,\n        and you will be grateful to that previous self\n        for making the code readable.\n      </p>\n      <p>\n        You must comment anything complicated\n        so that the next developer can understand what's going on.\n        (Again, the \"hit by a truck\" principle.)\n      </p>\n      <p>\n        Also use comments as a way to guide those who read the code,\n        so they know what to find where.\n      </p>\n      <ul>\n        <li>\n          File headers and important comments\n          that apply to large sections of code in a source file\n          should begin with four semicolons.\n        </li>\n        <li>\n          You should use three semicolons\n          to begin comments that apply to just\n          one top-level form or small group of top-level forms.\n        </li>\n        <li>\n          Inside a top-level form, you should use two semicolons\n          to begin a comment if it appears between lines.\n        </li>\n        <li>\n          You should use one semicolon if it is a parenthetical remark\n          and occurs at the end of a line.\n          You should use spaces to separate the comment\n          from the code it refers to so the comment stands out.\n          You should try to vertically align\n          consecutive related end-of-line comments.\n        </li>\n      </ul>\n      <CODE_SNIPPET>\n        ;;;; project-euler.lisp\n        ;;;; File-level comments or comments for large sections of code.\n\n        ;;; Problems are described in more detail here:  https://projecteuler.net/\n\n        ;;; Divisibility\n        ;;; Comments that describe a group of definitions.\n\n        (defun divisorp (d n)\n          (zerop (mod n d)))\n\n        (defun proper-divisors (n)\n          ...)\n\n        (defun divisors (n)\n          (cons n (proper-divisors n)))\n\n        ;;; Prime numbers\n\n        (defun small-prime-number-p (n)\n          (cond ((or (&lt; n 2))\n                 nil)\n                ((= n 2)   ; parenthetical remark here\n                 t)        ; continuation of the remark\n                ((divisorp 2 n)\n                 nil)  ; different remark\n                ;; Comment that applies to a section of code.\n                (t\n                 (loop for i from 3 upto (sqrt n) by 2\n                       never (divisorp i n)))))\n      </CODE_SNIPPET>\n      <p>\n        You should include a space between the semicolon and the text of the comment.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Grammar and punctuation\">\n    <SUMMARY>\n      You should punctuate documentation correctly.\n    </SUMMARY>\n    <BODY>\n      <p>\n        When a comment is a full sentence,\n        you should capitalize the initial letter of the first word\n        and end the comment with a period.\n        In general, you should use correct punctuation.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Attention Required\">\n    <SUMMARY>\n      You must follow the convention of using TODO comments\n      for code requiring special attention.\n      For code using unobvious forms, you must include a comment.\n    </SUMMARY>\n    <BODY>\n      <p>\n        For comments requiring special attention, such as\n        incomplete code, todo items, questions, breakage, and danger,\n        include a TODO comment indicating the type of problem,\n        its nature, and any notes on how it may be addressed.\n      </p>\n      <p>\n        The comments begin with <code>TODO</code> in all capital letters,\n        followed by the\n        \n        name, e-mail address, or other identifier\n        of the person \n        with the best context about the problem referenced by the <code>TODO</code>.\n        The main purpose is to have a consistent <code>TODO</code> that\n        can be searched to find out how to get more details upon\n        request. A <code>TODO</code> is not a commitment that the\n        person referenced will fix the problem. Thus when you create\n        a <code>TODO</code>,\n        it is almost always your \n        name\n        that is given.\n      </p>\n      <p>\n        When signing comments,\n        you should use your username (for code within the company)\n        or full email address (for code visible outside the company),\n        not just initials.\n        \n      </p>\n      <CODE_SNIPPET>\n        ;;--- TODO(george@gmail.com): Refactor to provide a better API.\n      </CODE_SNIPPET>\n      <p>\n        Be specific when indicating times or software releases\n        in a TODO comment and use\n        <a HREF=\"https://www.w3.org/TR/NOTE-datetime\">YYYY-MM-DD</a>\n        format for dates to make automated processing of such dates easier,\n        e.g., 2038-01-20 for the end of the 32-bit signed <code>time_t</code>.\n      </p>\n      <CODE_SNIPPET>\n        ;;--- TODO(brown): Remove this code after release 1.7 or before 2012-11-30.\n      </CODE_SNIPPET>\n      <p>\n        For code that uses unobvious forms to accomplish a task, you must include a comment\n        stating the purpose of the form and the task it accomplishes.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Domain-Specific Languages\">\n    <SUMMARY>\n      You should document DSLs and\n      any terse program in a DSL.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should design your Domain Specific Language\n        to be easy to read and understand by people familiar with the domain.\n      </p>\n      <p>\n        You must properly document all your Domain Specific Language.\n      </p>\n      <p>\n        Sometimes, your DSL is designed for terseness.\n        In that case, it is important to document what each program does,\n        if it's not painfully obvious from the context.\n      </p>\n      <p>\n        Notably, when you use regular expressions\n        (e.g. with the <code>CL-PPCRE</code> package),\n        you MUST ALWAYS put in a comment\n        (usually a two-semicolon comment on the previous line)\n        explaining, at least basically, what the regular expression does,\n        or what the purpose of using it is.\n        The comment need not spell out every bit of the syntax, but\n        it should be possible for someone to follow the logic of the code\n        without actually parsing the regular expression.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n\n</CATEGORY>\n\n<CATEGORY title=\"Naming\">\n  <STYLEPOINT title=\"Symbol guidelines\">\n    <SUMMARY>\n      You should use lower case.\n      You should follow the rules for <a href=\"#Spelling_and_Abbreviations\">Spelling and Abbreviations</a>\n      You should follow punctuation conventions.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Use lower case for all symbols.\n        Consistently using lower case makes searching for symbol names easier\n        and is more readable.\n      </p>\n      <p>\n        Note that Common Lisp is case-converting,\n        and that the <code>symbol-name</code> of your symbols\n        will be upper case.\n        Because of this case-converting,\n        attempts to distinguish symbols by case are defeated,\n        and only result in confusion.\n        While it is possible to escape characters in symbols\n        to force lower case,\n        you should not use this capability\n        unless this is somehow necessary\n        to interoperate with third-party software.\n      </p>\n      <p>\n        Place hyphens between all the words in a symbol.\n        If you can't easily say an identifier out loud,\n        it is probably badly named.\n      </p>\n      <p>\n        You must not use <code>\"/\"</code> or <code>\".\"</code>\n        instead of <code>\"-\"</code>\n        unless you have a well-documented overarching reason to,\n        and permission from other hackers who review your proposal.\n      </p>\n      <p>\n        See the section on <a href=\"#Spelling_and_Abbreviations\">Spelling and Abbreviations</a>\n        for guidelines on using abbreviations.\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (defvar *default-username* \"Ann\")\n        (defvar *max-widget-cnt* 200)\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (defvar *default-user-name* \"Ann\")\n        (defvar *maximum-widget-count* 200)\n      </CODE_SNIPPET>\n      <p>\n        There are conventions in Common Lisp\n        for the use of punctuation in symbols.\n        You should not use punctuation in symbols outside these conventions.\n      </p>\n      <p>\n        Unless the scope of a variable is very small,\n        do not use overly short names like\n        <code>i</code> and <code>zq</code>.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Denote intent, not content\">\n    <SUMMARY>\n      Name your variables according to their intent,\n      not their content.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should name a variable according\n        to the high-level concept that it represents,\n        not according to the low-level implementation details\n        of how the concept is represented.\n      </p>\n      <p>\n        Thus, you should avoid embedding\n        data structure or aggregate type names,\n        such as <code>list</code>, <code>array</code>, or\n        <code>hash-table</code> inside variable names,\n        unless you're writing a generic algorithm that applies to\n        arbitrary lists, arrays, hash-tables, etc.\n        In that case it's perfectly OK to name a variable\n        <code>list</code> or <code>array</code>.\n      </p>\n      <p>\n        Indeed, you should be introducing new abstract data types\n        with <code>DEFCLASS</code> or <code>DEFTYPE</code>,\n        whenever a new kind of intent appears for objects in your protocols.\n        Functions that manipulate such objects generically may then\n        use variables the name of which reflect that abstract type.\n      </p>\n      <p>\n        For example, if a variable's value is always a row\n        (or is either a row or <code>NIL</code>),\n        it's good to call it <code>row</code> or <code>first-row</code>\n        or something like that.\n        It is alright is <code>row</code> has been\n        <code>DEFTYPE</code>'d to <code>STRING</code> —\n        precisely because you have abstracted the detail away,\n        and the remaining salient point is that it is a row.\n        You should not name the variable <code>STRING</code> in this context,\n        except possibly in low-level functions that specifically manipulate\n        the innards of rows to provide the suitable abstraction.\n      </p>\n      <p>\n        Be consistent.\n        If a variable is named <code>row</code> in one function,\n        and its value is being passed to a second function,\n        then call it <code>row</code> rather than, say, <code>value</code>\n        (this was a real case).\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Global variables and constants\">\n    <SUMMARY>\n      Name globals according to convention.\n    </SUMMARY>\n    <BODY>\n      <p>\n        The names of global constants should start and end\n        with plus characters.\n      </p>\n      <p>\n        Global variable names should start and end with asterisks\n        (also known in this context as earmuffs).\n      </p>\n      <p>\n        In some projects, parameters that are not meant\n        to be usually modified or bound under normal circumstances\n        (but may be during experimentation or exceptional situations)\n        should start (but do not end) with a dollar sign.\n        If such a convention exists within your project,\n        you should follow it consistently.\n        Otherwise, you should avoid naming variables like this.\n      </p>\n      <p>\n        Common Lisp does not have global lexical variables,\n        so a naming convention is used to ensure that globals,\n        which are dynamically bound,\n        never have names that overlap with local variables.\n        It is possible to fake global lexical variables\n        with a differently named global variable\n        and a <code>DEFINE-SYMBOL-MACRO</code>.\n        You should not use this trick,\n        unless you first publish a library that abstracts it away.\n      </p>\n      <CODE_SNIPPET>\n        (defconstant +hash-results+ #xbd49d10d10cbee50)\n\n        (defvar *maximum-search-depth* 100)\n      </CODE_SNIPPET>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Predicate names\">\n    <SUMMARY>\n      Names of predicate functions and variables end with a <code>\"P\"</code>.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should name boolean-valued functions and variables with a\n        trailing <code>\"P\"</code> or <code>\"-P\"</code>,\n        to indicate they are predicates.\n        Generally, you should use\n        <code>\"P\"</code> when the rest of the function name is one word\n        and <code>\"-P\"</code> when it is more than one word.\n      </p>\n      <p>\n        A rationale for this convention is given in\n        <a href=\"http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node69.html\">the CLtL2 chapter on predicates</a>.\n      </p>\n      <p>\n        For uniformity, you should follow the convention above,\n        and not one of the alternatives below.\n      </p>\n      <p>\n        An alternative rule used in some existing packages\n        is to always use <code>\"-P\"</code>.\n        Another alternative rule used in some existing packages\n        is to always use <code>\"?\"</code>.\n        When you develop such a package,\n        you must be consistent with the rest of the package.\n        When you start a new package,\n        you should not use such an alternative rule\n        without a very good documented reason.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Omit library prefixes\">\n    <SUMMARY>\n      You should not include a library or package name\n      as a prefix within the name of symbols.\n    </SUMMARY>\n    <BODY>\n      <p>\n        When naming a symbol (external or internal) in a package,\n        you should not include the package name\n        as a prefix within the name of the symbol.\n        Naming a symbol this way makes it awkward to use\n        from a client package accessing the symbol\n        by qualifying it with a package prefix,\n        where the package name then appears twice\n        (once as a package prefix,\n        another time as a prefix within the symbol name).\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (in-package #:varint)\n        (defun varint-length64 () ... )\n\n        (in-package #:client-code)\n        (defconst +padding+ (varint:varint-length64 +end-token+))\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (in-package #:varint)\n        (defun length64 () ... )\n\n        (in-package #:client-code)\n        (defconst +padding+ (varint:length64 +end-token+))\n      </CODE_SNIPPET>\n      <p>\n        An exception to the above rule would be to include a prefix\n        for the names of variables that would otherwise be expected to clash\n        with variables in packages that use the current one.\n        For instance, <code>ASDF</code> exports a variable <code>*ASDF-VERBOSE*</code>\n        that controls the verbosity of <code>ASDF</code> only,\n        rather than of the entire Lisp program.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Packages\">\n    <SUMMARY>\n      Use packages appropriately.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Lisp packages are used to demarcate namespaces.\n        Usually, each system has its own namespace.\n        A package has a set of external symbols,\n        which are intended to be used from outside the package,\n        in order to allow other modules to use this module's facilities.\n      </p>\n      <p>\n        The internal symbols of a package\n        should never be referred to from other packages.\n        That is, you should never have to use\n        the double-colon <code>::</code> construct.\n        (e.g. <code>QUAKE::HIDDEN-FUNCTION</code>).\n        If you need to use double-colons to write real production code,\n        something is wrong and needs to be fixed.\n      </p>\n      <p>\n        As an exception,\n        unit tests may use the internals of the package being tested.\n        So when you refactor, watch out for\n        internals used by the package's unit tests.\n      </p>\n      <p>\n        The <code>::</code> construct is also useful for very temporary hacks,\n        and at the REPL.\n        But if the symbol really is part of\n        the externally-visible definition of the package,\n        export it.\n      </p>\n      <p>\n        You may find that some internal symbols represent concepts\n        you usually want to abstract away and hide under the hood,\n        yet at times are necessary to expose for various extensions.\n        For the former reason, you do not want to export them,\n        yet for the latter reason, you have to export them.\n        The solution is to have two different packages,\n        one for your normal users to use, and\n        another for the implementation and its extenders to use.\n      </p>\n      <p>\n        Each package is one of two types:\n      </p>\n      <ul>\n        <li>\n          Intended to be included\n          in the <code>:use</code> specification of other packages.\n          If package <code>A</code> \"uses\" package <code>B</code>,\n          then the external symbols of package <code>B</code>\n          can be referenced from within package <code>A</code>\n          without a package prefix.\n          We mainly use this for low-level modules\n          that provide widely-used facilities.\n        </li>\n        <li>\n          Not intended to be \"used\".\n          To reference a facility provided by package <code>B</code>,\n          code in package <code>A</code> must use an explicit package prefix,\n          e.g. <code>B:DO-THIS</code>.\n        </li>\n      </ul>\n      <p>\n        If you add a new package, it should always be of the second type,\n        unless you have a special reason and get permission.\n        Usually a package is designed to be one or the other,\n        by virtue of the names of the functions.\n        For example, if you have an abstraction called <code>FIFO</code>,\n        and it were in a package of the first type\n        you'd have functions named things like\n        <code>FIFO-ADD-TO</code> and <code>FIFO-CLEAR-ALL</code>.\n        If you used a package of the second type,\n        you'd have names like <code>ADD-TO</code> and <code>CLEAR-ALL</code>,\n        because the callers would be saying\n        <code>FIFO:ADD-TO</code> and <code>FIFO:CLEAR-ALL</code>.\n        (<code>FIFO:FIFO-CLEAR-ALL</code> is redundant and ugly.)\n      </p>\n      <p>\n        Another good thing about packages is that\n        your symbol names won't \"collide\" with the names of other packages,\n        except the ones your packages \"uses\".\n        So you have to stay away from symbols\n        that are part of the Lisp implementation (since you always \"use\" that)\n        and that are part of any other packages you \"use\",\n        but otherwise you are free to make up your own names,\n        even short ones, and not worry about some else\n        having used the same name.\n        You're isolated from each other.\n      </p>\n      <p>\n        Your package must not shadow (and thus effectively redefine)\n        symbols that are part of the Common Lisp language.\n        There are certain exceptions,\n        but they should be very well-justified and extremely rare:\n      </p>\n      <ul>\n        <li>\n          If you are explicitly replacing a Common Lisp symbol\n          by a safer or more featureful version.\n        </li>\n        <li>\n          If you are defining a package not meant to be \"used\",\n          and have a good reason to export a symbol\n          that clashes with Common Lisp,\n          such as <code>log:error</code> and <code>log:warn</code>\n          and so on.\n        </li>\n      </ul>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Language usage guidelines\">\n  <STYLEPOINT title=\"Mostly Functional Style\">\n    <SUMMARY>\n      You should avoid side-effects when they are not necessary.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Lisp is best used as a \"mostly functional\" language.\n      </p>\n      <p>\n        Avoid modifying local variables, try rebinding instead.\n      </p>\n      <p>\n        Avoid creating objects and the SETFing their slots.\n        It's better to set the slots during initialization.\n      </p>\n      <p>\n        Make classes as immutable as possible, that is, avoid giving slots\n        setter functions if at all possible.\n      </p>\n      <p>\n        Using a mostly functional style makes it much easier\n        to write concurrent code that is thread-safe.\n        It also makes it easier to test the code.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Recursion\">\n    <SUMMARY>\n      You should favor iteration over recursion.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Common Lisp systems are not required to implement\n        function calls from tail positions without leaking stack space\n        — which is known as proper tail calls (PTC),\n        tail call elimination (TCE),\n        or tail call optimization (TCO).\n        This means that indefinite recursion through tail calls\n        may quickly blow out the stack,\n        which hampers functional programming.\n        Still, most serious implementations (including SBCL and CCL)\n        do implement proper tail calls, but with restrictions:\n      </p>\n      <ul>\n        <li>\n          The <code>(DECLARE (OPTIMIZE ...))</code> settings\n          must favor <code>SPEED</code> enough and\n          not favor <code>DEBUG</code> too much,\n          for some compiler-dependent meanings of \"enough\" and \"too much\".\n          (For instance, in SBCL, you should avoid <code>(SPEED 0)</code>\n          and <code>(DEBUG 3)</code> to achieve proper tail calls.)\n        </li>\n        <li>\n          There should not be dynamic bindings around the call\n          (even though some Scheme compilers are able to properly treat\n          such dynamic bindings, called parameters in Scheme parlance).\n        </li>\n      </ul>\n      <p>\n        For compatibility with all compilers and optimization settings,\n        and to avoid stack overflow when debugging,\n        you should prefer iteration or the built in mapping functions\n        to relying on proper tail calls.\n      </p>\n      <p>\n        If you do rely on proper tail calls,\n        you must prominently document the fact,\n        and take appropriate measures to ensure an appropriate compiler is used\n        with appropriate optimization settings.\n        For fully portable code, you may have to use trampolines instead.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Special variables\">\n    <SUMMARY>\n      Use special variables sparingly.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Using Lisp \"special\" (dynamically bound) variables\n        as implicit arguments to functions should be used sparingly,\n        and only in cases where it won't surprise the person reading the code,\n        and where it offers significant benefits.\n      </p>\n      <p>\n        Indeed, each special variable constitutes state.\n        Developers have to mentally track the state of all relevant variables\n        when trying to understand what the code does and how it does it;\n        tests have to be written and run with all relevant combinations;\n        to isolate some activity, care has to be taken to locally bind\n        all relevant variables, including those of indirectly used modules.\n        They can hide precious information from being printed in a backtrace.\n        Not only is there overhead associated to each new variable,\n        but interactions between variables\n        can make the code exponentially more complex\n        as the number of such variables increases.\n        The benefits have to match the costs.\n      </p>\n      <p>\n        Note though that a Lisp special variable is not a global variable\n        in the sense of a global variable in, say, BASIC or C.\n        As special variables can be dynamically bound to a local value,\n        they are much more powerful than\n        global value cells where all users necessarily interfere with each other.\n      </p>\n      <p>\n        Good candidates for such special variables\n        are items for which \"the current\" can be naturally used as prefix,\n        such as \"the current database connection\" or\n        \"the current business data source\".\n        They are singletons as far as the rest of the code is concerned,\n        and often passing them as an explicit argument\n        does not add anything to the readability or maintainability\n        of the source code in question.\n      </p>\n      <p>\n        They can make it easier to write code that can be refactored.\n        If you have a request processing chain,\n        with a number of layers that all operate upon a \"current\" request,\n        passing the request object explicitly to every function\n        requires that every function in the chain have a request argument.\n        Factoring out code into new functions often requires\n        that these functions also have this argument,\n        which clutters the code with boilerplate.\n      </p>\n      <p>\n        You should treat special variables\n        as though they are per-thread variables.\n        By default, you should leave a special variable\n        with no top-level binding at all,\n        and each thread of control\n        that needs the variable should bind it explicitly.\n        This will mean that any incorrect use of the variable\n        will result in an \"unbound variable\" error, and\n        each thread will see its own value for the variable.\n        Variables with a default global value should usually be\n        locally bound at thread creation time.\n        You should use suitable infrastructure\n        to automate the appropriate declaration of such variables.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Assignment\">\n    <SUMMARY>\n      Be consistent in assignment forms.\n    </SUMMARY>\n    <BODY>\n      <p>\n        There are several styles for dealing with assignment and side-effects;\n        whichever a given package is using,\n        keep using the same consistently when hacking said package.\n        Pick a style that makes sense when starting a new package.\n      </p>\n      <p>\n        Regarding multiple assignment in a same form, there are two schools:\n        the first style groups as many assignments as possible into a single\n        <code>SETF</code> or <code>PSETF</code> form\n        thus minimizing the number of forms with side-effects;\n        the second style splits assignments into as many individual\n        <code>SETF</code> (or <code>SETQ</code>, see below) forms as possible,\n        to maximize the chances of locating forms that modify a kind of place\n        by grepping for <code>(setf (foo ...</code>.\n        A grep pattern must actually contain as many place-modifying forms\n        as you may use in your programs, which may make this rationale either\n        convincing or moot depending on the rest of the style of your code.\n        You should follow the convention used in the package you are hacking.\n        We recommend the first convention for new packages.\n      </p>\n      <p>\n        Regarding <code>SETF</code> and <code>SETQ</code>,\n        there are two schools:\n        this first regards <code>SETQ</code>\n        as an archaic implementation detail,\n        and avoids it entirely in favor of <code>SETF</code>;\n        the second regards <code>SETF</code>\n        as an additional layer of complexity,\n        and avoids it in favor of <code>SETQ</code> whenever possible\n        (i.e. whenever the assigned place is a variable or symbol-macro).\n        You should follow the convention used in the package you are hacking.\n        We recommend the first convention for new packages.\n      </p>\n      <p>\n        In the spirit of a mostly pure functional style,\n        which makes testing and maintenance easier,\n        we invite you to consider how to do things with the fewest assignments required.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Assertions and Conditions\">\n    <SUMMARY>\n      You must make proper usage of assertions and conditions.\n    </SUMMARY>\n    <BODY>\n      <ul>\n        <li>\n          <code>ASSERT</code> should be used ONLY to detect internal bugs.\n          Code should <code>ASSERT</code> invariants whose failure indicates\n          that the software is itself broken.\n          Incorrect input should be handled properly at runtime,\n          and must not cause an assertion violation.\n          The audience for an <code>ASSERT</code> failure is a developer.\n          Do not use the data-form and argument-form in <code>ASSERT</code>\n          to specify a condition to signal.\n          It's fine to use them to print out a message for debugging purposes\n          (and since it's only for debugging, there's no issue of\n          internationalization).\n        </li>\n        <li>\n          <code>CHECK-TYPE</code>,\n          <code>ETYPECASE</code> are also forms of assertion.\n          When one of these fails, that's a detected bug.\n          You should prefer to use <code>CHECK-TYPE</code>\n          over (DECLARE (TYPE ...))\n          for the inputs of functions.\n        </li>\n        <li>\n          Your code should use assertions and type checks liberally.\n          The sooner a bug is discovered, the better!\n          Only code in the critical path for performance\n          and internal helpers should eschew\n          explicit assertions and type checks.\n        </li>\n        <li>\n          Invalid input, such as files that are read\n          but do not conform to the expected format,\n          should not be treated as assertion violations.\n          Always check to make sure that input is valid,\n          and take appropriate action if it is not,\n          such as signalling a real error.\n        </li>\n        <li>\n          <code>ERROR</code> should be used\n          to detect problems with user data, requests, permissions, etc.,\n          or to report \"unusual outcomes\" to the caller.\n        </li>\n        <li>\n          <code>ERROR</code> should always be called\n          with an explicit condition type;\n          it should never simply be called with a string.\n          This enables internationalization.\n        </li>\n        <li>\n          Functions that report unusual outcomes\n          by signaling a condition should say so explicitly in their contracts\n          (their textual descriptions, in documentation and docstrings etc.).\n          When a function signals a condition\n          that is not specified by its contract, that's a bug.\n          The contract should specify the condition class(es) clearly.\n          The function may then signal any condition\n          that is a type-of any of those conditions.\n          That is, signaling instances of subclasses\n          of the documented condition classes is fine.\n        </li>\n        <li>\n          Complex bug-checks may need to use <code>ERROR</code>\n          instead of <code>ASSERT</code>.\n          \n        </li>\n        <li>\n          When writing a server, you must not call <code>WARN</code>.\n          Instead, you should use the appropriate logging framework.\n          \n        </li>\n        <li>\n          Code must not call <code>SIGNAL</code>.\n          Instead, use <code>ERROR</code> or <code>ASSERT</code>.\n        </li>\n        <li>\n          Code should not use <code>THROW</code> and <code>CATCH</code>;\n          instead use the <code>restart</code> facility.\n        </li>\n        <li>\n          Code should not generically handle all conditions,\n          e.g. type <code>T</code>, or use <code>IGNORE-ERRORS</code>.\n          Instead, let unknown conditions propagate to\n          the standard ultimate handler for processing.\n          \n        </li>\n        <li>\n          There are a few places where handling all conditions is appropriate,\n          but they are rare.\n          The problem is that handling all conditions can mask program bugs.\n          If you <em>do</em> need to handle \"all conditions\",\n          you MUST handle only <code>ERROR</code>, <em>not</em> <code>T</code>\n          and not <code>SERIOUS-CONDITION</code>.\n          (This is notably because CCL's process shutdown\n          depends on being able to signal <code>process-reset</code>\n          and have it handled by CCL's handler,\n          so we must not interpose our own handler.)\n        </li>\n        <li>\n          <code>(error (make-condition 'foo-error ...))</code>\n          is equivalent to <code>(error 'foo-error ...)</code> —\n          code must use the shorter form.\n        </li>\n        <li>\n          Code should not signal conditions from inside the cleanup form of\n          <code>UNWIND-PROTECT</code>\n          (unless they are always handled inside the cleanup form),\n          or otherwise do non-local exits from cleanup handlers\n          outside of the handler e.g. <code>INVOKE-RESTART</code>.\n        </li>\n        <li>\n          Do not clean up by resignaling.\n          If you do that, and the condition is not handled,\n          the stack trace will halt at the point of the resignal,\n          hiding the rest.\n          And the rest is the part we really care about!\n          <BAD_CODE_SNIPPET>\n            ;; Bad\n            (handler-case\n              (catch 'ticket-at\n                (etd-process-blocks))\n              (error (c)\n                (reset-parser-values)\n                  (error c)))\n          </BAD_CODE_SNIPPET>\n          <CODE_SNIPPET>\n            ;; Better\n            (unwind-protect\n              (catch 'ticket-at\n                (etd-process-blocks))\n              (reset-parser-values))\n          </CODE_SNIPPET>\n        </li>\n      </ul>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Type Checking\">\n    <SUMMARY>\n      If you know the type of something, you should make it explicit\n      in order to enable compile-time and run-time sanity-checking.\n    </SUMMARY>\n    <BODY>\n      \n      <p>\n        If your function is using a special variable as an implicit argument,\n        it's good to put in a <code>CHECK-TYPE</code> for the special variable,\n        for two reasons:\n        to clue in the person reading the code\n        that this variable is being used implicitly as an argument,\n        and also to help detect bugs.\n      </p>\n      \n      <p>\n        Using <code>(declare (type ...))</code>\n        is the least-desirable mechanism to use\n        because, as Scott McKay puts it:\n      </p>\n      <blockquote>\n        <p>\n          The fact is, <code>(declare (type ...))</code> does different things\n          depending on the compiler settings of speed, safety, etc.\n          In some compilers, when speed is greater than safety,\n          <code>(declare (type ...))</code> will tell the compiler\n          \"please assume that these variables have these types\"\n          <em>without</em> generating any type-checks.\n          That is, if some variable has the value <code>1432</code> in it,\n          and you declare it to be of type <code>string</code>,\n          the compiler might just go ahead and use it as though it's a string.\n        </p>\n        <p>\n          Moral: don't use <code>(declare (type ...))</code>\n          to declare the contract of any API functions,\n          it's not the right thing.\n          Sure, use it for \"helper\" functions, but not API functions.\n        </p>\n      </blockquote>\n      <p>\n        You should, of course, use appropriate declarations\n        in internal low-level functions\n        where these declarations are used for optimization.\n        When you do, however, see our recommendations for\n        <a href=\"#Unsafe_Operations\">Unsafe Operations</a>.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"CLOS\">\n    <SUMMARY>\n      Use CLOS appropriately.\n    </SUMMARY>\n    <BODY>\n      <p>\n        When a generic function is intended to be called from other\n        modules (other parts of the code), there should be an\n        explicit <code>DEFGENERIC</code> form,\n        with a <code>:DOCUMENTATION</code> string\n        explaining the generic contract of the function\n        (as opposed to its behavior for some specific class).\n        It's generally good to do explicit <code>DEFGENERIC</code> forms,\n        but for module entry points it is mandatory.\n      </p>\n      <p>\n        When the argument list of a generic function includes\n        <code>&amp;KEY</code>,\n        the <code>DEFGENERIC</code> should always explicitly list\n        all of the keyword arguments that are acceptable,\n        and explain what they mean.\n        (Common Lisp does not require this, but it is good form,\n        and it may avoid spurious warnings on SBCL.)\n      </p>\n      <p>\n        You should avoid <code>SLOT-VALUE</code> and <code>WITH-SLOTS</code>,\n        unless you absolutely intend to circumvent\n        any sort of method combination that might be in effect for the slot.\n        Rare exceptions include <code>INITIALIZE-INSTANCE</code>\n        and <code>PRINT-OBJECT</code> methods and\n        accessing normally hidden slots in the low-level implementation of\n        methods that provide user-visible abstractions.\n        Otherwise, you should use accessors,\n        <code>WITH-ACCESSORS</code>\n      </p>\n      \n      <p>\n        Accessor names generally follow a convention of\n        <code>&lt;protocol-name&gt;-&lt;slot-name&gt;</code>,\n        where a \"protocol\" in this case loosely indicates\n        a set of functions with well-defined behavior.\n      </p>\n      <p>\n        No implication of a formal \"protocol\" concept is necessarily intended,\n        much less first-class \"protocol\" objects.\n        However, there may indeed be an abstract CLOS class\n        or an\n        <a href=\"https://common-lisp.net/~frideau/lil-ilc2012/lil-ilc2012.html\">Interface-Passing Style</a> interface\n        that embodies the protocol.\n        Further (sub)classes or (sub)interfaces may then implement\n        all or part of a protocol by defining\n        some methods for (generic) functions in the protocol,\n        including readers and writers.\n      </p>\n      <p>\n        For example, if there were a notional protocol called\n        is <code>pnr</code> with accessors <code>pnr-segments</code>\n        and <code>pnr-passengers</code>, then\n        the classes <code>air-pnr</code>, <code>hotel-pnr</code> and\n        <code>car-pnr</code> could each reasonably implement\n        methods for <code>pnr-segments</code> and <code>pnr-passengers</code>\n        as accessors.\n      </p>\n      <p>\n        By default, an abstract base class name is used\n        as the notional protocol name, so accessor names default\n        to <code>&lt;class-name&gt;-&lt;slot-name&gt;</code>;\n        while such names are thus quite prevalent,\n        this form is neither required nor even preferred.\n        In general, it contributes to \"symbol bloat\",\n        and in many cases has led to a proliferation of \"trampoline\" methods.\n      </p>\n      <p>\n        Accessors named <code>&lt;slot-name&gt;-of</code> should not be used.\n      </p>\n      <p>\n        Explicit <code>DEFGENERIC</code> forms should be used when there are\n        (or it is anticipated that there will be)\n        more than one <code>DEFMETHOD</code> for that generic function.\n        The reason is that the documentation for the generic function\n        explains the abstract contract for the function,\n        as opposed to explaining what an individual method does for\n        some specific class(es).\n      </p>\n      <p>\n        You must not use generic functions where there is no notional protocol.\n        To put it more concretely,\n        if you have more than one generic function that specializes its Nth argument,\n        the specializing classes should all be descendants of a single class.\n        Generic functions must not be used for \"overloading\",\n        i.e. simply to use the same name for two entirely unrelated types.\n      </p>\n      <p>\n        More precisely, it's not really\n        whether they descend from a common superclass,\n        but whether they obey the same \"protocol\".\n        That is, the two classes should handle the same set of generic functions,\n        as if there were an explicit <code>DEFGENERIC</code> for each method.\n      </p>\n      <p>\n        Here's another way to put it.\n        Suppose you have two classes, A and B, and a generic function F.\n        There are two methods for F,\n        which dispatch on an argument being of types A and B.\n        Is it plausible that there might be a function call somewhere\n        in the program that calls F,\n        in which the argument might sometimes, at runtime,\n        be of class A and other times be of class B?\n        If not, you probably are overloading and\n        should not be using a single generic function.\n      </p>\n      <p>\n        We allow one exception to this rule:\n        it's OK to do overloading\n        if the corresponding argument \"means\" the same thing.\n        Typically one overloading allows an X object,\n        and the other allows the name of an X object,\n        which might be a symbol or something.\n      </p>\n      <p>\n        You must not use MOP \"intercessory\" operations at runtime.\n        You should not use MOP \"intercessory\" operations at compile-time.\n        At runtime, they are at worst a danger, at best a performance issue.\n        At compile-time, it is usually cleaner that\n        macros should set things up the right way in one pass\n        than have to require a second pass of fixups through intercession;\n        but sometimes, fixups are necessary to resolve forward references,\n        and intercession is allowed then.\n        MOP intercession is a great tool for interactive development,\n        and you may enjoy it while developping and debugging;\n        but you should not use it in normal applications.\n      </p>\n      <p>\n        If a class definition creates a method\n        as a <code>:READER</code>, <code>:WRITER</code>,\n        or <code>:ACCESSOR</code>,\n        do not redefine that method.\n        It's OK to add <code>:BEFORE</code>, <code>:AFTER</code>,\n        and <code>:AROUND</code> methods,\n        but don't override the primary method.\n      </p>\n      <p>\n        In methods with keyword arguments,\n        you must always use <code>&amp;KEY</code>,\n        even if the method does not care about the values of any keys,\n        and you should never use <code>&amp;ALLOW-OTHER-KEYS</code>.\n        As long as a keyword is accepted by any method of a generic function,\n        it's OK to use it in the generic function,\n        even if the other methods of the same generic function\n        don't mention it explicitly.\n        This is particularly important\n        for <code>INITIALIZE-INSTANCE</code> methods,\n        since if you did use <code>&amp;ALLOW-OTHER-KEYS</code>,\n        it would disable error checking for misspelled or wrong keywords\n        in <code>MAKE-INSTANCE</code> calls!\n      </p>\n      \n      <p>\n        A typical <code>PRINT-OBJECT</code> method might look like this:\n      </p>\n      <CODE_SNIPPET>\n        (defmethod print-object ((p person) stream)\n          (print-unreadable-object (p stream :type t :identity t)\n            (with-slots (first-name last-name) p\n              (safe-format stream \"~a ~a\" first-name last-name))))\n      </CODE_SNIPPET>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Meta-language guidelines\">\n  <STYLEPOINT title=\"Macros\">\n    <SUMMARY>\n      Use macros when appropriate, which is often.\n      Define macros when appropriate, which is seldom.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Macros bring syntactic abstraction, which is a wonderful thing.\n        It helps make your code clearer, by describing your intent\n        without getting bogged in implementation details\n        (indeed abstracting those details away).\n        It helps make your code more concise and more readable,\n        by eliminating both redundancy and irrelevant details.\n        But it comes at a cost to the reader,\n        which is learning a new syntactic concept for each macro.\n        And so it should not be abused.\n      </p>\n      <p>\n        The general conclusion is that there shouldn't be\n        any recognizable <em>design pattern</em>\n        in a good Common Lisp program.\n        The one and only pattern is: <em>use the language</em>,\n        which includes defining and using syntactic abstractions.\n      </p>\n      <p>\n        Existing macros must be used\n        whenever they make code clearer\n        by conveying intent in a more concise way,\n        which is often.\n        When a macro is available in your project\n        that expresses the concept you're using,\n        you must not write the expansion rather than use the macro.\n      </p>\n      <p>\n        New macros should be defined as appropriate,\n        which should be seldom,\n        for common macros have already been provided\n        by the language and its various libraries,\n        and your program typically only needs few new ones\n        relative to its size.\n      </p>\n      <p>\n        You should follow the OAOOM rule of thumb\n        for deciding when to create a new abstraction,\n        whether syntactic or not:\n        if a particular pattern is used more than twice,\n        it should probably be abstracted away.\n        A more refined rule to decide when to use abstraction\n        should take into account\n        the benefit in term of number of uses and gain at each use,\n        to the costs in term of having to get used to reading the code.\n        For syntactic abstractions, costs and benefits to the reader\n        is usually more important than costs and benefits to the writer,\n        because good code is usually written once\n        and read many times by many people\n        (including the same programmer\n        who has to maintain the program after having forgotten it).\n        Yet the cost to the writer of the macro\n        should also be taken into account;\n        however, in doing so it should rather be compared\n        to the cost of the programmer writing other code instead\n        that may have higher benefits.\n      </p>\n      <p>\n        Using Lisp macros properly requires taste.\n        Avoid writing complicated macros\n        unless the benefit clearly outweighs the cost.\n        It takes more effort for your fellow developers to learn your macro,\n        so you should only use a macro if the gain in expressiveness\n        is big enough to justify that cost.\n        As usual, feel free to consult your colleagues if you're not sure,\n        since without a lot of Lisp experience,\n        it can be hard to make this judgment.\n      </p>\n      <p>\n        You must never use a macro where a function will do.\n        That is, if the semantics of what you are writing\n        conforms to the semantics of a function,\n        then you must write it as a function rather than a macro.\n      </p>\n      <p>\n        You must not transform a function into a macro for performance reasons.\n        If profiling shows that you have a performance problem\n        with a specific function <code>FOO</code>,\n        document the need and profiling-results appropriately,\n        and\n        <code>(declaim (inline foo))</code>.\n      </p>\n      \n      <p>\n        You can also use a compiler-macro\n        as a way to speed up function execution\n        by specifying a source-to-source transformation.\n        Beware that it interferes with tracing the optimized function.\n      </p>\n      <p>\n        When you write a macro-defining macro\n        (a macro that generates macros),\n        document and comment it particularly clearly,\n        since these are harder to understand.\n      </p>\n      <p>\n        You must not install new reader macros\n        without a consensus among the developers of your system.\n        Reader macros must not leak out of the system that uses them\n        to clients of that system or other systems used in the same project.\n        You must use software such as\n        <code>cl-syntax</code> or <code>named-readtables</code>\n        to control how reader macros are used.\n        This clients who desire it may use the same reader macros as you do.\n        In any case, your system must be usable\n        even to clients who do not use these reader macros.\n      </p>\n      <p>\n        If your macro has a parameter that is a Lisp form\n        that will be evaluated when the expanded code is run,\n        you should name the parameter with the suffix <code>-form</code>.\n        This convention helps make it clearer to the macro's user\n        which parameters are Lisp forms to be evaluated, and which are not.\n        The common names <code>body</code> and <code>end</code> are\n        exceptions to this rule.\n      </p>\n      <p>\n        You should follow the so-called <code>CALL-WITH</code> style when it applies.\n        This style is explained at length in\n        <a href=\"http://random-state.net/log/3390120648.html\">http://random-state.net/log/3390120648.html</a>.\n        The general principle is that the macro is strictly limited to processing the syntax,\n        and as much of the semantics as possible is kept in normal functions.\n        Therefore, a macro <code>WITH-<em>FOO</em></code> is often limited to\n        generating a call to an auxiliary function\n        <code>CALL-WITH-<em>FOO</em></code>\n        with arguments deduced from the macro arguments.\n        Macro <code>&amp;body</code> arguments are typically\n        wrapped into a lambda expression of which they become the body,\n        which is passed as one of the arguments of the auxiliary function.\n      </p>\n      <p>\n        The separation of syntactic and semantic concerns\n        is a general principle of style that applies\n        beyond the case of <code>WITH-</code> macros.\n        Its advantages are many.\n        By keeping semantics outside the macro,\n        the macro is made simpler, easier to get right, and less subject to change,\n        which makes it easier to develop and maintain.\n        The semantics is written in a simpler language — one without staging —\n        which also makes it easier to develop and maintain.\n        It becomes possible to debug and update the semantic function\n        without having to recompile all clients of the macro.\n        The semantic function appears in the stack trace\n        which also helps debug client functions.\n        The macro expansion is made shorter and\n        each expansion shares more code with other expansions,\n        which reduces memory pressure which in turn usually makes things faster.\n        It also makes sense to write the semantic functions first,\n        and write the macros last as syntactic sugar on top.\n        You should use this style unless the macro is used\n        in tight loops where performance matters;\n        and even then, see our rules regarding optimization.\n      </p>\n      <p>\n        Any functions (closures) created by the macro should be named,\n        which can be done using <code>FLET</code>.\n        \n        This also allows you to declare the function to be of dynamic extent\n        (if it is — and often it is; yet see below regarding\n        <a href=\"#DYNAMIC-EXTENT\">DYNAMIC-EXTENT</a>).\n      </p>\n      <p>\n        If a macro call contains a form,\n        and the macro expansion includes more than one copy of that form,\n        the form can be evaluated more than once,\n        and code it contains macro-expanded and compiled more than once.\n        If someone uses the macro and calls it\n        with a form that has side effects or that takes a long time to compute,\n        the behavior will be undesirable\n        (unless you're intentionally writing\n        a control structure such as a loop).\n        A convenient way to avoid this problem\n        is to evaluate the form only once,\n        and bind a (generated) variable to the result.\n        There is a very useful macro called <code>ALEXANDRIA:ONCE-ONLY</code>\n        that generates code to do this.\n        See also <code>ALEXANDRIA:WITH-GENSYMS</code>,\n        to make some temporary variables in the generated code.\n        Note that if you follow our <code>CALL-WITH</code> style,\n        you typically expand the code only once, as either\n        an argument to the auxiliary function, or\n        the body of a lambda passed as argument to it;\n        you therefore avoid the above complexity.\n      </p>\n      <p>\n        When you write a macro with a body,\n        such as a <code>WITH-xxx</code> macro,\n        even if there aren't any parameters,\n        you should leave space for them anyway.\n        For example, if you invent <code>WITH-LIGHTS-ON</code>,\n        do not make the call to it look like\n        <code>(defmacro with-lights-on (&amp;body b) ...)</code>.\n        Instead, do <code>(defmacro with-lights-on (() &amp;body b) ...)</code>.\n        That way, if parameters are needed in the future,\n        you can add them without necessarily having to change\n        all the uses of the macro.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"EVAL-WHEN\">\n    <SUMMARY>\n      When using <code>EVAL-WHEN</code>, you should almost always use all of\n      <code>(:compile-toplevel :load-toplevel :execute)</code>.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Lisp evaluation happens at several times,\n        some of them interleaved.\n        Be aware of them when writing macros.\n        <a href=\"https://fare.livejournal.com/146698.html\">EVAL-WHEN considered harmful to your mental health</a>.\n      </p>\n      <p>\n        In summary of the article linked above,\n        unless you're doing truly advanced macrology,\n        the only valid combination in an <code>EVAL-WHEN</code>\n        is to include all of\n        <code>(eval-when (:compile-toplevel :load-toplevel :execute) ...)</code>\n      </p>\n      <p>\n        You must use\n        <code>(eval-when (:compile-toplevel :load-toplevel :execute) ...)</code>\n        whenever you define functions, types, classes, constants, variables, etc.,\n        that are going to be used in macros.\n      </p>\n      <p>\n        It is usually an error to omit the <code>:execute</code>,\n        because it prevents <code>LOAD</code>ing the source rather than the fasl.\n        It is usually an error to omit the <code>:load-toplevel</code>\n        (except to modify e.g. readtables and compile-time settings),\n        because it prevents <code>LOAD</code>ing future files\n        or interactively compiling code\n        that depends on the effects that happen at compile-time,\n        unless the current file was <code>COMPILE-FILE</code>d\n        within the same Lisp session.\n      </p>\n      <p>\n        Regarding variables, note that because macros may or may not\n        be expanded in the same process that runs the expanded code,\n        you must not depend on compile-time and runtime effects\n        being either visible or invisible at the other time.\n        There are still valid uses of variables in macros:\n      </p>\n      <ul>\n        <li>\n          Some variables may hold dictionaries\n          for some new kind of definition and other meta-data.\n          If such meta-data is to be visible at runtime and/or in other files,\n          you must make sure that the macro expands into code that\n          will register the definitions to those meta-data structures\n          at load-time,\n          in addition to effecting the registration at compile-time.\n          Typically, your top-level definitions expand\n          to code that does the registration.\n          if your code doesn't expand at the top-level,\n          you can sometimes use <code>LOAD-TIME-VALUE</code> for good effect.\n          In extreme cases, you may have to use\n          <code>ASDF-FINALIZERS:EVAL-AT-TOPLEVEL</code>.\n        </li>\n        <li>\n          Some variables may hold temporary data\n          that is only used at compile-time in the same file,\n          and can be cleaned up at the end of the file's compilation.\n          Predefined such variables would include <code>*readtable*</code>\n          or compiler-internal variables holding\n          the current optimization settings.\n          You can often manage existing and new such variables using\n          the <code>:AROUND-COMPILE</code> hooks of <code>ASDF</code>.\n        </li>\n      </ul>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Read-time evaluation\">\n    <SUMMARY>\n      You should use <code>#.</code> sparingly,\n      and you must avoid read-time side-effects.\n    </SUMMARY>\n    <BODY>\n      <p>\n        The <code>#.</code> standard read-macro\n        will read one object, evaluate the object, and\n        have the reader return the resulting value.\n      </p>\n      <p>\n        You must not use it where other idioms will do, such as\n        using <code>EVAL-WHEN</code> to evaluate side-effects at compile-time,\n        using a regular macro to return an expression computed at compile-time,\n        using <code>LOAD-TIME-VALUE</code> to compute it at load-time.\n      </p>\n      <p>\n        Read-time evaluation is often used as a quick way\n        to get something evaluated at compile time\n        (actually \"read time\" but it amounts to the same thing).\n        If you use this, the evaluation MUST NOT have any side effects\n        and MUST NOT depend on any variable global state.\n        The <code>#.</code> should be treated as a way\n        to force \"constant-folding\"\n        that a sufficiently-clever compiler\n        could have figure out all by itself,\n        when the compiler isn't sufficiently-clever\n        and the difference matters.\n      </p>\n      <p>\n        Another use of <code>#.</code> is to expand the equivalent of macros\n        in places that are neither expressions nor (quasi)quotations,\n        such as lambda-lists. However, if you find yourself using it a lot,\n        it might be time to instead define macros to replace your consumers\n        of lambda-lists with something that recognizes an extension.\n      </p>\n      <p>\n        Whenever you are going to use <code>#.</code>,\n        you should consider using <code>DEFCONSTANT</code> and its variants,\n        possibly in an <code>EVAL-WHEN</code>,\n        to give the value a name explaining what it means.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"EVAL\">\n    <SUMMARY>\n      You must not use <code>EVAL</code> at runtime.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Places where it is actually appropriate to use <code>EVAL</code>\n        are so few and far between that you must consult with your reviewers;\n        it's easily misused.\n      </p>\n      <p>\n        If your code manipulates symbols at runtime\n        and needs to get the value of a symbol,\n        use <code>SYMBOL-VALUE</code>, not <code>EVAL</code>.\n      </p>\n      <p>\n        Often, what you really need is to write a macro,\n        not to use <code>EVAL</code>.\n      </p>\n      <p>\n        You may be tempted to use <code>EVAL</code> as a shortcut\n        to evaluating expressions in a safe subset of the language.\n        But it often requires more scrutiny to properly check and sanitize\n        all possible inputs to such use of <code>EVAL</code>\n        than to build a special-purpose evaluator.\n        You must not use <code>EVAL</code> in this way at runtime.\n      </p>\n      <p>\n        Places where it is OK to use <code>EVAL</code> are:\n      </p>\n      <ul>\n        <li>\n          The implementation of an interactive development tool.\n        </li>\n        <li>\n          The build infrastructure.\n        </li>\n        <li>\n          Backdoors that are part of testing frameworks.\n          (You MUST NOT have such backdoors in production code.)\n        </li>\n        <li>\n          Macros that fold constants at compile-time.\n        </li>\n        <li>\n          Macros that register definitions to meta-data structures;\n          the registration form is sometimes evaluated at compile-time\n          as well as included in the macro-expansion,\n          so it is immediately available to other macros.\n        </li>\n      </ul>\n      <p>\n        Note that in the latter case,\n        if the macro isn't going to be used at the top-level,\n        it might not be possible to make these definitions available\n        as part of the expansion.\n        The same phenomenon may happen in a <code>DEFTYPE</code> expansion,\n        or in helper functions used by macros.\n        In these cases, you may actually have to use\n        <code>ASDF-FINALIZERS:EVAL-AT-TOPLEVEL</code> in your macro.\n        It will not only <code>EVAL</code> your definitions\n        at macro-expansion time for immediate availability,\n        it will also save the form aside, for inclusion in a\n        <code>(ASDF-FINALIZERS:FINAL-FORMS)</code>\n        that you need to include at the end of the file being compiled\n        (or before the form is needed).\n        This way, the side-effects are present when loading the fasl\n        without having compiled it as well as while compiling it;\n        in either case, the form is made available at load-time.\n        <code>ASDF-FINALIZERS</code> ensures that the form is present,\n        by throwing an error if you omit it.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"INTERN and UNINTERN\">\n    <SUMMARY>\n      You must not use <code>INTERN</code> or <code>UNINTERN</code> at runtime.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You must not use <code>INTERN</code> at runtime.\n        Not only does it cons,\n        it either creates a permanent symbol that won't be collected\n        or gives access to internal symbols.\n        This creates opportunities for memory leaks, denial of service attacks,\n        unauthorized access to internals, clashes with other symbols.\n      </p>\n      <p>\n        You must not <code>INTERN</code> a string\n        just to compare it to a keyword;\n        use <code>STRING=</code> or <code>STRING-EQUAL</code>.\n      </p>\n      <BAD_CODE_SNIPPET>\n        (member (intern str :keyword) $keys) ; Bad\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (member str $keys :test #'string-equal) ; Better\n      </CODE_SNIPPET>\n      <p>\n        You must not use <code>UNINTERN</code> at runtime.\n        It can break code that relies on dynamic binding.\n        It makes things harder to debug.\n        You must not dynamically intern any new symbol,\n        and therefore you need not dynamically unintern anything.\n      </p>\n      <p>\n        You may of course use <code>INTERN</code> at compile-time,\n        in the implementation of some macros.\n        Even so, it is usually more appropriate\n        to use abstractions on top of it, such as\n        <code>ALEXANDRIA:SYMBOLICATE</code> or\n        <code>ALEXANDRIA:FORMAT-SYMBOL</code>\n        to create the symbols you need.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Data Representation\">\n  <STYLEPOINT title=\"NIL: empty-list, false and I Don't Know\">\n    <SUMMARY>\n      Appropriately use or avoid using <code>NIL</code>.\n    </SUMMARY>\n    <BODY>\n      <p>\n        <code>NIL</code> can have several different interpretations:\n      </p>\n      <ul>\n        <li>\n          \"False.\"\n          In this case, use <code>NIL</code>.\n          You should test for false <code>NIL</code>\n          using the operator <code>NOT</code> or\n          using the predicate function <code>NULL</code>.\n        </li>\n        <li>\n          \"Empty-list.\"\n          In this case, use <code>'()</code>.\n          (Be careful about quoting the empty-list when calling macros.)\n          You should use <code>ENDP</code> to test for the empty list\n          when the argument is known to be a proper list,\n          or with <code>NULL</code> otherwise.\n        </li>\n        <li>\n          A statement about some value being unspecified.\n          In this case, you may use <code>NIL</code>\n          if there is no risk of ambiguity anywhere in your code;\n          otherwise you should use an explicit, descriptive symbol.\n        </li>\n        <li>\n          A statement about some value being known not to exist.\n          In this case, you should use an explicit, descriptive symbol\n          instead of <code>NIL</code>.\n        </li>\n      </ul>\n      <p>\n        You must not introduce ambiguity in your data representations\n        that will cause headaches for whoever has to debug code.\n        If there is any risk of ambiguity,\n        you should use an explicit, descriptive symbol or keyword\n        for each case,\n        instead of using <code>NIL</code> for either.\n        If you do use <code>NIL</code>,\n        you must make sure that the distinction is well documented.\n      </p>\n      <p>\n        In many contexts,\n        instead of representing \"I don't know\" as a particular value,\n        you should instead use multiple values,\n        one for the value that is known if any,\n        and one to denote whether the value was known or found.\n      </p>\n      \n      <p>\n        When working with database classes, keep in mind that\n        <code>NIL</code> need not always map to <code>'NULL'</code>\n        (and vice-versa)!\n        The needs of the database may differ from the needs of the Lisp.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Do not abuse lists\">\n    <SUMMARY>\n      You must select proper data representation.\n      You must not abuse the <code>LIST</code> data structure.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Even though back in 1958, LISP was short for \"LISt Processing\",\n        its successor Common Lisp has been a modern programming language\n        with modern data structures since the 1980s.\n        You must use the proper data structures in your programs.\n      </p>\n      <p>\n        You must not abuse the builtin (single-linked) <code>LIST</code>\n        data structure where it is not appropriate,\n        even though Common Lisp makes it especially easy to use it.\n      </p>\n      <p>\n        You must only use lists\n        when their performance characteristics\n        is appropriate for the algorithm at hand:\n        sequential iteration over the entire contents of the list.\n      </p>\n      <p>\n        An exception where it is appropriate to use lists\n        is when it is known in advance\n        that the size of the list will remain very short\n        (say, less than 16 elements).\n      </p>\n      <p>\n        List data structures are often (but not always)\n        appropriate for macros and functions used by macros at compile-time:\n        indeed, not only is source code passed as lists in Common Lisp,\n        but the macro-expansion and compilation processes\n        will typically walk over the entire source code, sequentially, once.\n        (Note that advanced macro systems don't directly use lists, but instead\n        use abstract syntax objects that track source code location and scope;\n        however there is no such advanced macro system\n        in Common Lisp at this time.)\n      </p>\n      <p>\n        Another exception where it is appropriate to use lists is\n        for introducing literal constants\n        that will be transformed into more appropriate data structures\n        at compile-time or load-time.\n        It is a good to have a function with a relatively short name\n        to build your program's data structures from such literals.\n      </p>\n      <p>\n        In the many cases when lists are not the appropriate data structure,\n        various libraries such as\n        <a href=\"http://cliki.net/cl-containers\">cl-containers</a> or\n        <a href=\"http://cliki.net/lisp-interface-library\">lisp-interface-library</a>\n        provide plenty of different data structures\n        that should fulfill all the basic needs of your programs.\n        If the existing libraries are not satisfactory, see above about\n        <a href=\"#Using_Libraries\">Using Libraries</a> and\n        <a href=\"#Open-Sourcing_Code\">Open-Sourcing Code</a>.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Lists vs. structures vs. multiple values\">\n    <SUMMARY>\n      You should use the appropriate representation for product types.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should avoid using a list as anything\n        besides a container of elements of like type.\n        You must not use a list as method of passing\n        multiple separate values of different types\n        in and out of function calls.\n        Sometimes it is convenient to use a list\n        as a little ad hoc structure,\n        i.e. \"the first element of the list is a FOO, and the second is a BAR\",\n        but this should be used minimally\n        since it gets harder to remember the little convention.\n        You must only use a list that way\n        when destructuring the list of arguments from a function,\n        or creating a list of arguments\n        to which to <code>APPLY</code> a function.\n      </p>\n      <p>\n        The proper way to pass around an object\n        comprising several values of heterogeneous types\n        is to use a structure as defined by <code>DEFSTRUCT</code>\n        or <code>DEFCLASS</code>.\n      </p>\n      <p>\n        You should use multiple values only\n        when function returns a small number of values\n        that are meant to be destructured immediately by the caller,\n        rather than passed together as arguments to further functions.\n      </p>\n      <p>\n        You should not return a condition object\n        as one of a set of multiple values.\n        Instead, you should signal the condition to denote an unusual outcome.\n      </p>\n      <p>\n        You should signal a condition to denote an unusual outcome,\n        rather than relying on a special return type.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Lists vs. Pairs\">\n    <SUMMARY>\n      Use the appropriate functions when manipulating lists.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Use <code>FIRST</code> to access the first element of a list,\n        <code>SECOND</code> to access the second element, etc.\n        Use <code>REST</code> to access the tail of a list.\n        Use <code>ENDP</code> to test for the end of the list.\n      </p>\n      <p>\n        Use <code>CAR</code> and <code>CDR</code>\n        when the cons cell is not being used to implement a proper list\n        and is instead being treated as a pair of more general objects.\n        Use <code>NULL</code> to test for <code>NIL</code> in this context.\n      </p>\n      <p>\n        The latter case should be rare outside of alists,\n        since you should be using structures and classes where they apply,\n        and data structure libraries when you want trees.\n      </p>\n      <p>\n        Exceptionally, you may use <code>CDADR</code> and other variants\n        on lists when manually destructuring them,\n        instead of using a combination of several list accessor functions.\n        In this context, using <code>CAR</code> and <code>CDR</code>\n        instead of <code>FIRST</code> and <code>REST</code> also makes sense.\n        However, keep in mind that it might be more appropriate in such cases\n        to use higher-level constructs such as\n        <code>DESTRUCTURING-BIND</code> or <code>OPTIMA:MATCH</code>.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Lists vs. Arrays\">\n    <SUMMARY>\n      You should use arrays rather than lists where random access matters.\n    </SUMMARY>\n    <BODY>\n      <p>\n        <code>ELT</code> has <i>O(n)</i> behavior when used on lists.\n        If you are to use random element access on an object,\n        use arrays and <code>AREF</code> instead.\n      </p>\n      <p>\n        The exception is for code outside the critical path\n        where the list is known to be small anyway.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Lists vs. Sets\">\n    <SUMMARY>\n      You should only use lists as sets for very small lists.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Using lists as representations of sets is a bad idea\n        unless you know the lists will be small,\n        for accessors are <i>O(n)</i> instead of <i>O(log n)</i>.\n        For arbitrary big sets, use balanced binary trees,\n        for instance using <code>lisp-interface-library</code>.\n      </p>\n      <p>\n        If you still use lists as sets,\n        you should not <code>UNION</code> lists just to search them.\n      </p>\n      <BAD_CODE_SNIPPET>\n        (member foo (union list-1 list-2)) ; Bad\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (or (member foo list-1) (member foo list-2)) ; Better\n      </CODE_SNIPPET>\n      <p>\n        Indeed, <code>UNION</code> not only conses unnecessarily,\n        but it can be <i>O(n^2)</i> on some implementations,\n        and is rather slow even when it's <i>O(n)</i>.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Proper Forms\">\n  <p>\n    You must follow the proper usage regarding\n    well-known functions, macros and special forms.\n  </p>\n  <STYLEPOINT title=\"Defining Constants\">\n    <SUMMARY>\n      You must use proper defining forms for constant values.\n    </SUMMARY>\n    <BODY>\n      <p>\n        The Lisp system we primarily use, SBCL, is very picky and\n        signals a condition whenever a constant is redefined to a value not\n        <code>EQL</code> to its previous setting.\n        You must not use <code>DEFCONSTANT</code>\n        when defining variables that are not\n        numbers, characters, or symbols (including booleans and keywords).\n        Instead, consistently use whichever alternative\n        is recommended for your project.\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (defconstant +google-url+ \"https://www.google.com/\")\n        (defconstant +valid-colors+ '(red green blue))\n      </BAD_CODE_SNIPPET>\n      \n      \n      \n      \n      <p>\n        Open-Source libraries may use\n        <code>ALEXANDRIA:DEFINE-CONSTANT</code>\n        for constants other than numbers, characters and symbols\n        (including booleans and keywords).\n        You may use the <code>:TEST</code> keyword argument\n        to specify an equality predicate.\n      </p>\n      <CODE_SNIPPET>\n        ;; Better, for Open-Source code:\n        (define-constant +google-url+ \"https://www.google.com/\" :test #'string=)\n        (define-constant +valid-colors+ '(red green blue))\n      </CODE_SNIPPET>\n      <p>\n        Note that with optimizing implementations, such as SBCL or CMUCL,\n        defining constants this way precludes any later redefinition\n        short of <code>UNINTERN</code>ing the symbol\n        and recompiling all its clients.\n        This may make it \"interesting\" to debug things at the REPL\n        or to deploy live code upgrades.\n        If there is a chance that your \"constants\" are not going to be constant\n        over the lifetime of your server processes\n        after taking into consideration scheduled and unscheduled code patches,\n        you should consider using\n        <code>DEFPARAMETER</code> or <code>DEFVAR</code> instead,\n        or possibly a variant of <code>DEFINE-CONSTANT</code>\n        that builds upon some future library implementing global lexicals\n        rather than <code>DEFCONSTANT</code>.\n        You may keep the <code>+plus+</code> convention in these cases\n        to document the intent of the parameter as a constant.\n      </p>\n      <p>\n        Also note that <code>LOAD-TIME-VALUE</code> may help you\n        avoid the need for defined constants.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Defining Functions\">\n    <SUMMARY>\n      You should make proper use of\n      <code>&amp;OPTIONAL</code> and\n      <code>&amp;KEY</code> arguments.\n      You should not use <code>&amp;AUX</code> arguments.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should avoid using <code>&amp;ALLOW-OTHER-KEYS</code>,\n        since it blurs the contract of a function.\n        Almost any real function (generic or not) allows a certain\n        fixed set of keywords, as far as its caller is concerned,\n        and those are part of its contract.\n        If you are implementing a method of a generic function,\n        and it does not need to know\n        the values of some of the keyword arguments,\n        you should explicitly <code>(DECLARE (IGNORE ...))</code>\n        all the arguments that you are not using.\n        You must not use <code>&amp;ALLOW-OTHER-KEYS</code>\n        unless you explicitly want to disable checking of allowed keys\n        for all methods when invoking the generic function on arguments\n        that match this particular method.\n        Note that the contract of a generic function belongs in\n        the <code>DEFGENERIC</code>, not in the <code>DEFMETHOD</code>\n        which is basically an \"implementation detail\" of the generic function\n        as far as the caller of the generic is concerned.\n      </p>\n      <p>\n        A case where <code>&amp;ALLOW-OTHER-KEYS</code> is appropriate\n        is when you write a wrapper function to other some other functions\n        that may vary (within the computation or during development),\n        and pass around a plist as a <code>&amp;REST</code> argument.\n      </p>\n      <p>\n        You should avoid using <code>&amp;AUX</code> arguments.\n      </p>\n      <p>\n        You should avoid having both <code>&amp;OPTIONAL</code>\n        and <code>&amp;KEY</code> arguments,\n        unless it never makes sense to specify keyword arguments\n        when the optional arguments are not all specified.\n        You must not have non-<code>NIL</code> defaults\n        to your <code>&amp;OPTIONAL</code> arguments\n        when your function has both <code>&amp;OPTIONAL</code>\n        and <code>&amp;KEY</code> arguments.\n      </p>\n      <p>\n        For maximum portability of a library, it is good form\n        that <code>DEFMETHOD</code> definitions should\n        <code>(DECLARE (IGNORABLE ...))</code>\n        all the required arguments that they are not using.\n        Indeed, some implementations will issue a warning\n        if you <code>(DECLARE (IGNORE ...))</code> those arguments,\n        whereas other implementations will issue a warning\n        if you fail to <code>(DECLARE (IGNORE ...))</code> them.\n        <code>(DECLARE (IGNORABLE ...))</code> works on all implementations.\n      </p>\n      <p>\n        You should avoid excessive nesting of binding forms inside a function.\n        If your function ends up with massive nesting,\n        you should probably break it up into several functions or macros.\n        If it is really a single conceptual unit,\n        consider using a macro such as <code>FARE-UTILS:NEST</code>\n        to at least reduce the amount of indentation required.\n        It is bad form to use <code>NEST</code> in typical short functions\n        with 4 or fewer levels of nesting,\n        but also bad form not to use it in the exceptional long functions\n        with 10 or more levels of nesting.\n        Use your judgment and consult your reviewers.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Conditional Expressions\">\n    <SUMMARY>\n      Use the appropriate conditional form.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Use <code>WHEN</code> and <code>UNLESS</code>\n        when there is only one alternative.\n        Use <code>IF</code> when there are two alternatives\n        and <code>COND</code> when there are several.\n      </p>\n      <p>\n        However, don't use <code>PROGN</code> for an <code>IF</code> clause\n        — use <code>COND</code>, <code>WHEN</code>, or <code>UNLESS</code>.\n      </p>\n      <p>\n        Note that in Common Lisp,\n        <code>WHEN</code> and <code>UNLESS</code> return <code>NIL</code>\n        when the condition is not met.\n        You may take advantage of it.\n        Nevertheless, you may use an <code>IF</code>\n        to explicitly return <code>NIL</code>\n        if you have a specific reason to insist on the return value.\n        You may similarly include a fall-through clause <code>(t nil)</code>\n        as the last in your <cond>COND</cond>,\n        or <code>(otherwise nil)</code> as the last in your <cond>CASE</cond>,\n        to insist on the fact that the value returned by the conditional matters\n        and that such a case is going to be used.\n        You should omit the fall-through clause\n        when the conditional is used for side-effects.\n      </p>\n      <p>\n        You should prefer <code>AND</code> and <code>OR</code>\n        when it leads to more concise code than using\n        <code>IF</code>, <code>COND</code>,\n        <code>WHEN</code> or <code>UNLESS</code>,\n        and there are no side-effects involved.\n        You may also use an <code>ERROR</code>\n        as a side-effect in the final clause of an <code>OR</code>.\n      </p>\n      <p>\n        You should only use <code>CASE</code> and <code>ECASE</code>\n        to compare numbers, characters or symbols\n        (including booleans and keywords).\n        Indeed, <code>CASE</code> uses <code>EQL</code> for comparisons,\n        so strings, pathnames and structures may not compare the way you expect,\n        and <code>1</code> will differ from <code>1.0</code>.\n      </p>\n      <p>\n        You should use <code>ECASE</code> and <code>ETYPECASE</code>\n        in preference to <code>CASE</code> and <code>TYPECASE</code>.\n        It is better to catch erroneous values early.\n      </p>\n      <p>\n        You should not use <code>CCASE</code> or <code>CTYPECASE</code> at all.\n        At least, you should not use them in server processes,\n        unless you have quite robust error handling infrastructure\n        and make sure not to leak sensitive data this way.\n        These are meant for interactive use,\n        and can cause interesting damage\n        if they cause data or control to leak to attackers.\n      </p>\n      <p>\n        You must not use gratuitous single quotes in <code>CASE</code> forms.\n        This is a common error:\n      </p>\n      <BAD_CODE_SNIPPET>\n        (case x ; Bad: silently returns NIL on mismatch\n          ('bar :bar) ; Bad: catches QUOTE\n          ('baz :baz)) ; Bad: also would catch QUOTE\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (ecase x ; Better: will error on mismatch\n          ((bar) :bar) ; Better: won't match QUOTE\n          ((baz) :baz)) ; Better: same reason\n      </CODE_SNIPPET>\n      <p>\n        <code>'BAR</code> there is <code>(QUOTE BAR)</code>,\n        meaning this leg of the case will be executed\n        if <code>X</code> is <code>QUOTE</code>...\n        and ditto for the second leg\n        (though <code>QUOTE</code> will be caught by the first clause).\n        This is unlikely to be what you really want.\n      </p>\n      <p>\n        In <code>CASE</code> forms,\n        you must use <code>otherwise</code> instead of <code>t</code>\n        when you mean \"execute this clause if the others fail\".\n        You must use <code>((t) ...)</code>\n        when you mean \"match the symbol T\" rather than \"match anything\".\n        You must also use <code>((nil) ...)</code>\n        when you mean \"match the symbol NIL\" rather than \"match nothing\".\n      </p>\n      <p>\n        Therefore, if you want to map booleans <code>NIL</code> and <code>T</code>\n        to respective symbols <code>:BAR</code> and <code>:QUUX</code>,\n        you should avoid the former way and do it the latter way:\n      </p>\n      <BAD_CODE_SNIPPET>\n        (ecase x ; Bad: has no actual error case!\n          (nil :bar)) ; Bad: matches nothing\n          (t :quux)) ; Bad: matches anything\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (ecase x ; Better: will actually catch non-booleans\n          ((nil) :bar)) ; Better: matches NIL\n          ((t) :quux)) ; Better: matches T\n      </CODE_SNIPPET>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Identity, Equality and Comparisons\">\n    <SUMMARY>\n      You should use the appropriate predicates when comparing objects.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Lisp provides four general equality predicates:\n        <code>EQ</code>, <code>EQL</code>, <code>EQUAL</code>,\n        and <code>EQUALP</code>,\n        which subtly vary in semantics.\n        Additionally, Lisp provides the type-specific predicates\n        <code>=</code>, <code>CHAR=</code>, <code>CHAR-EQUAL</code>,\n        <code>STRING=</code>, and <code>STRING-EQUAL</code>.\n        Know the distinction!\n      </p>\n      <p>\n        You should use <code>EQL</code> to compare objects and symbols\n        for <em>identity</em>.\n      </p>\n      <p>\n        You must not use <code>EQ</code> to compare numbers or characters.\n        Two numbers or characters that are <code>EQL</code>\n        are not required by Common Lisp to be <code>EQ</code>.\n      </p>\n      <p>\n        When choosing between <code>EQ</code> and <code>EQL</code>,\n        you should use <code>EQL</code> unless you are writing\n        performance-critical low-level code.\n        <code>EQL</code> reduces the opportunity\n        for a class of embarrassing errors\n        (i.e. if numbers or characters are ever compared).\n        There may a tiny performance cost relative to <code>EQ</code>,\n        although under SBCL, it often compiles away entirely.\n        <code>EQ</code> is equivalent to <code>EQL</code> and type declarations,\n        and use of it for optimization should be treated just like\n        any such <a href=\"#Unsafe_Operations\">unsafe operations</a>.\n      </p>\n      <p>\n        You should use <code>CHAR=</code>\n        for case-dependent character comparisons,\n        and <code>CHAR-EQUAL</code> for case-ignoring character comparisons.\n      </p>\n      <p>\n        You should use <code>STRING=</code>\n        for case-dependent string comparisons,\n        and <code>STRING-EQUAL</code> for case-ignoring string comparisons.\n      </p>\n      <p>\n        A common mistake when using <code>SEARCH</code> on strings\n        is to provide <code>STRING=</code> or <code>STRING-EQUAL</code>\n        as the <code>:TEST</code> function.\n        The <code>:TEST</code> function\n        is given two sequence elements to compare.\n        If the sequences are strings,\n        the <code>:TEST</code> function is called on two characters,\n        so the correct tests are <code>CHAR=</code> or <code>CHAR-EQUAL</code>.\n        If you use <code>STRING=</code> or <code>STRING-EQUAL</code>,\n        the result is what you expect,\n        but in some Lisp implementations it's much slower.\n        CCL (at least as of 8/2008)\n        creates a one-character string upon each comparison, for example,\n        which is very expensive.\n      </p>\n      <p>\n        Also, you should use <code>:START</code> and <code>:END</code> arguments\n        to <code>STRING=</code> or <code>STRING-EQUAL</code>\n        instead of using <code>SUBSEQ</code>;\n        e.g. <code>(string-equal (subseq s1 2 6) s2)</code> should instead be\n        <code>(string-equal s1 s2 :start1 2 :end1 6)</code>\n        This is preferable because it does not cons.\n      </p>\n      <p>\n        You should use <code>ZEROP</code>,\n        <code>PLUSP</code>, or <code>MINUSP</code>,\n        instead of comparing a value to <code>0</code> or <code>0.0</code>.\n      </p>\n      <p>\n        You must not use exact comparison on floating point numbers,\n        since the vague nature of floating point arithmetic\n        can produce little \"errors\" in numeric value.\n        You should compare absolute values to a threshold.\n      </p>\n      <p>\n        You must use <code>=</code> to compare numbers,\n        unless you really mean for <code>0</code>,\n        <code>0.0</code> and <code>-0.0</code> to compare unequal,\n        in which case you should use <code>EQL</code>.\n        Then again, you must not usually use exact comparison\n        on floating point numbers.\n      </p>\n      <p>\n        Monetary amounts should be using decimal (rational) numbers\n        to avoid the complexities and rounding errors\n        of floating-point arithmetic.\n        Libraries such as\n        <a href=\"http://wukix.com/lisp-decimals\">wu-decimal</a>\n        may help you;\n        once again, if this library is not satisfactory, see above about\n        <a href=\"#Using_Libraries\">Using Libraries</a> and\n        <a href=\"#Open-Sourcing_Code\">Open-Sourcing Code</a>.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Iteration\">\n    <SUMMARY>\n      Use the appropriate form for iteration.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should use simpler forms such as\n        <code>DOLIST</code> or <code>DOTIMES</code>\n        instead of <code>LOOP</code>\n        in simple cases when you're not going to use any\n        of the <code>LOOP</code> facilities such as\n        bindings, collection or block return.\n      </p>\n      <p>\n        Use the <code>WITH</code> clause of <code>LOOP</code>\n        when it will avoid a level of nesting with <code>LET</code>.\n        You may use <code>LET</code> if it makes it clearer\n        to return one of bound variables after the <code>LOOP</code>,\n        rather than use a clumsy <code>FINALLY (RETURN ...)</code> form.\n      </p>\n      <p>\n        In the body of a <code>DOTIMES</code>,\n        do not set the iteration variable.\n        (CCL will issue a compiler warning if you do.)\n      </p>\n      <p>\n        Most systems use unadorned symbols in the current package\n        as <code>LOOP</code> keywords.\n        Other systems use actual <code>:keywords</code>\n        from the <code>KEYWORD</code> package\n        as <code>LOOP</code> keywords.\n        You must be consistent with the convention used in your system.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"I/O\">\n    <SUMMARY>\n      Use the appropriate I/O functions.\n    </SUMMARY>\n    <BODY>\n      <p>\n        When writing a server,\n        code must not send output to the standard streams such as\n        <code>*STANDARD-OUTPUT*</code> or <code>*ERROR-OUTPUT*</code>.\n        Instead, code must use the proper logging framework\n        to output messages for debugging.\n        We are running as a server, so there is no console!\n      </p>\n      <p>\n        Code must not use <code>PRINT-OBJECT</code>\n        to communicate with a user —\n        <code>PRINT-OBJECT</code> is for debugging purposes only.\n        Modifying any <code>PRINT-OBJECT</code> method\n        must not break any public interfaces.\n      </p>\n      <p>\n        You should not use a sequence of <code>WRITE-XXX</code>\n        where a single <code>FORMAT</code> string could be used.\n        Using format allows you\n        to parameterize the format control string in the future\n        if the need arises.\n      </p>\n      <p>\n        You should use <code>WRITE-CHAR</code> to emit a character\n        rather than <code>WRITE-STRING</code>\n        to emit a single-character string.\n      </p>\n      <p>\n        You should not use <code>(format nil \"~A\" value)</code>;\n        you should use <code>PRINC-TO-STRING</code> instead.\n      </p>\n      <p>\n        You should use <code>~&lt;Newline&gt;</code>\n        or <code>~@&lt;Newline&gt;</code> in format strings\n        to keep them from wrapping in 100-column editor windows,\n        or to indent sections or clauses to make them more readable.\n      </p>\n      <p>\n        You should not use <code>STRING-UPCASE</code>\n        or <code>STRING-DOWNCASE</code>\n        on format control parameters;\n        instead, it should use <code>\"~:@(~A~)\"</code> or <code>\"~(~A~)\"</code>.\n      </p>\n      <p>\n        Be careful when using the <code>FORMAT</code> conditional directive.\n        The parameters are easy to forget.\n      </p>\n      <dl>\n        <dt>No parameters, e.g. <code>\"~[Siamese~;Manx~;Persian~] Cat\"</code></dt>\n        <dd>\n          Take one format argument, which should be an integer.\n          Use it to choose a clause. Clause numbers are zero-based.\n          If the number is out of range, just print nothing.\n          You can provide a default value\n          by putting a <code>\":\"</code> in front of the last <code>\";\"</code>.\n          E.g. in <code>\"~[Siamese~;Manx~;Persian~:;Alley~] Cat\"</code>,\n          an out-of-range arg prints <code>\"Alley\"</code>.\n        </dd>\n        <dt><code>:</code> parameter, e.g. <code>\"~:[Siamese~;Manx~]\"</code></dt>\n        <dd>\n          Take one format argument.  If it's <code>NIL</code>,\n          use the first clause, otherwise use the second clause.\n        </dd>\n        <dt><code>@</code> parameter, e.g. <code>\"~@[Siamese ~a~]\"</code></dt>\n        <dd>\n          If the next format argument is true,\n          use the choice, but do NOT take the argument.\n          If it's false, take one format argument and print nothing.\n          (Normally the clause uses the format argument.)\n        </dd>\n        <dt><code>#</code> parameter, e.g. <code>\"~#[ none~; ~s~; ~s and ~s~]\"</code></dt>\n        <dd>\n          Use the number of arguments to format\n          as the number to choose a clause.\n          The same as no parameters in all other ways.\n          Here's the full hairy example:\n          <code>\"Items: ~#[ none~; ~S~; ~S and ~S~:;~@{~S~^~#[~; and ~:;, ~]~}~].\"</code>\n        </dd>\n      </dl>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Optimization\">\n  <STYLEPOINT title=\"Avoid Allocation\">\n    <SUMMARY>\n      You should avoid unnecessary allocation of memory.\n    </SUMMARY>\n    <BODY>\n      <p>\n        In a language with automatic storage management (such as Lisp or Java),\n        the colloquial phrase \"memory leak\" refers to situation\n        where storage that is not actually needed\n        nevertheless does not get deallocated,\n        because it is still reachable.\n      </p>\n      <p>\n        You should be careful that when you create objects,\n        you don't leave them reachable after they are no longer needed!\n      </p>\n      <p>\n        Here's a particular trap-for-the-unwary in Common Lisp.\n        If you make an array with a fill pointer, and put objects in it,\n        and then set the fill pointer back to zero,\n        those objects are still reachable as far as Lisp goes\n        (the Common Lisp spec says that it's still OK\n        to refer to the array entries past the end of the fill pointer).\n      </p>\n      <p>\n        Don't cons (i.e., allocate) unnecessarily.\n        Garbage collection is not magic.\n        Excessive allocation is usually a performance problem.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Unsafe Operations\">\n    <SUMMARY>\n      You must only use faster unsafe operations\n      when there is a clear performance need\n      and you can document why it's correct.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Common Lisp implementations often provide backdoors\n        to compute some operations faster in an unsafe way.\n        For instance, some libraries provide arithmetic operations\n        that are designed to be used with fixnums only,\n        and yield the correct result faster if provided proper arguments.\n        The downside is that the result of such operations\n        is incorrect in case of overflow, and can\n        have undefined behavior when called with anything but fixnums.\n      </p>\n      \n      <p>\n        More generally, unsafe operations\n        will yield the correct result faster\n        than would the equivalent safe operation\n        if the arguments satisfy some invariant such as\n        being of the correct type and small enough;\n        however if the arguments fail to satisfy the required invariants,\n        then the operation may have undefined behavior,\n        such as crashing the software, or,\n        which is sometimes worse, silently giving wrong answers.\n        Depending on whether the software is piloting an aircraft\n        or other life-critical device,\n        or whether it is accounting for large amounts money,\n        such undefined behavior can kill or bankrupt people.\n        Yet proper speed can sometimes make the difference between\n        software that's unusably slow and software that does its job,\n        or between software that is a net loss\n        and software that can yield a profit.\n      </p>\n      <p>\n        You must not define or use unsafe operations without both\n        profiling results indicating the need for this optimization,\n        and careful documentation explaining why it is safe to use them.\n        Unsafe operations should be restricted to internal functions;\n        you should carefully documented how unsafe it is\n        to use these functions with the wrong arguments.\n        You should only use unsafe operations\n        inside functions internal to a package and\n        you should document the use of the declarations,\n        since calling the functions with arguments of the wrong type\n        can lead to undefined behavior.\n        Use <code>check-type</code> in functions exported from a package\n        to sanitize input arguments,\n        so that internal functions are never passed illegal values.\n      </p>\n      <p>\n        On some compilers,\n        new unsafe operations\n        can usually be defined by combining\n        type declarations with an <code>OPTIMIZE</code> declaration\n        that has sufficiently high <code>SPEED</code> and low <code>SAFETY</code>.\n        In addition to providing more speed for production code,\n        such declarations may more helpful\n        than <code>check-type</code> assertions\n        for finding bugs at compile-time,\n        on compilers that have type inference.\n        These compilers may interpret those declarations as assertions\n        if you switch to safer and slower optimize settings;\n        this is good to locate a dynamic error in your code during development,\n        but is not to be used for production code since\n        it defeats the purpose of declarations as a performance trick.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"DYNAMIC-EXTENT\">\n    <SUMMARY>\n      You should only use <code>DYNAMIC-EXTENT</code>\n      where it matters for performance,\n      and you can document why it is correct.\n    </SUMMARY>\n    <BODY>\n      <p>\n        <code>DYNAMIC-EXTENT</code> declarations are\n        a particular case of\n        <a href=\"#Unsafe_Operations\">unsafe operations</a>.\n      </p>\n      <p>\n        The purpose of a <code>DYNAMIC-EXTENT</code> declaration\n        is to improve performance by reducing garbage collection\n        in cases where it appears to be obvious that an object's lifetime\n        is within the \"dynamic extent\" of a function.\n        That means the object is created at some point\n        after the function is called, and\n        the object is always inaccessible after the function exits by any means.\n      </p>\n      <p>\n        By declaring a variable or a local function <code>DYNAMIC-EXTENT</code>,\n        the programmer <em>asserts</em> to Lisp\n        that any object that is ever a value of that variable\n        or the closure that is the definition of the function\n        has a lifetime within the dynamic extent of the (innermost) function\n        that declares the variable.\n      </p>\n      <p>\n        The Lisp implementation is then free to use that information\n        to make the program faster.\n        Typically, Lisp implementations can take advantage of this knowledge\n        to stack-allocate:\n      </p>\n      <ul>\n        <li>\n          The lists created to store <code>&amp;REST</code> parameters.\n        </li>\n        <li>\n          Lists, vectors and structures allocated within a function.\n        </li>\n        <li>\n          Closures.\n        </li>\n      </ul>\n      <p>\n        If the assertion is wrong, i.e. if the programmer's claim is not true,\n        the results can be <em>catastrophic</em>:\n        Lisp can terminate any time after the function returns,\n        or it can hang forever, or — worst of all —\n        it can produce incorrect results without any runtime error!\n      </p>\n      <p>\n        Even if the assertion is correct,\n        future changes to the function might introduce\n        a violation of the assertion.\n        This increases the danger.\n      </p>\n      <p>\n        In most cases, such objects are ephemeral.\n        Modern Lisp implementations use generational garbage collectors,\n        which are quite efficient under these circumstances.\n      </p>\n      <p>\n        Therefore, <code>DYNAMIC-EXTENT</code> declarations\n        should be used sparingly. You must only use them if:\n      </p>\n      <ol>\n        <li>\n          There is some good reason to think that the overall effect\n          on performance is noticeable, and\n        </li>\n        <li>\n          It is absolutely clear that the assertion is true.\n        </li>\n        <li>\n          It is quite unlikely that the code will be changed\n          in ways that cause the declaration to become false.\n        </li>\n      </ol>\n      <p>\n        Point (1) is a special case of\n        the principle of avoiding premature optimization.\n        An optimization like this only matters if such objects\n        are allocated at a very high rate, e.g. \"inside an inner loop\".\n      </p>\n      <p>\n        Note that is relatively easy to ascertain that\n        a function will not escape the dynamic extent of the current call frame\n        by analyzing where the function is called and\n        what other functions it is passed to;\n        therefore, you should somewhat wary of declaring a function\n        <code>DYNAMIC-EXTENT</code>, but this is not a high-stress declaration.\n        On the other hand, it is much harder to ascertain that\n        none of the objects ever bound or assigned to that variable\n        and none of their sub-objects\n        will escape the dynamic extent of the current call frame,\n        and that they still won't in any future modification of a function.\n        Therefore, you should be extremely wary\n        of declaring a variable <code>DYNAMIC-EXTENT</code>.\n      </p>\n      <p>\n        It's usually hard to predict the effect of such optimization on performance.\n        When writing a function or macro\n        that is part of a library of reusable code,\n        there's no a priori way to know how often the code will run.\n        Ideally, tools would be available to discover\n        the availability and suitability of using such an optimization\n        based on running simulations and test cases, but\n        in practice this isn't as easy as it ought to be.\n        It's a tradeoff.\n        If you're very, very sure that the assertion is true\n        (that any object bound to the variable and any of its sub-objects\n        are only used within the dynamic extent of the specified scope),\n        and it's not obvious how much time will be saved\n        and it's not easy to measure,\n        then it may be better to put in the declaration than to leave it out.\n        (Ideally it would be easier to make such measurements\n        than it actually is.)\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"REDUCE vs APPLY\">\n    <SUMMARY>\n      You should use <code>REDUCE</code>\n      instead of <code>APPLY</code> where appropriate.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should use <code>REDUCE</code>\n        instead of <code>APPLY</code> and a consed-up list,\n        where the semantics of the first operator argument\n        otherwise guarantees the same semantics.\n        Of course, you must use <code>APPLY</code>\n        if it does what you want and <code>REDUCE</code> doesn't.\n        For instance:\n      </p>\n      <BAD_CODE_SNIPPET>\n        ;; Bad\n        (apply #'+ (mapcar #'acc frobs))\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        ;; Better\n        (reduce #'+ frobs :key #'acc :initial-value 0)\n      </CODE_SNIPPET>\n      <p>\n        This is preferable because it does not do extra consing,\n        and does not risk going beyond <code>CALL-ARGUMENTS-LIMIT</code>\n        on implementations where that limit is small,\n        which could blow away the stack on long lists\n        (we want to avoid gratuitous non-portability in our code).\n      </p>\n      <p>\n        However, you must be careful not to use <code>REDUCE</code>\n        in ways that needlessly increase\n        the complexity class of the computation.\n        For instance, <code>(REDUCE 'STRCAT ...)</code> is <i>O(n^2)</i>\n        when an appropriate implementation is only <i>O(n)</i>.\n        Moreover, <code>(REDUCE 'APPEND ...)</code>\n        is also <i>O(n^2)</i> unless you specify <code>:FROM-END T</code>.\n        In such cases, you MUST NOT use <code>REDUCE</code>,\n        and you MUST NOT use <code>(APPLY 'STRCAT ...)</code>\n        or <code>(APPLY 'APPEND ...)</code> either.\n        Instead you MUST use proper abstractions\n        from a suitable library (that you may have to contribute to)\n        that properly handles those cases\n        without burdening users with implementation details.\n        See for instance <code>UIOP:REDUCE/STRCAT</code>.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Avoid NCONC\">\n    <SUMMARY>\n      You should not use <code>NCONC</code>;\n      you should use <code>APPEND</code> instead,\n      or better data structures.\n    </SUMMARY>\n    <BODY>\n      <p>\n        You should almost never use <code>NCONC</code>.\n        You should use <code>APPEND</code>\n        when you don't depend on any side-effect.\n        You should use <code>ALEXANDRIA:APPENDF</code>\n        when you need to update a variable.\n        You should probably not depend on games\n        being played with the <code>CDR</code>\n        of the current CONS cell\n        (which some might argue is suggested but not guaranteed by the specification);\n        if you do, you must include a prominent\n        comment explaining the use of <code>NCONC</code>;\n        and you should probably reconsider your data representation strategy.\n      </p>\n      <p>\n        By extension, you should avoid <code>MAPCAN</code>\n        or the <code>NCONC</code> feature of <code>LOOP</code>.\n        You should instead respectively use\n        <code>ALEXANDRIA:MAPPEND</code>\n        and the <code>APPEND</code> feature of <code>LOOP</code>.\n      </p>\n      <p>\n        <code>NCONC</code> is very seldom a good idea,\n        since its time complexity class is no better than <code>APPEND</code>,\n        its space complexity class also is no better than <code>APPEND</code>\n        in the common case where no one else is sharing the side-effected list,\n        and its bug complexity class is way higher than <code>APPEND</code>.\n      </p>\n      <p>\n        If the small performance hit due\n        to <code>APPEND</code> vs. <code>NCONC</code>\n        is a limiting factor in your program,\n        you have a big problem and are probably using the wrong data structure:\n        you should be using sequences with constant-time append\n        (see Okasaki's book, and add them to lisp-interface-library),\n        or more simply you should be accumulating data in a tree\n        that will get flattened once in linear time\n        after the accumulation phase is complete.\n      </p>\n      <p>\n        You may only use <code>NCONC</code>, <code>MAPCAN</code>\n        or the <code>NCONC</code> feature of <code>LOOP</code>\n        in low-level functions where performance matters,\n        where the use of lists as a data structure has been vetted\n        because these lists are known to be short,\n        and when the function or expression the result of which are accumulated\n        explicitly promises in its contract that it only returns fresh lists\n        (in particular, it can't be a constant quote or backquote expression).\n        Even then, the use of such primitives must be rare,\n        and accompanied by justifying documentation.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<CATEGORY title=\"Pitfalls\">\n  <STYLEPOINT title=\"#'FUN vs. 'FUN\">\n    <SUMMARY>\n      You should usually refer to a function as <code>#'FUN</code> rather than <code>'FUN</code>.\n    </SUMMARY>\n    <BODY>\n      <p>\n        The former, which reads as <code>(FUNCTION FUN)</code>,\n        refers to the function object, and is lexically scoped.\n        The latter, which reads as <code>(QUOTE FUN)</code>,\n        refers to the symbol, which when called\n        uses the global <code>FDEFINITION</code> of the symbol.\n      </p>\n      <p>\n        When using functions that take a functional argument\n        (e.g., <code>MAPCAR</code>, <code>APPLY</code>,\n        <code>:TEST</code> and <code>:KEY</code> arguments),\n        you should use the <code>#'</code> to refer to the function,\n        not just single quote.\n      </p>\n      <p>\n        An exception is when you explicitly want dynamic linking,\n        because you anticipate that\n        the global function binding will be updated.\n      </p>\n      <p>\n        Another exception is when you explicitly want to access\n        a global function binding,\n        and avoid a possible shadowing lexical binding.\n        This shouldn't happen often, as it is usually a bad idea\n        to shadow a function when you will want to use the shadowed function;\n        just use a different name for the lexical function.\n      </p>\n      <p>\n        You must consistently use either <code>#'(lambda ...)</code>\n        or <code>(lambda ...)</code> without <code>#'</code> everywhere.\n        Unlike the case of <code>#'symbol</code> vs <code>'symbol</code>,\n        it is only a syntactic difference with no semantic impact,\n        except that the former works on Genera and the latter doesn't.\n        \n        You must use the former style if your code is intended as a library\n        with maximal compatibility to all Common Lisp implementations;\n        otherwise, it is optional which style you use.\n        <code>#'</code> may be seen as a hint\n        that you're introducing a function in expression context;\n        but the <code>lambda</code> itself is usually sufficient hint,\n        and concision is good.\n        Choose wisely, but above all,\n        consistently with yourself and other developers,\n        within a same file, package, system, project, etc.\n      </p>\n      <p>\n        Note that if you start writing a new system\n        in a heavily functional style,\n        you may consider using\n        <a href=\"http://cliki.net/lambda-reader\">lambda-reader</a>,\n        a system that lets you use the unicode character <code>λ</code>\n        instead of <code>LAMBDA</code>.\n        But you must not start using such a syntactic extension\n        in an existing system without getting permission from other developers.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"Pathnames\">\n    <SUMMARY>\n      Common Lisp pathnames are tricky. Be aware of pitfalls. Use <code>UIOP</code>.\n    </SUMMARY>\n    <BODY>\n      <p>\n        It is surprisingly hard to properly deal with pathnames in Common Lisp.\n      </p>\n      <p>\n        <code>ASDF 3</code> comes with a portability library <code>UIOP</code>\n        that makes it <em>much</em> easier to deal with pathnames\n        portably — and correctly — in Common Lisp.\n        You should use it when appropriate.\n      </p>\n      <p>\n        First, be aware of the discrepancies between\n        the syntax of Common Lisp pathnames,\n        which depends on which implementation and operating system\n        you are using,\n        and the native syntax of pathnames on your operating system.\n        The Lisp syntax may involves quoting of special characters\n        such as <code>#\\.</code> and <code>#\\*</code>, etc.,\n        in addition to the quoting of\n        <code>#\\\\</code> and <code>#\\\"</code> within strings.\n        By contrast, your operating system's other\n        system programming languages\n        (shell, C, scripting languages)\n        may only have one layer of quoting, into strings.\n      </p>\n      <p>\n        Second, when using <code>MERGE-PATHNAMES</code>,\n        be wary of the treatment of the <code>HOST</code> component,\n        which matters a lot on non-Unix platforms\n        (and even on some Unix implementations).\n        You probably should be using\n        <code>UIOP:MERGE-PATHNAMES*</code> or <code>UIOP:SUBPATHNAME</code>\n        instead of <code>MERGE-PATHNAMES</code>,\n        especially if your expectations for relative pathnames\n        are informed by the way they work in Unix or Windows;\n        otherwise you might hit weird bugs whereby on some implementations,\n        merging a relative pathnames with an absolute pathname\n        results in overriding the absolute pathname's host\n        and replace it with the host from the value of\n        <code>*DEFAULT-PATHNAME-DEFAULTS*</code>\n        at the time the relative pathname was created.\n      </p>\n      <p>\n        Third, be aware that <code>DIRECTORY</code>\n        is not portable across implementations\n        in how it handles wildcards, sub-directories, symlinks, etc.\n        There again, <code>UIOP</code> provides several\n        common abstractions to deal with pathnames,\n        but only does so good a job.\n        For a complete portable solution, use IOLib —\n        though its Windows support lags behind.\n      </p>\n      <p>\n        <code>LOGICAL-PATHNAME</code>s are not a portable abstraction,\n        and should not be used in portable code.\n        Many implementations have bugs in them, when they are supported at all.\n        SBCL implements them very well,\n        but strictly enforces the limitations on characters\n        allowed by the standard, which restricts their applicability.\n        Other implementations allow arbitrary characters in such pathnames,\n        but in doing so are not being conformant,\n        and are still incompatible with each other in many ways.\n        You should use other pathname abstractions,\n        such as <code>ASDF:SYSTEM-RELATIVE-PATHNAME</code> or\n        the underlying <code>UIOP:SUBPATHNAME</code> and\n        <code>UIOP:PARSE-UNIX-NAMESTRING</code>.\n      </p>\n      \n      <p>\n        Finally, be aware that paths may change between\n        the time you build the Lisp image for your application,\n        and the time you run the application from its image.\n        You should be careful to reset your image\n        to forget irrelevant build-time paths and\n        reinitialize any search path from current environment variables.\n        <code>ASDF</code> for instance requires you to reset its paths\n        with <code>UIOP:CLEAR-CONFIGURATION</code>.\n        <code>UIOP</code> provides hooks\n        to call functions before an image is dumped,\n        from which to reset or <code>makunbound</code> relevant variables.\n      </p>\n      \n    </BODY>\n  </STYLEPOINT>\n  <STYLEPOINT title=\"SATISFIES\">\n    <SUMMARY>\n      You must be careful when using a <code>SATISFIES</code> clause in a type specifier.\n    </SUMMARY>\n    <BODY>\n      <p>\n        Most Common Lisp implementations can't optimize\n        based on a <code>SATISFIES</code> type,\n        but many of them offer simple optimizations\n        based on a type of the form\n        <code>(AND FOO (SATISFIES BAR-P))</code>\n        where the first term of the <code>AND</code> clause\n        describes the structure of the object\n        without any <code>SATISFIES</code>\n        and the second term is the <code>SATISFIES</code>.\n      </p>\n      <BAD_CODE_SNIPPET>\n        (deftype prime-number () (satisfies prime-number-p)) ; Bad\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (deftype prime-number () (and integer (satisfies prime-number-p)) ; Better\n      </CODE_SNIPPET>\n      <p>\n        However, <code>AND</code> in the <code>DEFTYPE</code> language\n        isn't a left-to-right short-circuit operator\n        as in the expression language;\n        it is a symmetrical connector that allows for reordering subterms\n        and doesn't guarantee short-circuiting.\n        Therefore, in the above example,\n        you cannot rely on the test for <code>INTEGER</code>ness\n        to protect the function <code>PRIME-NUMBER-P</code>\n        from being supplied non-integer arguments\n        to test for being of instances of the type.\n        Implementations may, and some <em>will</em>,\n        invoke <code>SATISFIES</code>-specified function\n        at compile-time to test various relevant objects.\n      </p>\n      <p>\n        That is why any function specified in a <code>SATISFIES</code> clause\n        MUST accept objects of any type as argument to the function,\n        and MUST be defined within an <code>EVAL-WHEN</code>\n        (as well as any variable it uses or function it calls):\n      </p>\n      <BAD_CODE_SNIPPET>\n        (defun prime-number-p (n) ; Doubly bad!\n          (let ((m (abs n)))\n            (if (&lt;= m *prime-number-cutoff*)\n                (small-prime-number-p m)\n                (big-prime-number-p m))))\n      </BAD_CODE_SNIPPET>\n      <CODE_SNIPPET>\n        (eval-when (:compile-toplevel :load-toplevel :execute) ; Better\n          (defun prime-number-p (n)\n            (when (integerp n) ; Better\n              (let ((m (abs n)))\n                (if (&lt;= m *prime-number-cutoff*)\n                    (small-prime-number-p m)\n                    (big-prime-number-p m))))))\n      </CODE_SNIPPET>\n      <p>\n        In particular, the above means that the\n        <a href=\"https://www.lispworks.com/documentation/HyperSpec/Body/t_satisf.htm\">example</a>\n        used in the Common Lisp Standard is erroneous:\n        <code>(and integer (satisfies evenp))</code>\n        is <em>not</em> a safe, conformant type specifier to use,\n        because <code>EVENP</code> will throw an error\n        rather than return <code>NIL</code>\n        when passed a non-integer as an argument.\n      </p>\n      <p>\n        Finally, there is a catch when your <code>DEFTYPE</code> code expands\n        to a <code>SATISFIES</code> with a dynamically generated function:\n      </p>\n      <ul>\n        <li>\n          You cannot control when implementations will or will not\n          expand a <code>DEFTYPE</code>.\n        </li>\n        <li>\n          The expansion itself cannot contain a function definition\n          or any code in the expression language.\n        </li>\n        <li>\n          You cannot control when the expansion is used,\n          it may happen in a different process\n          that didn't expand the definition.\n        </li>\n      </ul>\n      <p>\n        Therefore, you cannot merely create the function\n        as a side-effect of expansion\n        using <code>EVAL</code> at type-expansion time.\n        The solution is to use\n        <code>ASDF-FINALIZERS:EVAL-AT-TOPLEVEL</code> instead.\n        See the very last point\n        in the discussion about <a href=\"#EVAL\">EVAL</a>.\n      </p>\n      <p>\n        Common Lisp is hard to satisfy.\n      </p>\n    </BODY>\n  </STYLEPOINT>\n</CATEGORY>\n\n<HR/>\n\n<small>Credits:\n   Adam Worrall, Dan Pierson, Matt Marjanovic, Matt Reklaitis,\n   Paul Weiss, Scott McKay, Sundar Narasimhan,\n   and several other people contributed.\n   Special thanks to Steve Hain,\n   and to the previous editors,\n   in reverse chronological order Dan Weinreb and Jeremy Brown.\n</small>\n\n<p align=\"right\">\nRevision 1.28\n</p>\n\n\n<address>\nRobert Brown\n</address>\n\n<address>\n  <a HREF=\"mailto:tunes@google.com\">François-René Rideau</a>\n</address>\n\n\n\n</GUIDE>\n"
  },
  {
    "path": "objcguide.md",
    "content": "# Google Objective-C Style Guide\n\n> Objective-C is a dynamic, object-oriented extension of C. It's designed to be\n> easy to use and read, while enabling sophisticated object-oriented design. It\n> is one of the primary development languages for applications on Apple\n> platforms.\n>\n> Apple has already written a very good, and widely accepted, [Cocoa Coding\n> Guidelines](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html)\n> for Objective-C. Please read it in addition to this guide.\n>\n> The purpose of this document is to describe the Objective-C (and\n> Objective-C++) coding guidelines and practices. These guidelines have evolved\n> and been proven over time on other projects and teams.\n> Open-source projects developed by Google conform to the requirements in this guide.\n>\n> Note that this guide is not an Objective-C tutorial. We assume that the reader\n> is familiar with the language. If you are new to Objective-C or need a\n> refresher, please read [Programming with\n> Objective-C](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html).\n\n\n\n## Principles\n\n### Optimize for the reader, not the writer\n\nCodebases often have extended lifetimes and more time is spent reading the code\nthan writing it. We explicitly choose to optimize for the experience of our\naverage software engineer reading, maintaining, and debugging code in our\ncodebase rather than the ease of writing said code. For example, when something\nsurprising or unusual is happening in a snippet of code, leaving textual hints\nfor the reader is valuable.\n\n### Be consistent\n\nWhen the style guide allows multiple options it is preferable to pick one option\nover mixed usage of multiple options. Using one style consistently throughout a\ncodebase lets engineers focus on other (more important) issues. Consistency also\nenables better automation because consistent code allows more efficient\ndevelopment and operation of tools that format or refactor code. In many cases,\nrules that are attributed to \"Be Consistent\" boil down to \"Just pick one and\nstop worrying about it\"; the potential value of allowing flexibility on these\npoints is outweighed by the cost of having people argue over them.\n\n### Be consistent with Apple SDKs\n\nConsistency with the way Apple SDKs use Objective-C has value for the same\nreasons as consistency within our code base. If an Objective-C feature solves a\nproblem that's an argument for using it. However, sometimes language features\nand idioms are flawed, or were just designed with assumptions that are not\nuniversal. In those cases it is appropriate to constrain or ban language\nfeatures or idioms.\n\n### Style rules should pull their weight\n\nThe benefit of a style rule must be large enough to justify asking engineers to\nremember it. The benefit is measured relative to the codebase we would get\nwithout the rule, so a rule against a very harmful practice may still have a\nsmall benefit if people are unlikely to do it anyway. This principle mostly\nexplains the rules we don’t have, rather than the rules we do: for example, goto\ncontravenes many of the following principles, but is not discussed due to its\nextreme rarity.\n\n<a id=\"Example\"></a>\n\n## Example\n\nThey say an example is worth a thousand words, so let's start off with an\nexample that should give you a feel for the style, spacing, naming, and so on.\n\nHere is an example header file, demonstrating the correct commenting and spacing\nfor an `@interface` declaration.\n\n```objectivec\n// GOOD:\n\n#import <Foundation/Foundation.h>\n\n@class Bar;\n\n/**\n * A sample class demonstrating good Objective-C style. All interfaces,\n * categories, and protocols (read: all non-trivial top-level declarations\n * in a header) MUST be commented. Comments must also be adjacent to the\n * object they're documenting.\n */\n@interface Foo : NSObject\n\n/** The retained Bar. */\n@property(nonatomic) Bar *bar;\n\n/** The current drawing attributes. */\n@property(nonatomic, copy) NSDictionary<NSString *, NSNumber *> *attributes;\n\n/**\n * Convenience creation method.\n * See -initWithBar: for details about @c bar.\n *\n * @param bar The string for fooing.\n * @return An instance of Foo.\n */\n+ (instancetype)fooWithBar:(Bar *)bar;\n\n/**\n * Initializes and returns a Foo object using the provided Bar instance.\n *\n * @param bar A string that represents a thing that does a thing.\n */\n- (instancetype)initWithBar:(Bar *)bar NS_DESIGNATED_INITIALIZER;\n\n/**\n * Does some work with @c blah.\n *\n * @param blah\n * @return YES if the work was completed; NO otherwise.\n */\n- (BOOL)doWorkWithBlah:(NSString *)blah;\n\n@end\n```\n\nAn example source file, demonstrating the correct commenting and spacing for the\n`@implementation` of an interface.\n\n```objectivec\n// GOOD:\n\n#import \"Shared/Util/Foo.h\"\n\n@implementation Foo {\n  /** The string used for displaying \"hi\". */\n  NSString *_string;\n}\n\n+ (instancetype)fooWithBar:(Bar *)bar {\n  return [[self alloc] initWithBar:bar];\n}\n\n- (instancetype)init {\n  // Classes with a custom designated initializer should always override\n  // the superclass's designated initializer.\n  return [self initWithBar:nil];\n}\n\n- (instancetype)initWithBar:(Bar *)bar {\n  self = [super init];\n  if (self) {\n    _bar = [bar copy];\n    _string = [[NSString alloc] initWithFormat:@\"hi %d\", 3];\n    _attributes = @{\n      @\"color\" : UIColor.blueColor,\n      @\"hidden\" : @NO\n    };\n  }\n  return self;\n}\n\n- (BOOL)doWorkWithBlah:(NSString *)blah {\n  // Work should be done here.\n  return NO;\n}\n\n@end\n```\n\n<a id=\"Naming\"></a>\n\n## Naming\n\nNames should be as descriptive as possible, within reason. Follow standard\n[Objective-C naming\nrules](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html).\n\nAvoid non-standard abbreviations (including non-standard acronyms and\ninitialisms). Don't worry about saving horizontal space as it is far more\nimportant to make your code immediately understandable by a new reader. For\nexample:\n\n```objectivec\n// GOOD:\n\n// Good names.\nint numberOfErrors = 0;\nint completedConnectionsCount = 0;\ntickets = [[NSMutableArray alloc] init];\nuserInfo = [someObject object];\nport = [network port];\nNSDate *gAppLaunchDate;\n```\n\n```objectivec\n// AVOID:\n\n// Names to avoid.\nint w;\nint nerr;\nint nCompConns;\ntix = [[NSMutableArray alloc] init];\nobj = [someObject object];\np = [network port];\n```\n\nAny class, category, method, function, or variable name should use all capitals\nfor acronyms and [initialisms](https://en.wikipedia.org/wiki/Initialism) within\n(including at the beginning of) the name. This follows Apple's standard of using\nall capitals within a name for acronyms such as URL, ID, TIFF, and EXIF.\n\nNames of C functions and typedefs should be capitalized and use camel case as\nappropriate for the surrounding code.\n\n<a id=\"Inclusive_Language\"></a>\n\n### Inclusive Language\n\nIn all code, including naming and comments, use inclusive language and avoid\nterms that other programmers might find disrespectful or offensive (such as\n\"master\" and \"slave\", \"blacklist\" and \"whitelist\", or \"redline\"), even if the\nterms also have an ostensibly neutral meaning. Similarly, use gender-neutral\nlanguage unless you're referring to a specific person (and using their\npronouns). For example, use \"they\"/\"them\"/\"their\" for people of unspecified\ngender (even when singular), and \"it\"/\"its\" for non-people.\n\n\n<a id=\"File_Names\"></a>\n\n### File Names\n\nFile names should reflect the name of the class implementation that they\ncontain—including case.\n\nFollow the convention that your project uses.\n\nFile extensions should be as follows:\n\nExtension | Type\n--------- | ---------------------------------\n.h        | C/C++/Objective-C header file\n.m        | Objective-C implementation file\n.mm       | Objective-C++ implementation file\n.cc       | Pure C++ implementation file\n.c        | C implementation file\n\nFiles containing code that may be shared across projects or used in a large\nproject should have a clearly unique name, typically including the project or\nclass [prefix](#prefixes).\n\nFile names for categories should include the name of the class being extended,\nlike GTMNSString+Utils.h or NSTextView+GTMAutocomplete.h\n\n### Prefixes\n\nPrefixes are commonly required in Objective-C to avoid naming collisions in a\nglobal namespace. Classes, protocols, global functions, and global constants\nshould generally be named with a prefix that begins with a capital letter\nfollowed by one or more capital letters or numbers.\n\nWARNING: Apple reserves two-letter prefixes—see\n[Conventions in Programming with Objective-C](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html)—so\nprefixes with a minimum of three characters are considered best practice.\n\n```objectivec\n// GOOD:\n\n/** An example error domain. */\nGTM_EXTERN NSString *GTMExampleErrorDomain;\n\n/** Gets the default time zone. */\nGTM_EXTERN NSTimeZone *GTMGetDefaultTimeZone(void);\n\n/** An example delegate. */\n@protocol GTMExampleDelegate <NSObject>\n@end\n\n/** An example class. */\n@interface GTMExample : NSObject\n@end\n\n```\n\n<a id=\"Class_Names\"></a>\n\n### Class Names\n\nClass names (along with category and protocol names) should start as uppercase\nand use mixed case to delimit words.\n\nClasses and protocols in code shared across multiple applications must have an\nappropriate [prefix](#prefixes) (e.g. GTMSendMessage). Prefixes are recommended,\nbut not required, for other classes and protocols.\n\n<a id=\"Category_Names\"></a>\n\n### Category Naming\n\nCategory names should start with an appropriate [prefix](#prefixes) identifying\nthe category as part of a project or open for general use.\n\nCategory source file names should begin with the class being extended followed\nby a plus sign and the name of the category, e.g., `NSString+GTMParsing.h`.\nMethods in a category should be prefixed with a lowercase version of the prefix\nused for the category name followed by an underscore (e.g.,\n`gtm_myCategoryMethodOnAString:`) in order to prevent collisions in\nObjective-C's global namespace.\n\nThere should be a single space between the class name and the opening\nparenthesis of the category.\n\n```objectivec\n// GOOD:\n\n// UIViewController+GTMCrashReporting.h\n\n/** A category that adds metadata to include in crash reports to UIViewController. */\n@interface UIViewController (GTMCrashReporting)\n\n/** A unique identifier to represent the view controller in crash reports. */\n@property(nonatomic, setter=gtm_setUniqueIdentifier:) int gtm_uniqueIdentifier;\n\n/** Returns an encoded representation of the view controller's current state. */\n- (nullable NSData *)gtm_encodedState;\n\n@end\n```\n\nIf a class is not shared with other projects, categories extending it may omit\nname prefixes and method name prefixes.\n\n```objectivec\n// GOOD:\n\n/** This category extends a class that is not shared with other projects. */\n@interface XYZDataObject (Storage)\n- (NSString *)storageIdentifier;\n@end\n```\n\n<a id=\"Objective-C_Method_Names\"></a>\n\n### Objective-C Method Names\n\nMethod and parameter names typically start as lowercase and then use mixed case.\n\nProper capitalization should be respected, including at the beginning of names.\n\n```objectivec\n// GOOD:\n\n+ (NSURL *)URLWithString:(NSString *)URLString;\n```\n\nThe method name should read like a sentence if possible, meaning you should\nchoose parameter names that flow with the method name. Objective-C method names\ntend to be very long, but this has the benefit that a block of code can almost\nread like prose, thus rendering many implementation comments unnecessary.\n\nUse prepositions and conjunctions like \"with\", \"from\", and \"to\" in the second\nand later parameter names only where necessary to clarify the meaning or\nbehavior of the method.\n\n```objectivec\n// GOOD:\n\n- (void)addTarget:(id)target action:(SEL)action;                          // GOOD; no conjunction needed\n- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;           // GOOD; conjunction clarifies parameter\n- (void)replaceCharactersInRange:(NSRange)aRange\n            withAttributedString:(NSAttributedString *)attributedString;  // GOOD.\n```\n\nIf the method returns an attribute of the receiver, name the method after the\nattribute.\n\n```objectivec\n// GOOD:\n\n/** Returns this instance's sandwich. */\n- (Sandwich *)sandwich;      // GOOD.\n\n- (CGFloat)height;           // GOOD.\n\n// GOOD; Returned value is not an attribute.\n- (UIBackgroundTaskIdentifier)beginBackgroundTask;\n```\n\n```objectivec\n// AVOID:\n\n- (CGFloat)calculateHeight;  // AVOID.\n- (id)theDelegate;           // AVOID.\n```\n\nAn accessor method should be named the same as the object it's getting, but it\nshould not be prefixed with the word `get`. For example:\n\n```objectivec\n// GOOD:\n\n- (id)delegate;     // GOOD.\n```\n\n```objectivec\n// AVOID:\n\n- (id)getDelegate;  // AVOID.\n```\n\nAccessors that return the value of boolean adjectives have method names\nbeginning with `is`, but property names for those methods omit the `is`.\n\nDot notation is used only with property names, not with method names.\n\n```objectivec\n// GOOD:\n\n@property(nonatomic, getter=isGlorious) BOOL glorious;\n// The method for the getter of the property above is:\n// - (BOOL)isGlorious;\n\nBOOL isGood = object.glorious;      // GOOD.\nBOOL isGood = [object isGlorious];  // GOOD.\n```\n\n```objectivec\n// AVOID:\n\nBOOL isGood = object.isGlorious;    // AVOID.\n```\n\n```objectivec\n// GOOD:\n\nNSArray<Frog *> *frogs = [NSArray<Frog *> arrayWithObject:frog];\nNSEnumerator *enumerator = [frogs reverseObjectEnumerator];  // GOOD.\n```\n\n```objectivec\n// AVOID:\n\nNSEnumerator *enumerator = frogs.reverseObjectEnumerator;    // AVOID.\n```\n\nSee [Apple's Guide to Naming\nMethods](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF)\nfor more details on Objective-C naming.\n\nThese guidelines are for Objective-C methods only. C++ method names continue to\nfollow the rules set in the C++ style guide.\n\n<a id=\"Function_Names\"></a>\n\n### Function Names\n\nFunction names should start with a capital letter and have a capital letter for\neach new word (a.k.a. \"[camel case](https://en.wikipedia.org/wiki/Camel_case)\"\nor \"Pascal case\").\n\n```objectivec\n// GOOD:\n\nstatic void AddTableEntry(NSString *tableEntry);\nstatic BOOL DeleteFile(const char *filename);\n```\n\nBecause Objective-C does not provide namespacing, non-static functions should\nhave a [prefix](#prefixes) that minimizes the chance of a name collision.\n\n```objectivec\n// GOOD:\n\nGTM_EXTERN NSTimeZone *GTMGetDefaultTimeZone(void);\nGTM_EXTERN NSString *GTMGetURLScheme(NSURL *URL);\n```\n\n<a id=\"Variable_Names\"></a>\n\n### Variable Names\n\nVariable names typically start with a lowercase and use mixed case to delimit\nwords.\n\nInstance variables have leading underscores. File scope or global variables have\na prefix `g`. For example: `myLocalVariable`, `_myInstanceVariable`,\n`gMyGlobalVariable`.\n\n<a id=\"Common_Variable_Names\"></a>\n\n#### Common Variable Names\n\nReaders should be able to infer the variable type from the name, but do not use\nHungarian notation for syntactic attributes, such as the static type of a\nvariable (int or pointer).\n\nFile scope or global variables (as opposed to constants) declared outside the\nscope of a method or function should be rare, and should have the prefix `g`.\n\n```objectivec\n// GOOD:\n\nstatic int gGlobalCounter;\n```\n\n<a id=\"Instance_Variables\"></a>\n\n#### Instance Variables\n\nInstance variable names are mixed case and should be prefixed with an\nunderscore, like `_usernameTextField`.\n\nNOTE: Google's previous convention for Objective-C ivars was a trailing\nunderscore. Existing projects may opt to continue using trailing underscores in\nnew code in order to maintain consistency within the project codebase.\nConsistency of prefix or suffix underscores should be maintained within each\nclass.\n\n<a id=\"Constants\"></a>\n\n#### Constants\n\nConstant symbols (const global and static variables and constants created\nwith #define) should use mixed case to delimit words.\n\nGlobal and file scope constants should have an appropriate [prefix](#prefixes).\n\n```objectivec\n// GOOD:\n\n/** The domain for GTL service errors. */\nGTL_EXTERN NSString *const GTLServiceErrorDomain;\n\n/** An enumeration of GTL service error codes. */\ntypedef NS_ENUM(int32_t, GTLServiceError) {\n  /** An error code indicating that a query result was missing. */\n  GTLServiceErrorQueryResultMissing = -3000,\n  /** An error code indicating that the query timed out. */\n  GTLServiceErrorQueryTimedOut      = -3001,\n};\n```\n\nBecause Objective-C does not provide namespacing, constants with external\nlinkage should have a prefix that minimizes the chance of a name collision,\ntypically like `ClassNameConstantName` or `ClassNameEnumName`.\n\nFor interoperability with Swift code, enumerated values should have names that\nextend the typedef name:\n\n```objectivec\n// GOOD:\n\n/** An enumeration of supported display tinges. */\ntypedef NS_ENUM(int32_t, DisplayTinge) {\n  DisplayTingeGreen = 1,\n  DisplayTingeBlue = 2,\n};\n```\n\nA lowercase k can be used as a standalone prefix for constants of static storage\nduration declared within implementation files:\n\n```objectivec\n// GOOD:\n\nstatic const int kFileCount = 12;\nstatic NSString *const kUserKey = @\"kUserKey\";\n```\n\nNOTE: Previous convention was for public constant names to begin with a\nlowercase k followed by a project-specific [prefix](#prefixes). This practice is\nno longer recommended.\n\n<a id=\"Types_and_Declarations\"></a>\n\n## Types and Declarations\n\n<a id=\"Method_Declarations\"></a>\n\n### Method Declarations\n\nAs shown in the [example](#Example), the recommended order\nfor declarations in an `@interface` declaration are: properties, class methods,\ninitializers, and then finally instance methods. The class methods section\nshould begin with any convenience constructors.\n\n<a id=\"Local_Variables\"></a>\n\n### Local Variables\n\nDeclare variables in the narrowest practical scopes, and close to their use.\nInitialize variables in their declarations.\n\n```objectivec\n// GOOD:\n\nCLLocation *location = [self lastKnownLocation];\nfor (int meters = 1; meters < 10; meters++) {\n  reportFrogsWithinRadius(location, meters);\n}\n```\n\nOccasionally, efficiency will make it more appropriate to declare a variable\noutside the scope of its use. This example declares meters separate from\ninitialization, and needlessly sends the lastKnownLocation message each time\nthrough the loop:\n\n```objectivec\n// AVOID:\n\nint meters;                                         // AVOID.\nfor (meters = 1; meters < 10; meters++) {\n  CLLocation *location = [self lastKnownLocation];  // AVOID.\n  reportFrogsWithinRadius(location, meters);\n}\n```\n\nUnder Automatic Reference Counting, strong and weak pointers to Objective-C\nobjects are automatically initialized to `nil`, so explicit initialization to\n`nil` is not required for those common cases. However, automatic initialization\ndoes *not* occur for many Objective-C pointer types, including object pointers\ndeclared with the `__unsafe_unretained` ownership qualifier and CoreFoundation\nobject pointer types. When in doubt, prefer to initialize all Objective-C\nlocal variables.\n\n### Static Variables\n\nWhen file scope variable/constant declarations in an implementation file do not\nneed to be referenced outside that file, declare them static (or in an anonymous\nnamespace in Objective-C++). Do not declare file scope variables or constants\nwith static storage duration (or in anonymous namespaces in Objective-C++) in .h\nfiles.\n\n```objectivec\n// GOOD:\n\n// file: Foo.m\nstatic const int FOORequestLimit = 5;\n```\n\n```objectivec\n// AVOID:\n\n// file: Foo.h\nstatic const int FOORequestLimit = 5;  // AVOID.\n```\n\n<a id=\"Unsigned_Integers\"></a>\n\n### Unsigned Integers\n\nAvoid unsigned integers except when matching types used by system interfaces.\n\nSubtle errors crop up when doing math or counting down to zero using unsigned\nintegers. Rely only on signed integers in math expressions except when matching\nNSUInteger in system interfaces.\n\n```objectivec\n// GOOD:\n\nNSUInteger numberOfObjects = array.count;\nfor (NSInteger counter = numberOfObjects - 1; counter >= 0; --counter)\n```\n\n```objectivec\n// AVOID:\n\nfor (NSUInteger counter = numberOfObjects - 1; counter >= 0; --counter)  // AVOID.\n```\n\nUnsigned integers may be used for flags and bitmasks, though often NS_OPTIONS or\nNS_ENUM will be more appropriate.\n\n<a id=\"Types_with_Inconsistent_Sizes\"></a>\n\n### Types with Inconsistent Sizes\n\nBe aware that types long, NSInteger, NSUInteger and CGFloat have sizes that\ndiffer in 32- and 64-bit builds. Their use is appropriate when matching system\ninterfaces but should be avoided when dealing with APIs that\nrequire exact sizing, e.g., proto APIs.\n\n```objectivec\n// GOOD:\n\nint32_t scalar1 = proto.intValue;\n\nint64_t scalar2 = proto.longValue;\n\nNSUInteger numberOfObjects = array.count;\n\nCGFloat offset = view.bounds.origin.x;\n```\n\n```objectivec\n// AVOID:\n\nNSInteger scalar2 = proto.longValue;  // AVOID.\n```\n\nFile and buffer sizes often exceed 32-bit limits, so they should be declared\nusing `int64_t`, not with `long`, `NSInteger`, or `NSUInteger`.\n\n<a id=\"Floating_Point_Constants\"></a>\n\n#### Floating Point Constants\n\nWhen defining `CGFloat` constants, please keep in mind the following.\n\nPreviously for projects targeting 32-bit platforms, using `float` literals\n(numbers with the `f` suffix) could be necessary to avoid type-conversion\nwarnings.\n\nSince all Google iOS projects are now targeting only 64-bit runtime, `CGFloat`\nconstants may omit the suffix (use `double` values). However, teams may choose\nto continue using `float` numbers for legacy code consistency, until they\neventually migrate to `double` values everywhere. Avoid a mixture of `float`\nand `double` values in the same code.\n\n```objectivec\n// GOOD:\n\n// Good since CGFloat is double\nstatic const CGFloat kHorizontalMargin = 8.0;\nstatic const CGFloat kVerticalMargin = 12.0;\n\n// This is OK as long as all values for CGFloat constants in your project are float\nstatic const CGFloat kHorizontalMargin = 8.0f;\nstatic const CGFloat kVerticalMargin = 12.0f;\n```\n\n```objectivec\n// AVOID:\n\n// Avoid a mixture of float and double constants\nstatic const CGFloat kHorizontalMargin = 8.0f;\nstatic const CGFloat kVerticalMargin = 12.0;\n```\n\n<a id=\"Comments\"></a>\n\n## Comments\n\nComments are absolutely vital to keeping our code readable. The following rules\ndescribe what you should comment and where. But remember: while comments are\nimportant, the best code is self-documenting. Giving sensible names to types and\nvariables is much better than using obscure names and then trying to explain\nthem through comments.\n\nPay attention to punctuation, spelling, and grammar; it is easier to read\nwell-written comments than badly written ones.\n\nComments should be as readable as narrative text, with proper capitalization and\npunctuation. In many cases, complete sentences are more readable than sentence\nfragments. Shorter comments, such as comments at the end of a line of code, can\nsometimes be less formal, but use a consistent style.\n\nWhen writing your comments, write for your audience: the next contributor who\nwill need to understand your code. Be generous—the next one may be you!\n\n<a id=\"File_Comments\"></a>\n\n### File Comments\n\nA file may optionally start with a description of its contents.\n\nEvery file may contain the following items, in order\n  * License boilerplate if necessary. Choose the appropriate boilerplate for the\n    license used by the project.\n  * A basic description of the contents of the file if necessary.\n\nIf you make significant changes to a file with an author line, consider deleting\nthe author line since revision history already provides a more detailed and\naccurate record of authorship.\n\n\n<a id=\"Declaration_Comments\"></a>\n\n### Declaration Comments\n\nEvery non-trivial interface, public and private, should have an accompanying\ncomment describing its purpose and how it fits into the larger picture.\n\nComments should be used to document classes, properties, ivars, functions,\ncategories, protocol declarations, and enums.\n\n\n```objectivec\n// GOOD:\n\n/**\n * A delegate for NSApplication to handle notifications about app\n * launch and shutdown. Owned by the main app controller.\n */\n@interface MyAppDelegate : NSObject {\n  /**\n   * The background task in progress, if any. This is initialized\n   * to the value UIBackgroundTaskInvalid.\n   */\n  UIBackgroundTaskIdentifier _backgroundTaskID;\n}\n\n/** The factory that creates and manages fetchers for the app. */\n@property(nonatomic) GTMSessionFetcherService *fetcherService;\n\n@end\n```\n\n[Doxygen](https://doxygen.nl)-style comments are encouraged for interfaces as\nthey are parsed by Xcode\nto display formatted documentation. There is a wide variety of\n[Doxygen commands](https://www.doxygen.nl/manual/commands.html);\nuse them consistently within a project.\n\nIf you have already described an interface in detail in the comments at the top\nof your file, feel free to simply state, \"See comment at top of file for a\ncomplete description\", but be sure to have some sort of comment.\n\nAdditionally, each method should have a comment explaining its function,\narguments, return value, thread or queue assumptions, and any side effects.\nDocumentation comments should be in the header for public methods, or\nimmediately preceding the method for non-trivial private methods.\n\nUse descriptive form (\"Opens the file\") rather than imperative form (\"Open the\nfile\") for method and function comments. The comment describes the function; it\ndoes not tell the function what to do.\n\nDocument the thread usage assumptions the class, properties, or methods make, if\nany. If an instance of the class can be accessed by multiple threads, take extra\ncare to document the rules and invariants surrounding multithreaded use.\n\nAny sentinel values for properties and ivars, such as `NULL` or `-1`, should be\ndocumented in comments.\n\nDeclaration comments explain how a method or function is used. Comments\nexplaining how a method or function is implemented should be with the\nimplementation rather than with the declaration.\n\nDeclaration comments may be omitted on test case classes and test methods\nif comments would communicate no additional information beyond the method's\nname. Utility methods in tests or test-specific classes (such as helpers) should\nbe commented.\n\n<a id=\"Implementation_Comments\"></a>\n\n### Implementation Comments\n\nProvide comments explaining tricky, subtle, or complicated sections of code.\n\n```objectivec\n// GOOD:\n\n// Set the property to nil before invoking the completion handler to\n// avoid the risk of reentrancy leading to the callback being\n// invoked again.\nCompletionHandler handler = self.completionHandler;\nself.completionHandler = nil;\nhandler();\n```\n\nWhen useful, also provide comments about implementation approaches that were\nconsidered or abandoned.\n\nEnd-of-line comments should be separated from the code by at least 2 spaces. If\nyou have several comments on subsequent lines, it can often be more readable to\nline them up.\n\n```objectivec\n// GOOD:\n\n[self doSomethingWithALongName];  // Two spaces before the comment.\n[self doSomethingShort];          // More spacing to align the comment.\n```\n\n\n<a id=\"Disambiguating_Symbols\"></a>\n\n### Disambiguating Symbols\n\nWhere needed to avoid ambiguity, use backticks or vertical bars to quote\nvariable names and symbols in comments in preference to using quotation marks\nor naming the symbols inline.\n\nIn Doxygen-style comments, prefer demarcating symbols with a monospace text\ncommand, such as [`@c`](https://www.doxygen.nl/manual/commands.html#cmdc).\n\nDemarcation helps provide clarity when a symbol is a common word that might make\nthe sentence read like it was poorly constructed. A common example is the symbol\n`count`:\n\n```objectivec\n// GOOD:\n\n// Sometimes `count` will be less than zero.\n```\n\nor when quoting something which already contains quotes\n\n```objectivec\n// GOOD:\n\n// Remember to call `StringWithoutSpaces(\"foo bar baz\")`\n```\n\nBackticks or vertical bars are not needed when a symbol is self-apparent.\n\n```objectivec\n// GOOD:\n\n// This class serves as a delegate to GTMDepthCharge.\n```\n\nDoxygen formatting is also suitable for identifying symbols.\n\n```objectivec\n// GOOD:\n\n/** @param maximum The highest value for @c count. */\n```\n\n<a id=\"Object_Ownership\"></a>\n\n### Object Ownership\n\nFor objects not managed by ARC, make the pointer ownership model as explicit as\npossible when it falls outside the most common Objective-C usage idioms.\n\n<a id=\"Manual_Reference_Counting\"></a>\n\n#### Manual Reference Counting\n\nInstance variables for NSObject-derived objects are presumed to be retained; if\nthey are not retained, they should be either commented as weak or declared with\nthe `__weak` lifetime qualifier.\n\nAn exception is in Mac software for instance variables labeled as `@IBOutlets`,\nwhich are presumed to not be retained.\n\nWhere instance variables are pointers to Core Foundation, C++, and other\nnon-Objective-C objects, they should always be declared with strong and weak\ncomments to indicate which pointers are and are not retained. Core Foundation\nand other non-Objective-C object pointers require explicit memory management,\neven when building for automatic reference counting.\n\nExamples of strong and weak declarations:\n\n```objectivec\n// GOOD:\n\n@interface MyDelegate : NSObject\n\n@property(nonatomic) NSString *doohickey;\n@property(nonatomic, weak) NSString *parent;\n\n@end\n\n\n@implementation MyDelegate {\n  IBOutlet NSButton *_okButton;  // Normal NSControl; implicitly weak on Mac only\n\n  AnObjcObject *_doohickey;  // My doohickey\n  __weak MyObjcParent *_parent;  // To send messages back (owns this instance)\n\n  // non-NSObject pointers...\n  CWackyCPPClass *_wacky;  // Strong, some cross-platform object\n  CFDictionaryRef *_dict;  // Strong\n}\n@end\n```\n\n<a id=\"Automatic_Reference_Counting\"></a>\n\n#### Automatic Reference Counting\n\nObject ownership and lifetime are explicit when using ARC, so no additional\ncomments are required for automatically retained objects.\n\n<a id=\"C_Language_Features\"></a>\n\n## C Language Features\n\n<a id=\"Macros\"></a>\n\n### Macros\n\nAvoid macros, especially where `const` variables, enums, Xcode snippets, or C\nfunctions may be used instead.\n\nMacros make the code you see different from the code the compiler sees. Modern C\nrenders traditional uses of macros for constants and utility functions\nunnecessary. Macros should only be used when there is no other solution\navailable.\n\nWhere a macro is needed, use a unique name to avoid the risk of a symbol\ncollision in the compilation unit. If practical, keep the scope limited by\n`#undefining` the macro after its use.\n\nMacro names should use `SHOUTY_SNAKE_CASE`—all uppercase letters with\nunderscores between words. Function-like macros may use C function naming\npractices. Do not define macros that appear to be C or Objective-C keywords.\n\n```objectivec\n// GOOD:\n\n#define GTM_EXPERIMENTAL_BUILD ...      // GOOD\n\n// Assert unless X > Y\n#define GTM_ASSERT_GT(X, Y) ...         // GOOD, macro style.\n\n// Assert unless X > Y\n#define GTMAssertGreaterThan(X, Y) ...  // GOOD, function style.\n```\n\n```objectivec\n// AVOID:\n\n#define kIsExperimentalBuild ...        // AVOID\n\n#define unless(X) if(!(X))              // AVOID\n```\n\nAvoid macros that expand to unbalanced C or Objective-C constructs. Avoid macros\nthat introduce scope, or may obscure the capturing of values in blocks.\n\nAvoid macros that generate class, property, or method definitions in\nheaders to be used as public API. These only make the code hard to\nunderstand, and the language already has better ways of doing this.\n\nAvoid macros that generate method implementations, or that generate declarations\nof variables that are later used outside of the macro. Macros shouldn't make\ncode hard to understand by hiding where and how a variable is declared.\n\n```objectivec\n// AVOID:\n\n#define ARRAY_ADDER(CLASS) \\\n  -(void)add ## CLASS ## :(CLASS *)obj toArray:(NSMutableArray *)array\n\nARRAY_ADDER(NSString) {\n  if (array.count > 5) {              // AVOID -- where is 'array' defined?\n    ...\n  }\n}\n```\n\nExamples of acceptable macro use include assertion and debug logging macros\nthat are conditionally compiled based on build settings—often, these are\nnot compiled into release builds.\n\n<a id=\"Nonstandard_Extensions\"></a>\n\n### Nonstandard Extensions\n\nNonstandard extensions to C/Objective-C may not be used unless otherwise\nspecified.\n\nCompilers support various extensions that are not part of standard C. Examples\ninclude compound statement expressions (e.g. `foo = ({ int x; Bar(&x); x })`).\n\n#### The `__typeof__` Keyword\n\nThe `__typeof__` keyword is allowed in cases where the type doesn't aid in\nclarity for the reader. The `__typeof__` keyword is encouraged over other\nsimilar keywords (e.g., the `typeof` keyword) as it is supported in all language\nvariants.\n\n```objectivec\n// GOOD:\n\n  __weak __typeof__(self) weakSelf = self;\n```\n\n```objectivec\n// AVOID:\n\n  __typeof__(data) copiedData = [data copy];  // AVOID.\n  __weak typeof(self) weakSelf = self;        // AVOID.\n```\n\n#### The `__auto_type` Keyword and Type Deduction\n\nType deduction using the `__auto_type` keyword is allowed only for local\nvariables of block and function pointer types. Avoid type deduction if a typedef\nalready exists for the block or pointer type.\n\n```objectivec\n// GOOD:\n\n__auto_type block = ^(NSString *arg1, int arg2) { ... };\n__auto_type functionPointer = &MyFunction;\n\ntypedef void(^SignInCallback)(Identity *, NSError *);\nSignInCallback signInCallback = ^(Identity *identity, NSError *error) { ... };\n```\n\n```objectivec\n// AVOID:\n\n__auto_type button = [self createButtonForInfo:info];\n__auto_type viewController = [[MyCustomViewControllerClass alloc] initWith...];\n\ntypedef void(^SignInCallback)(Identity *, NSError *);\n__auto_type signInCallback = ^(Identity *identity, NSError *error) { ... };\n```\n\n#### Approved Nonstandard Extensions\n\n*   The `__attribute__` keyword is approved as it is used in Apple API\n    declarations.\n*   The binary form of the conditional operator, `A ?: B`, is approved.\n\n<a id=\"Cocoa_and_Objective-C_Features\"></a>\n\n## Cocoa and Objective-C Features\n\n<a id=\"Identify_Designated_Initializer\"></a>\n\n### Identify Designated Initializers\n\nClearly identify your designated initializer(s).\n\nIt is important for subclassing that a class clearly identify its designated\ninitializers. This allows a subclass to override a subset of initializers to\ninitialize subclass state or invoke a new designated initializer provided by the\nsubclass. Clearly identified designated initializers also make tracing through\nand debugging initialization code easier.\n\nPrefer identifying designated initializers by annotating them with designated\ninitializer attributes, e.g., `NS_DESIGNATED_INITIALIZER`. Declare designated\ninitializers in comments when designated initializer attributes are not\navailable. Prefer a single designated initializer unless there is a compelling\nreason or requirement for multiple designated initializers.\n\nSupport initializers inherited from superclasses by\n[overriding superclass designated initializers](#Override_Designated_Initializer)\nto ensure that all inherited initializers are directed through subclass\ndesignated initializers. When there is a compelling reason or requirement that\nan inherited initializer should not be supported, the initializer may be\nannotated with availability attributes (e.g., `NS_UNAVAILABLE`) to discourage\nusage; however, note that availability attributes alone do not completely\nprotect against invalid initialization.\n\n<a id=\"Override_Designated_Initializer\"></a>\n\n### Override Designated Initializers\n\nWhen writing a subclass that requires a new designated initializer, make sure\nyou override any designated initializers of the superclass.\n\nWhen declaring designated initializers on a class, remember that any\ninitializers that were considered designated initializers on the superclass\nbecome convenience initializers of the subclass unless declared otherwise.\nFailure to override superclass designated initializers can result in bugs due to\ninvalid initialization using superclass initializers. To avoid invalid\ninitialization, ensure convenience initializers call through to a designated\ninitializer.\n\n<a id=\"Overridden_NSObject_Method_Placement\"></a>\n\n### Overridden NSObject Method Placement\n\nPut overridden methods of NSObject at the top of an `@implementation`.\n\nThis commonly applies to (but is not limited to) the `init...`, `copyWithZone:`,\nand `dealloc` methods. The `init...` methods should be grouped together,\nincluding those `init...` methods that are not `NSObject` overrides, followed by\nother typical `NSObject` methods such as `description`, `isEqual:`, and `hash`.\n\nConvenience class factory methods for creating instances may precede the\n`NSObject` methods.\n\n<a id=\"Initialization\"></a>\n\n### Initialization\n\nDon't initialize instance variables to `0` or `nil` in the `init` method; doing\nso is redundant.\n\nAll instance variables for a newly allocated object are [initialized\nto](https://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/ObjectAllocation/ObjectAllocation.html)\n`0` (except for isa), so don't clutter up the init method by re-initializing\nvariables to `0` or `nil`.\n\n<a id=\"Instance_Variables_In_Headers_Should_Be_@protected_or_@private\"></a>\n\n### Instance Variables In Headers Should Be @protected or @private\n\nInstance variables should typically be declared in implementation files or\nauto-synthesized by properties. When ivars are declared in a header file, they\nshould be marked `@protected` or `@private`.\n\n```objectivec\n// GOOD:\n\n@interface MyClass : NSObject {\n @protected\n  id _myInstanceVariable;\n}\n@end\n```\n\n<a id=\"Avoid_+new\"></a>\n\n### Do Not Use +new\n\nDo not invoke the `NSObject` class method `new`, nor override it in a subclass.\n`+new` is rarely used and contrasts greatly with initializer usage. Instead, use\n`+alloc` and `-init` methods to instantiate retained objects.\n\n<a id=\"Keep_the_Public_API_Simple\"></a>\n\n### Keep the Public API Simple\n\nKeep your class simple; avoid \"kitchen-sink\" APIs. If a method doesn't need to\nbe public, keep it out of the public interface.\n\nUnlike C++, Objective-C doesn't differentiate between public and private\nmethods; any message may be sent to an object. As a result, avoid placing\nmethods in the public API unless they are actually expected to be used by a\nconsumer of the class. This helps reduce the likelihood they'll be called when\nyou're not expecting it. This includes methods that are being overridden from\nthe parent class.\n\nSince internal methods are not really private, it's easy to accidentally\noverride a superclass's \"private\" method, thus making a very difficult bug to\nsquash. In general, private methods should have a fairly unique name that will\nprevent subclasses from unintentionally overriding them.\n\n<a id=\"#import_and_#include\"></a>\n\n### #import and #include\n\n`#import` Objective-C and Objective-C++ headers, and `#include` C/C++ headers.\n\nC/C++ headers include other C/C++ headers using `#include`. Using `#import`\non C/C++ headers prevents future inclusions using `#include` and could result in\nunintended compilation behavior.\n\nC/C++ headers should provide their own `#define` guard.\n\n<a id=\"Order_of_Includes\"></a>\n\n### Order of Includes\n\nThe standard order for header inclusion is the related header, operating system\nheaders, language library headers, and finally groups of headers for other\ndependencies.\n\nThe related header precedes others to ensure it has no hidden dependencies.\nFor implementation files the related header is the header file.\nFor test files the related header is the header containing the tested interface.\n\nSeparate each non-empty group of includes with one blank line. Within each group\nthe includes should be ordered alphabetically.\n\nImport headers using their path relative to the project's source directory.\n\n```objectivec\n// GOOD:\n\n#import \"ProjectX/BazViewController.h\"\n\n#import <Foundation/Foundation.h>\n\n#include <unistd.h>\n#include <vector>\n\n#include \"base/basictypes.h\"\n#include \"base/integral_types.h\"\n#import \"base/mac/FOOComplexNumberSupport\"\n#include \"util/math/mathutil.h\"\n\n#import \"ProjectX/BazModel.h\"\n#import \"Shared/Util/Foo.h\"\n```\n\n<a id=\"Use_Umbrella_Headers_for_System_Frameworks\"></a>\n\n### Use Umbrella Headers for System Frameworks\n\nImport umbrella headers for system frameworks and system libraries rather than\ninclude individual files.\n\nWhile it may seem tempting to include individual system headers from a framework\nsuch as Cocoa or Foundation, in fact it's less work on the compiler if you\ninclude the top-level root framework. The root framework is generally\npre-compiled and can be loaded much more quickly. In addition, remember to use\n`@import` or `#import` rather than `#include` for Objective-C frameworks.\n\n```objectivec\n// GOOD:\n\n@import UIKit;     // GOOD.\n#import <Foundation/Foundation.h>     // GOOD.\n```\n\n```objectivec\n// AVOID:\n\n#import <Foundation/NSArray.h>        // AVOID.\n#import <Foundation/NSString.h>\n...\n```\n\n### Avoid Messaging the Current Object Within Initializers and `-dealloc`\n\nCode in initializers and `-dealloc` should avoid invoking instance methods when\npossible.\n\nSuperclass initialization completes before subclass initialization. Until all\nclasses have had a chance to initialize their instance state any method\ninvocation on self may lead to a subclass operating on uninitialized instance\nstate.\n\nA similar issue exists for `-dealloc`, where a method invocation may cause a\nclass to operate on state that has been deallocated.\n\nOne case where this is less obvious is property accessors. These can be\noverridden just like any other selector. Whenever practical, directly assign to\nand release ivars in initializers and `-dealloc`, rather than rely on accessors.\n\n```objectivec\n// GOOD:\n\n- (instancetype)init {\n  self = [super init];\n  if (self) {\n    _bar = 23;  // GOOD.\n  }\n  return self;\n}\n```\n\nBeware of factoring common initialization code into helper methods:\n\n-   Methods can be overridden in subclasses, either deliberately, or\n    accidentally due to naming collisions.\n-   When editing a helper method, it may not be obvious that the code is being\n    run from an initializer.\n\n```objectivec\n// AVOID:\n\n- (instancetype)init {\n  self = [super init];\n  if (self) {\n    self.bar = 23;  // AVOID.\n    [self sharedMethod];  // AVOID. Fragile to subclassing or future extension.\n  }\n  return self;\n}\n```\n\n```objectivec\n// GOOD:\n\n- (void)dealloc {\n  [_notifier removeObserver:self];  // GOOD.\n}\n```\n\n```objectivec\n// AVOID:\n\n- (void)dealloc {\n  [self removeNotifications];  // AVOID.\n}\n```\n\nThere are common cases where a class may need to use properties and methods\nprovided by a superclass during initialization. This commonly occurs for classes\nderived from UIKit and AppKit base classes, among other base classes. Use your\njudgement and knowledge of common practice when deciding whether to make an\nexception to this rule.\n\n### Avoid redundant property access\n\nCode should avoid redundant property access. Prefer to assign a property value\nto a local variable when the property value is not expected to change and needs\nto be used multiple times.\n\n```objc\n// GOOD:\n\nUIView *view = self.view;\nUIScrollView *scrollView = self.scrollView;\n[scrollView.leadingAnchor constraintEqualToAnchor:view.leadingAnchor].active = YES;\n[scrollView.trailingAnchor constraintEqualToAnchor:view.trailingAnchor].active = YES;\n```\n\n```objc\n// AVOID:\n\n[self.scrollView.loadingAnchor constraintEqualToAnchor:self.view.loadingAnchor].active = YES;\n[self.scrollView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;\n```\n\nWhen repeatedly referencing chained property invocations, prefer to capture the\nrepeated expression in a local variable:\n\n```objc\n// AVOID:\n\nfoo.bar.baz.field1 = 10;\nfoo.bar.baz.field2 = @\"Hello\";\nfoo.bar.baz.field3 = 2.71828183;\n```\n\n```objc\n// GOOD:\n\nBaz *baz = foo.bar.baz;\nbaz.field1 = 10;\nbaz.field2 = @\"Hello\";\nbaz.field3 = 2.71828183;\n```\n\nRedundantly accessing the same properties results in multiple message dispatches\nto fetch the same value, and under ARC requires retains and releases of any\nreturned objects; the compiler cannot optimize away these extra operations,\nleading to slower execution and substantial increases in binary size.\n\n\n<a id=\"Mutables_Copies_Ownership\"></a>\n\n### Mutables, Copies and Ownership\n\nFor [Foundation and other hierarchies containing both immutable and mutable\nsubclasses](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html)\na mutable subclass may be substituted for an immutable so long as the\nimmutable's contract is honored.\n\nThe most common example of this sort of substitution are ownership transfers,\nparticularly for return values. In these cases an additional copy is not\nnecessary and returning the mutable subclass is more efficient.\n[Callers are expected to treat return values as their declared type](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW67),\nand thus the return value will be treated as an immutable going forward.\n\n```objectivec\n// GOOD:\n\n- (NSArray *)listOfThings {\n  NSMutableArray *generatedList = [NSMutableArray array];\n  for (NSInteger i = 0; i < _someLimit; i++) {\n    [generatedList addObject:[self thingForIndex:i]];\n  }\n  // Copy not necessary, ownership of generatedList is transferred.\n  return generatedList;\n}\n```\n\nThis rule also applies to classes where only a mutable variant exists so long as\nthe ownership transfer is clear. Protos are a common example.\n\n```objectivec\n// GOOD:\n\n- (SomeProtoMessage *)someMessageForValue:(BOOL)value {\n  SomeProtoMessage *message = [SomeProtoMessage message];\n  message.someValue = value;\n  return message;\n}\n```\n\nIt is not necessary to create a local immutable copy of a mutable type to match\nthe method signature of a method being called so long as the mutable argument\nwill not change for the duration of the method call. Called methods are expected\nto treat arguments as the declared type, and take\n[defensive copies](#Defensive_Copies)\n([referred to by Apple as \"snapshots\"](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW68))\nif they intend to retain those arguments beyond the duration of the call.\n\n```objectivec\n// AVOID:\n\nNSMutableArray *updatedThings = [NSMutableArray array];\n[updatedThings addObject:newThing];\n[_otherManager updateWithCurrentThings:[updatedThings copy]];  // AVOID\n```\n\n<a id=\"Defensive_Copies\"></a>\n<a id=\"Setters_copy_NSStrings\"></a>\n\n### Copy Potentially Mutable Objects\n\nCode receiving and retaining collections or other types with\n[mutable variants](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html)\nshould consider that the passed object may be mutable, and thus an immutable or\nmutable copy should be retained instead of the original object. In particular,\ninitializers and setters\n[should copy instead of retaining objects whose types have mutable variants](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW68).\n\nSynthesized accessors should use the `copy` keyword to ensure the generated code\nmatches these expectations.\n\nNOTE: [The `copy` property keyword only affects the synthesized setter and has\nno effect on\ngetters](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW27).\nSince property keywords have no effect on direct ivar access custom accessors\nmust implement the same copy semantics.\n\n```objectivec\n// GOOD:\n\n@property(nonatomic, copy) NSString *name;\n@property(nonatomic, copy) NSSet<FilterThing *> *filters;\n\n- (instancetype)initWithName:(NSString *)name\n                     filters:(NSSet<FilterThing *> *)filters {\n  self = [super init];\n  if (self) {\n    _name = [name copy];\n    _filters = [filters copy];\n  }\n  return self;\n}\n\n- (void)setFilters:(NSSet<FilterThing *> *)filters {\n  // Ensure that we retain an immutable collection.\n  _filters = [filters copy];\n}\n```\n\nSimilarly, getters must return types that match the contract expectations of the\nimmutable types they return.\n\n```objectivec\n// GOOD:\n\n\n@implementation Foo {\n  NSMutableArray<ContentThing *> *_currentContent;\n}\n\n- (NSArray<ContentThing *> *)currentContent {\n  return [_currentContent copy];\n}\n\n```\n\nAll Objective-C protos are mutable and typically should be copied rather than\nretained\n[except in clear cases of ownership transfer](#Mutables_Copies_Ownership).\n\n```objectivec\n// GOOD:\n\n- (void)setFooMessage:(FooMessage *)fooMessage {\n  // Copy proto to ensure no other retainer can mutate our value.\n  _fooMessage = [fooMessage copy];\n}\n\n- (FooMessage *)fooMessage {\n  // Copy proto to return so that caller cannot mutate our value.\n  return [_fooMessage copy];\n}\n```\n\nAsynchronous code should copy potentially mutable objects prior to dispatch.\nObjects captured by blocks are retained but not copied.\n\n```objectivec\n// GOOD:\n\n- (void)doSomethingWithThings:(NSArray<Thing *> *)things {\n  NSArray<Thing *> *thingsToWorkOn = [things copy];\n  dispatch_async(_workQueue, ^{\n    for (id<Thing> thing in thingsToWorkOn) {\n      ...\n    }\n  });\n}\n```\n\nNOTE: It is unnecessary to copy objects that do not have mutable variants, e.g.\n`NSURL`, `NSNumber`, `NSDate`, `UIColor`, etc.\n\n<a id=\"Use_Lightweight_Generics_to_Document_Contained_Types\"></a>\n\n### Use Lightweight Generics to Document Contained Types\n\nAll projects compiling on Xcode 7 or newer versions should make use of the\nObjective-C lightweight generics notation to type contained objects.\n\nEvery `NSArray`, `NSDictionary`, or `NSSet` reference should be declared using\nlightweight generics for improved type safety and to explicitly document usage.\n\n```objectivec\n// GOOD:\n\n@property(nonatomic, copy) NSArray<Location *> *locations;\n@property(nonatomic, copy, readonly) NSSet<NSString *> *identifiers;\n\nNSMutableArray<MyLocation *> *mutableLocations = [otherObject.locations mutableCopy];\n```\n\nIf the fully-annotated types become complex, consider using a typedef to\npreserve readability.\n\n```objectivec\n// GOOD:\n\ntypedef NSSet<NSDictionary<NSString *, NSDate *> *> TimeZoneMappingSet;\nTimeZoneMappingSet *timeZoneMappings = [TimeZoneMappingSet setWithObjects:...];\n```\n\nUse the most descriptive common superclass or protocol available. In the most\ngeneric case when nothing else is known, declare the collection to be explicitly\nheterogeneous using id.\n\n```objectivec\n// GOOD:\n\n@property(nonatomic, copy) NSArray<id> *unknowns;\n```\n\n<a id=\"Avoid_Throwing_Exceptions\"></a>\n\n### Avoid Throwing Exceptions\n\nDon't `@throw` Objective-C exceptions, but you should be prepared to catch them\nfrom third-party or OS calls.\n\nThis follows the recommendation to use error objects for error delivery in\n[Apple's Introduction to Exception Programming Topics for\nCocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Exceptions/Exceptions.html).\n\nWe do compile with `-fobjc-exceptions` (mainly so we get `@synchronized`), but\nwe don't `@throw`. Use of `@try`, `@catch`, and `@finally` are allowed when\nrequired to properly use 3rd party code or libraries. If you do use them, please\ndocument exactly which methods you expect to throw.\n\n<a id=\"nil_Checks\"></a>\n\n### `nil` Checks\n\nAvoid `nil` pointer checks that exist only to prevent sending messages to `nil`.\nSending a message to `nil` [reliably\nreturns](http://www.sealiesoftware.com/blog/archive/2012/2/29/objc_explain_return_value_of_message_to_nil.html)\n`nil` as a pointer, zero as an integer or floating-point value, structs\ninitialized to `0`, and `_Complex` values equal to `{0, 0}`.\n\n```objectivec\n// AVOID:\n\nif (dataSource) {  // AVOID.\n  [dataSource moveItemAtIndex:1 toIndex:0];\n}\n```\n\n```objectivec\n// GOOD:\n\n[dataSource moveItemAtIndex:1 toIndex:0];  // GOOD.\n```\n\nNote that this applies to `nil` as a message target, not as a parameter value.\nIndividual methods may or may not safely handle `nil` parameter values.\n\nNote too that this is distinct from checking C/C++ pointers and block pointers\nagainst `NULL`, which the runtime does not handle and will cause your\napplication to crash. You still need to make sure you do not dereference a\n`NULL` pointer.\n\n### Nullability\n\nInterfaces can be decorated with nullability annotations to describe how the\ninterface should be used and how it behaves. Use of nullability regions (e.g.,\n`NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END`) and explicit nullability\nannotations are both accepted. Prefer using the `_Nullable` and `_Nonnull`\nkeywords over the `__nullable` and `__nonnull` keywords. For Objective-C methods\nand properties prefer using the context-sensitive, non-underscored keywords,\ne.g., `nonnull` and `nullable`.\n\n```objectivec\n// GOOD:\n\n/** A class representing an owned book. */\n@interface GTMBook : NSObject\n\n/** The title of the book. */\n@property(nonatomic, readonly, copy, nonnull) NSString *title;\n\n/** The author of the book, if one exists. */\n@property(nonatomic, readonly, copy, nullable) NSString *author;\n\n/** The owner of the book. Setting nil resets to the default owner. */\n@property(nonatomic, copy, null_resettable) NSString *owner;\n\n/** Initializes a book with a title and an optional author. */\n- (nonnull instancetype)initWithTitle:(nonnull NSString *)title\n                               author:(nullable NSString *)author\n    NS_DESIGNATED_INITIALIZER;\n\n/** Returns nil because a book is expected to have a title. */\n- (nullable instancetype)init;\n\n@end\n\n/** Loads books from the file specified by the given path. */\nNSArray<GTMBook *> *_Nullable GTMLoadBooksFromFile(NSString *_Nonnull path);\n```\n\n```objectivec\n// AVOID:\n\nNSArray<GTMBook *> *__nullable GTMLoadBooksFromTitle(NSString *__nonnull path);\n```\n\nDo not assume that a pointer is not null based on a nonnull qualifier, because\nthe compiler only checks a subset of such cases, and does not guarantee that the\npointer is not null. Avoid intentionally violating nullability semantics\nof function, method, and property declarations.\n\n<a id=\"BOOL_Pitfalls\"></a>\n\n### BOOL Pitfalls\n\n<a id=\"BOOL_Expressions_Conversions\"></a>\n#### BOOL Expressions and Conversions\n\nBe careful when converting general integral values to `BOOL`. Avoid comparing\ndirectly with `YES` or comparing multiple `BOOL` values with comparison\noperators.\n\n`BOOL` on some Apple platforms (notably Intel macOS, watchOS, and 32-bit iOS)\nis defined as a signed `char`, so it may have values other than `YES` (`1`) and\n`NO` (`0`). Do not cast or convert general integral values directly to `BOOL`.\n\nCommon mistakes include casting or converting an array's size, a pointer value,\nor the result of a bitwise logic operation to a `BOOL`. These operations can\ndepend on the value of the last byte of the integer value and result in an\nunexpected `NO` value. Operations with NS_OPTIONS values and flag masking are\nespecially common errors.\n\nWhen converting a general integral value to a `BOOL`, use conditional operators\nto return a `YES` or `NO` value.\n\nYou can safely interchange and convert `BOOL`, `_Bool` and `bool` (see C++ Std\n4.7.4, 4.12 and C99 Std 6.3.1.2). Use `BOOL` in Objective-C method signatures.\n\nUsing logical operators (`&&`, `||` and `!`) with `BOOL` is also valid and will\nreturn values that can be safely converted to `BOOL` without the need for a\nconditional operator.\n\n```objectivec\n// AVOID:\n\n- (BOOL)isBold {\n  return [self fontTraits] & NSFontBoldTrait;  // AVOID.\n}\n- (BOOL)isValid {\n  return [self stringValue];  // AVOID.\n}\n- (BOOL)isLongEnough {\n  return (BOOL)([self stringValue].count);  // AVOID.\n}\n```\n\n```objectivec\n// GOOD:\n\n- (BOOL)isBold {\n  return ([self fontTraits] & NSFontBoldTrait) ? YES : NO;\n}\n- (BOOL)isValid {\n  return [self stringValue] != nil;\n}\n- (BOOL)isLongEnough {\n  return [self stringValue].count > 0;\n}\n- (BOOL)isEnabled {\n  return [self isValid] && [self isBold];\n}\n```\n\nDon't directly compare `BOOL` variables directly with `YES`. Not only is\nit harder to read for those well-versed in C, but the first point above\ndemonstrates that return values may not always be what you expect.\n\n```objectivec\n// AVOID:\n\nBOOL great = [foo isGreat];\nif (great == YES) {  // AVOID.\n  // ...be great!\n}\n```\n\n```objectivec\n// GOOD:\n\nBOOL great = [foo isGreat];\nif (great) {         // GOOD.\n  // ...be great!\n}\n```\n\nDon't directly compare `BOOL` values using comparison operators. `BOOL`\nvalues that are true may not be equal. Use logical operators in place\nof bitwise comparisons of `BOOL` values.\n\n```objectivec\n// AVOID:\n\nif (oldBOOLValue != newBOOLValue) {  // AVOID.\n  // ... code that should only run when the value changes.\n}\n```\n\n```objectivec\n// GOOD:\n\nif ((!oldBoolValue && newBoolValue) || (oldBoolValue && !newBoolValue)) {  // GOOD.\n  // ... code that should only run when the value changes.\n}\n\n// GOOD, the results of logical operators on BOOLs are safe to compare.\nif (!oldBoolValue != !newBoolValue) {\n  // ... code that should only run when the value changes.\n}\n```\n\n#### BOOL Literals\n\nThe [BOOL NSNumber literals](https://clang.llvm.org/docs/ObjectiveCLiterals.html#nsnumber-literals)\nare `@YES` and `@NO` which are equivalent to `[NSNumber numberWithBool:...]`.\n\nAvoid using [boxed expressions](https://clang.llvm.org/docs/ObjectiveCLiterals.html#boxed-expressions)\nto create BOOL values, including simple expressions like `@(YES)`.\nBoxed expressions suffer from [the same pitfalls as other BOOL expressions]\n(#BOOL_Expressions_Conversions) as boxing general integral values can\nproduce true or false `NSNumbers` that are not equal to `@YES` and `@NO`.\n\nWhen converting a general integral value to a BOOL literal, use conditional\noperators to convert to `@YES` or `@NO`. Do not embed a conditional operator\ninside a boxed expression as this is equivalent to boxing general integral\nvalues even when the result of the operation is a BOOL.\n\n```objectivec\n// AVOID:\n\n[_boolArray addValue:@(YES)];  // AVOID boxing even in simple cases.\nNSNumber *isBold = @(self.fontTraits & NSFontBoldTrait);  // AVOID.\nNSNumber *hasContent = @([self stringValue].length);  // AVOID.\nNSNumber *isValid = @([self stringValue]);  // AVOID.\nNSNumber *isStringNotNil = @([self stringValue] ? YES : NO);  // AVOID.\n```\n\n```objectivec\n// GOOD:\n\n[_boolArray addValue:@YES];  // GOOD.\nNSNumber *isBold = self.fontTraits & NSFontBoldTrait ? @YES : @NO;  // GOOD.\nNSNumber *hasContent = [self stringValue].length ? @YES : @NO;  // GOOD.\nNSNumber *isValid = [self stringValue] ? @YES : @NO;  // GOOD.\nNSNumber *isStringNotNil = [self stringValue] ? @YES : @NO;  // GOOD.\n```\n\n<a id=\"Interfaces_Without_Instance_Variables\"></a>\n<a id=\"interfaces-without-instance-variables\"></a>\n\n### Containers Without Instance Variables\n\nOmit the empty set of braces on interfaces, class extensions, and\nimplementations without any instance variable declarations.\n\n```objectivec\n// GOOD:\n\n@interface MyClass : NSObject\n// Does a lot of stuff.\n- (void)fooBarBam;\n@end\n\n@interface MyClass ()\n- (void)classExtensionMethod;\n@end\n\n@implementation MyClass\n// Actual implementation.\n@end\n```\n\n```objectivec\n// AVOID:\n\n@interface MyClass : NSObject {\n}\n// Does a lot of stuff.\n- (void)fooBarBam;\n@end\n\n@interface MyClass () {\n}\n- (void)classExtensionMethod;\n@end\n\n@implementation MyClass {\n}\n// Actual implementation.\n@end\n```\n\n<a id=\"Cocoa_Patterns\"></a>\n\n## Cocoa Patterns\n\n<a id=\"Delegate_Pattern\"></a>\n\n### Delegate Pattern\n\nDelegates, target objects, and block pointers should not be retained when doing\nso would create a retain cycle.\n\nTo avoid causing a retain cycle, a delegate or target pointer should be released\nas soon as it is clear there will no longer be a need to message the object.\n\nIf there is no clear time at which the delegate or target pointer is no longer\nneeded, the pointer should only be retained weakly.\n\nBlock pointers cannot be retained weakly. To avoid causing retain cycles in the\nclient code, block pointers should be used for callbacks only where they can be\nexplicitly released after they have been called or once they are no longer\nneeded. Otherwise, callbacks should be done via weak delegate or target\npointers.\n\n<a id=\"Objective-C++\"></a>\n\n## Objective-C++\n\n<a id=\"Style_Matches_the_Language\"></a>\n\n### Style Matches the Language\n\nWithin an Objective-C++ source file, follow the style for the language of the\nfunction or method you're implementing. In order to minimize clashes between the\ndiffering naming styles when mixing Cocoa/Objective-C and C++, follow the style\nof the method being implemented.\n\nFor code in an `@implementation` block, use the Objective-C naming rules. For\ncode in a method of a C++ class, use the C++ naming rules.\n\nFor code in an Objective-C++ file outside of a class implementation, be\nconsistent within the file.\n\n```objectivec++\n// GOOD:\n\n// file: cross_platform_header.h\n\nclass CrossPlatformAPI {\n public:\n  ...\n  int DoSomethingPlatformSpecific();  // impl on each platform\n private:\n  int an_instance_var_;\n};\n\n// file: mac_implementation.mm\n#include \"cross_platform_header.h\"\n\n/** A typical Objective-C class, using Objective-C naming. */\n@interface MyDelegate : NSObject {\n @private\n  int _instanceVar;\n  CrossPlatformAPI* _backEndObject;\n}\n\n- (void)respondToSomething:(id)something;\n\n@end\n\n@implementation MyDelegate\n\n- (void)respondToSomething:(id)something {\n  // bridge from Cocoa through our C++ backend\n  _instanceVar = _backEndObject->DoSomethingPlatformSpecific();\n  NSString* tempString = [NSString stringWithFormat:@\"%d\", _instanceVar];\n  NSLog(@\"%@\", tempString);\n}\n\n@end\n\n/** The platform-specific implementation of the C++ class, using C++ naming. */\nint CrossPlatformAPI::DoSomethingPlatformSpecific() {\n  NSString* temp_string = [NSString stringWithFormat:@\"%d\", an_instance_var_];\n  NSLog(@\"%@\", temp_string);\n  return [temp_string intValue];\n}\n```\n\nProjects may opt to use an 80 column line length limit for consistency with\nGoogle's C++ style guide.\n\n<a id=\"Spacing_and_Formatting\"></a>\n\n## Spacing and Formatting\n\n<a id=\"Spaces_vs._Tabs\"></a>\n\n### Spaces vs. Tabs\n\nUse only spaces, and indent 2 spaces at a time. We use spaces for indentation.\nDo not use tabs in your code.\n\nYou should set your editor to emit spaces when you hit the tab key, and to trim\ntrailing spaces on lines.\n\n<a id=\"Line_Length\"></a>\n\n### Line Length\n\nThe maximum line length for Objective-C files is 100 columns.\n\n<a id=\"Method_Declarations_and_Definitions\"></a>\n\n### Method Declarations and Definitions\n\nOne space should be used between the `-` or `+` and the return type. In general,\nthere should be no spacing in the parameter list except between parameters.\n\nMethods should look like this:\n\n```objectivec\n// GOOD:\n\n- (void)doSomethingWithString:(NSString *)theString {\n  ...\n}\n```\n\nThe spacing before the asterisk is optional. When adding new code, be consistent\nwith the surrounding file's style.\n\nIf a method declaration does not fit on a single line, put each parameter on its\nown line. All lines except the first should be indented at least four spaces.\nColons before parameters should be aligned on all lines. If the colon before the\nparameter on the first line of a method declaration is positioned such that\ncolon alignment would cause indentation on a subsequent line to be less than\nfour spaces, then colon alignment is only required for all lines except the\nfirst. If a parameter declared after the `:` in a method declaration or\ndefinition would cause the line limit to be exceeded, wrap the content to the\nnext line indented by at least four spaces.\n\n```objectivec\n// GOOD:\n\n- (void)doSomethingWithFoo:(GTMFoo *)theFoo\n                      rect:(NSRect)theRect\n                  interval:(float)theInterval {\n  ...\n}\n\n- (void)shortKeyword:(GTMFoo *)theFoo\n            longerKeyword:(NSRect)theRect\n    someEvenLongerKeyword:(float)theInterval\n                    error:(NSError **)theError {\n  ...\n}\n\n- (id<UIAdaptivePresentationControllerDelegate>)\n    adaptivePresentationControllerDelegateForViewController:(UIViewController *)viewController;\n\n- (void)presentWithAdaptivePresentationControllerDelegate:\n    (id<UIAdaptivePresentationControllerDelegate>)delegate;\n\n- (void)updateContentHeaderViewForExpansionToContentOffset:(CGPoint)contentOffset\n                                            withController:\n                                                (GTMCollectionExpansionController *)controller;\n\n```\n\n### Function Declarations and Definitions\n\nPrefer putting the return type on the same line as the function name and append\nall parameters on the same line if they will fit. Wrap parameter lists which do\nnot fit on a single line as you would wrap arguments in a [function\ncall](#Function_Calls).\n\n```objectivec\n// GOOD:\n\nNSString *GTMVersionString(int majorVersion, int minorVersion) {\n  ...\n}\n\nvoid GTMSerializeDictionaryToFileOnDispatchQueue(\n    NSDictionary<NSString *, NSString *> *dictionary,\n    NSString *filename,\n    dispatch_queue_t queue) {\n  ...\n}\n```\n\nFunction declarations and definitions should also satisfy the following\nconditions:\n\n*   The opening parenthesis must always be on the same line as the function\n    name.\n*   If you cannot fit the return type and the function name on a single line,\n    break between them and do not indent the function name.\n*   There should never be a space before the opening parenthesis.\n*   There should never be a space between function parentheses and parameters.\n*   The open curly brace is always on the end of the last line of the function\n    declaration, not the start of the next line.\n*   The close curly brace is either on the last line by itself or on the same\n    line as the open curly brace.\n*   There should be a space between the close parenthesis and the open curly\n    brace.\n*   All parameters should be aligned if possible.\n*   Function scopes should be indented 2 spaces.\n*   Wrapped parameters should have a 4 space indent.\n\n<a id=\"Conditionals\"></a>\n\n### Conditionals\n\nInclude a space after `if`, `while`, `for`, and `switch`, and around comparison\noperators.\n\n```objectivec\n// GOOD:\n\nfor (int i = 0; i < 5; ++i) {\n}\n\nwhile (test) {};\n```\n\nBraces may be omitted when a loop body or conditional statement fits on a single\nline.\n\n```objectivec\n// GOOD:\n\nif (hasSillyName) LaughOutLoud();\n\nfor (int i = 0; i < 10; i++) {\n  BlowTheHorn();\n}\n```\n\n```objectivec\n// AVOID:\n\nif (hasSillyName)\n  LaughOutLoud();               // AVOID.\n\nfor (int i = 0; i < 10; i++)\n  BlowTheHorn();                // AVOID.\n```\n\nIf an `if` clause has an `else` clause, both clauses should use braces.\n\n```objectivec\n// GOOD:\n\nif (hasBaz) {\n  foo();\n} else {  // The else goes on the same line as the closing brace.\n  bar();\n}\n```\n\n```objectivec\n// AVOID:\n\nif (hasBaz) foo();\nelse bar();        // AVOID.\n\nif (hasBaz) {\n  foo();\n} else bar();      // AVOID.\n```\n\nIntentional fall-through to the next case should be documented with a comment\nunless the case has no intervening code before the next case.\n\n```objectivec\n// GOOD:\n\nswitch (i) {\n  case 1:\n    ...\n    break;\n  case 2:\n    j++;\n    // Falls through.\n  case 3: {\n    int k;\n    ...\n    break;\n  }\n  case 4:\n  case 5:\n  case 6: break;\n}\n```\n\n<a id=\"Expressions\"></a>\n\n### Expressions\n\nUse a space around binary operators and assignments. Omit a space for a unary\noperator. Do not add spaces inside parentheses.\n\n```objectivec\n// GOOD:\n\nx = 0;\nv = w * x + y / z;\nv = -y * (x + z);\n```\n\nFactors in an expression may omit spaces.\n\n```objectivec\n// GOOD:\n\nv = w*x + y/z;\n```\n\n<a id=\"Method_Invocations\"></a>\n\n### Method Invocations\n\nMethod invocations should be formatted much like method declarations.\n\nWhen there's a choice of formatting styles, follow the convention already used\nin a given source file. Invocations should have all arguments on one line:\n\n```objectivec\n// GOOD:\n\n[myObject doFooWith:arg1 name:arg2 error:arg3];\n```\n\nor have one argument per line, with colons aligned:\n\n```objectivec\n// GOOD:\n\n[myObject doFooWith:arg1\n               name:arg2\n              error:arg3];\n```\n\nDon't use any of these styles:\n\n```objectivec\n// AVOID:\n\n[myObject doFooWith:arg1 name:arg2  // some lines with >1 arg\n              error:arg3];\n\n[myObject doFooWith:arg1\n               name:arg2 error:arg3];\n\n[myObject doFooWith:arg1\n          name:arg2  // aligning keywords instead of colons\n          error:arg3];\n```\n\nAs with declarations and definitions, when the first keyword is shorter than the\nothers, indent the later lines by at least four spaces, maintaining colon\nalignment:\n\n```objectivec\n// GOOD:\n\n[myObj short:arg1\n          longKeyword:arg2\n    evenLongerKeyword:arg3\n                error:arg4];\n```\n\nInvocations containing multiple inlined blocks may have their parameter names\nleft-aligned at a four space indent.\n\n<a id=\"Function_Calls\"></a>\n\n### Function Calls\n\nFunction calls should include as many parameters as fit on each line, except\nwhere shorter lines are needed for clarity or documentation of the parameters.\n\nContinuation lines for function parameters may be indented to align with the\nopening parenthesis, or may have a four-space indent.\n\n```objectivec\n// GOOD:\n\nCFArrayRef array = CFArrayCreate(kCFAllocatorDefault, objects, numberOfObjects,\n                                 &kCFTypeArrayCallBacks);\n\nNSString *string = NSLocalizedStringWithDefaultValue(@\"FEET\", @\"DistanceTable\",\n    resourceBundle,  @\"%@ feet\", @\"Distance for multiple feet\");\n\nUpdateTally(scores[x] * y + bases[x],  // Score heuristic.\n            x, y, z);\n\nTransformImage(image,\n               x1, x2, x3,\n               y1, y2, y3,\n               z1, z2, z3);\n```\n\nUse local variables with descriptive names to shorten function calls and reduce\nnesting of calls.\n\n```objectivec\n// GOOD:\n\ndouble scoreHeuristic = scores[x] * y + bases[x];\nUpdateTally(scoreHeuristic, x, y, z);\n```\n\n<a id=\"Exceptions\"></a>\n\n### Exceptions\n\nFormat exceptions with `@catch` and `@finally` labels on the same line as the\npreceding `}`. Add a space between the `@` label and the opening brace (`{`), as\nwell as between the `@catch` and the caught object declaration. If you must use\nObjective-C exceptions, format them as follows. However, see [Avoid Throwing\nExceptions](#Avoid_Throwing_Exceptions) for reasons why you should not be using\nexceptions.\n\n```objectivec\n// GOOD:\n\n@try {\n  foo();\n} @catch (NSException *ex) {\n  bar(ex);\n} @finally {\n  baz();\n}\n```\n\n<a id=\"Function_Length\"></a>\n\n### Function Length\n\nPrefer small and focused functions.\n\nLong functions and methods are occasionally appropriate, so no hard limit is\nplaced on function length. If a function exceeds about 40 lines, think about\nwhether it can be broken up without harming the structure of the program.\n\nEven if your long function works perfectly now, someone modifying it in a few\nmonths may add new behavior. This could result in bugs that are hard to find.\nKeeping your functions short and simple makes it easier for other people to read\nand modify your code.\n\nWhen updating legacy code, consider also breaking long functions into smaller\nand more manageable pieces.\n\n<a id=\"Vertical_Whitespace\"></a>\n\n### Vertical Whitespace\n\nUse vertical whitespace sparingly.\n\nTo allow more code to be easily viewed on a screen, avoid putting blank lines\njust inside the braces of functions.\n\nLimit blank lines to one or two between functions and between logical groups of\ncode.\n\n<a id=\"Objective-C_Style_Exceptions\"></a>\n\n## Objective-C Style Exceptions\n\n<a id=\"Indicating_style_exceptions\"></a>\n\n### Indicating style exceptions\n\nLines of code that are not expected to adhere to these style recommendations\nrequire `// NOLINT` at the end of the line or `// NOLINTNEXTLINE` at the end of\nthe previous line. Sometimes it is required that parts of Objective-C code must\nignore these style recommendations (for example code may be machine generated or\ncode constructs are such that its not possible to style correctly).\n\nA `// NOLINT` comment on that line or `// NOLINTNEXTLINE` on the previous line\ncan be used to indicate to the reader that code is intentionally ignoring style\nguidelines. In addition these annotations can also be picked up by automated\ntools such as linters and handle code correctly. Note that there is a single\nspace between `//` and `NOLINT*`.\n"
  },
  {
    "path": "objcguide.xml",
    "content": "<?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google Objective-C Style Guide\">\n  <p>\n    The style guide has moved to\n    <a href=\"https://github.com/google/styleguide/blob/gh-pages/objcguide.md\">objcguide.md</a>\n  </p>\n</GUIDE>\n"
  },
  {
    "path": "pyguide.md",
    "content": "<!--\nAUTHORS:\nPrefer only GitHub-flavored Markdown in external text.\nSee README.md for details.\n-->\n\n# Google Python Style Guide\n\n<!-- markdown=\"1\" is required for GitHub Pages to render the TOC properly. -->\n\n<details markdown=\"1\">\n  <summary>Table of Contents</summary>\n\n-   [1 Background](#s1-background)\n-   [2 Python Language Rules](#s2-python-language-rules)\n    *   [2.1 Lint](#s2.1-lint)\n    *   [2.2 Imports](#s2.2-imports)\n    *   [2.3 Packages](#s2.3-packages)\n    *   [2.4 Exceptions](#s2.4-exceptions)\n    *   [2.5 Mutable Global State](#s2.5-global-variables)\n    *   [2.6 Nested/Local/Inner Classes and Functions](#s2.6-nested)\n    *   [2.7 Comprehensions & Generator Expressions](#s2.7-comprehensions)\n    *   [2.8 Default Iterators and Operators](#s2.8-default-iterators-and-operators)\n    *   [2.9 Generators](#s2.9-generators)\n    *   [2.10 Lambda Functions](#s2.10-lambda-functions)\n    *   [2.11 Conditional Expressions](#s2.11-conditional-expressions)\n    *   [2.12 Default Argument Values](#s2.12-default-argument-values)\n    *   [2.13 Properties](#s2.13-properties)\n    *   [2.14 True/False Evaluations](#s2.14-truefalse-evaluations)\n    *   [2.16 Lexical Scoping](#s2.16-lexical-scoping)\n    *   [2.17 Function and Method Decorators](#s2.17-function-and-method-decorators)\n    *   [2.18 Threading](#s2.18-threading)\n    *   [2.19 Power Features](#s2.19-power-features)\n    *   [2.20 Modern Python: from \\_\\_future\\_\\_ imports](#s2.20-modern-python)\n    *   [2.21 Type Annotated Code](#s2.21-type-annotated-code)\n-   [3 Python Style Rules](#s3-python-style-rules)\n    *   [3.1 Semicolons](#s3.1-semicolons)\n    *   [3.2 Line length](#s3.2-line-length)\n    *   [3.3 Parentheses](#s3.3-parentheses)\n    *   [3.4 Indentation](#s3.4-indentation)\n        +   [3.4.1 Trailing commas in sequences of items?](#s3.4.1-trailing-commas)\n    *   [3.5 Blank Lines](#s3.5-blank-lines)\n    *   [3.6 Whitespace](#s3.6-whitespace)\n    *   [3.7 Shebang Line](#s3.7-shebang-line)\n    *   [3.8 Comments and Docstrings](#s3.8-comments-and-docstrings)\n        +   [3.8.1 Docstrings](#s3.8.1-comments-in-doc-strings)\n        +   [3.8.2 Modules](#s3.8.2-comments-in-modules)\n        +   [3.8.2.1 Test modules](#s3.8.2.1-test-modules)\n        +   [3.8.3 Functions and Methods](#s3.8.3-functions-and-methods)\n        +   [3.8.3.1 Overridden Methods](#s3.8.3.1-overridden-methods)\n        +   [3.8.4 Classes](#s3.8.4-comments-in-classes)\n        +   [3.8.5 Block and Inline Comments](#s3.8.5-block-and-inline-comments)\n        +   [3.8.6 Punctuation, Spelling, and Grammar](#s3.8.6-punctuation-spelling-and-grammar)\n    *   [3.10 Strings](#s3.10-strings)\n        +   [3.10.1 Logging](#s3.10.1-logging)\n        +   [3.10.2 Error Messages](#s3.10.2-error-messages)\n    *   [3.11 Files, Sockets, and similar Stateful Resources](#s3.11-files-sockets-closeables)\n    *   [3.12 TODO Comments](#s3.12-todo-comments)\n    *   [3.13 Imports formatting](#s3.13-imports-formatting)\n    *   [3.14 Statements](#s3.14-statements)\n    *   [3.15 Accessors](#s3.15-accessors)\n    *   [3.16 Naming](#s3.16-naming)\n        +   [3.16.1 Names to Avoid](#s3.16.1-names-to-avoid)\n        +   [3.16.2 Naming Conventions](#s3.16.2-naming-conventions)\n        +   [3.16.3 File Naming](#s3.16.3-file-naming)\n        +   [3.16.4 Guidelines derived from Guido's Recommendations](#s3.16.4-guidelines-derived-from-guidos-recommendations)\n    *   [3.17 Main](#s3.17-main)\n    *   [3.18 Function length](#s3.18-function-length)\n    *   [3.19 Type Annotations](#s3.19-type-annotations)\n        +   [3.19.1 General Rules](#s3.19.1-general-rules)\n        +   [3.19.2 Line Breaking](#s3.19.2-line-breaking)\n        +   [3.19.3 Forward Declarations](#s3.19.3-forward-declarations)\n        +   [3.19.4 Default Values](#s3.19.4-default-values)\n        +   [3.19.5 NoneType](#s3.19.5-nonetype)\n        +   [3.19.6 Type Aliases](#s3.19.6-type-aliases)\n        +   [3.19.7 Ignoring Types](#s3.19.7-ignoring-types)\n        +   [3.19.8 Typing Variables](#s3.19.8-typing-variables)\n        +   [3.19.9 Tuples vs Lists](#s3.19.9-tuples-vs-lists)\n        +   [3.19.10 Type variables](#s3.19.10-typevars)\n        +   [3.19.11 String types](#s3.19.11-string-types)\n        +   [3.19.12 Imports For Typing](#s3.19.12-imports-for-typing)\n        +   [3.19.13 Conditional Imports](#s3.19.13-conditional-imports)\n        +   [3.19.14 Circular Dependencies](#s3.19.14-circular-dependencies)\n        +   [3.19.15 Generics](#s3.19.15-generics)\n        +   [3.19.16 Build Dependencies](#s3.19.16-build-dependencies)\n-   [4 Parting Words](#4-parting-words)\n\n</details>\n\n<a id=\"s1-background\"></a>\n<a id=\"1-background\"></a>\n\n<a id=\"background\"></a>\n## 1 Background \n\nPython is the main dynamic language used at Google. This style guide is a list\nof *dos and don'ts* for Python programs.\n\nTo help you format code correctly, we've created a [settings file for Vim](google_python_style.vim). For Emacs, the default settings should be fine.\n\nMany teams use the [Black](https://github.com/psf/black) or [Pyink](https://github.com/google/pyink)\nauto-formatter to avoid arguing over formatting.\n\n\n<a id=\"s2-python-language-rules\"></a>\n<a id=\"2-python-language-rules\"></a>\n\n<a id=\"python-language-rules\"></a>\n## 2 Python Language Rules \n\n<a id=\"s2.1-lint\"></a>\n<a id=\"21-lint\"></a>\n\n<a id=\"lint\"></a>\n### 2.1 Lint \n\nRun `pylint` over your code using this [pylintrc](https://google.github.io/styleguide/pylintrc).\n\n<a id=\"s2.1.1-definition\"></a>\n<a id=\"211-definition\"></a>\n\n<a id=\"lint-definition\"></a>\n#### 2.1.1 Definition \n\n`pylint`\nis a tool for finding bugs and style problems in Python source code. It finds\nproblems that are typically caught by a compiler for less dynamic languages like\nC and C++. Because of the dynamic nature of Python, some\nwarnings may be incorrect; however, spurious warnings should be fairly\ninfrequent.\n\n<a id=\"s2.1.2-pros\"></a>\n<a id=\"212-pros\"></a>\n\n<a id=\"lint-pros\"></a>\n#### 2.1.2 Pros \n\nCatches easy-to-miss errors like typos, using-vars-before-assignment, etc.\n\n<a id=\"s2.1.3-cons\"></a>\n<a id=\"213-cons\"></a>\n\n<a id=\"lint-cons\"></a>\n#### 2.1.3 Cons \n\n`pylint`\nisn't perfect. To take advantage of it, sometimes we'll need to write around it,\nsuppress its warnings or fix it.\n\n<a id=\"s2.1.4-decision\"></a>\n<a id=\"214-decision\"></a>\n\n<a id=\"lint-decision\"></a>\n#### 2.1.4 Decision \n\nMake sure you run\n`pylint`\non your code.\n\n\nSuppress warnings if they are inappropriate so that other issues are not hidden.\nTo suppress warnings, you can set a line-level comment:\n\n```python\ndef do_PUT(self):  # WSGI name, so pylint: disable=invalid-name\n  ...\n```\n\n`pylint`\nwarnings are each identified by symbolic name (`empty-docstring`)\nGoogle-specific warnings start with `g-`.\n\nIf the reason for the suppression is not clear from the symbolic name, add an\nexplanation.\n\nSuppressing in this way has the advantage that we can easily search for\nsuppressions and revisit them.\n\nYou can get a list of\n`pylint`\nwarnings by doing:\n\n```shell\npylint --list-msgs\n```\n\nTo get more information on a particular message, use:\n\n```shell\npylint --help-msg=invalid-name\n```\n\nPrefer `pylint: disable` to the deprecated older form `pylint: disable-msg`.\n\nUnused argument warnings can be suppressed by deleting the variables at the\nbeginning of the function. Always include a comment explaining why you are\ndeleting it. \"Unused.\" is sufficient. For example:\n\n```python\ndef viking_cafe_order(spam: str, beans: str, eggs: str | None = None) -> str:\n    del beans, eggs  # Unused by vikings.\n    return spam + spam + spam\n```\n\nOther common forms of suppressing this warning include using '`_`' as the\nidentifier for the unused argument or prefixing the argument name with\n'`unused_`', or assigning them to '`_`'. These forms are allowed but no longer\nencouraged. These break callers that pass arguments by name and do not enforce\nthat the arguments are actually unused.\n\n<a id=\"s2.2-imports\"></a>\n<a id=\"22-imports\"></a>\n\n<a id=\"imports\"></a>\n### 2.2 Imports \n\nUse `import` statements for packages and modules only, not for individual types,\nclasses, or functions.\n\n<a id=\"s2.2.1-definition\"></a>\n<a id=\"221-definition\"></a>\n\n<a id=\"imports-definition\"></a>\n#### 2.2.1 Definition \n\nReusability mechanism for sharing code from one module to another.\n\n<a id=\"s2.2.2-pros\"></a>\n<a id=\"222-pros\"></a>\n\n<a id=\"imports-pros\"></a>\n#### 2.2.2 Pros \n\nThe namespace management convention is simple. The source of each identifier is\nindicated in a consistent way; `x.Obj` says that object `Obj` is defined in\nmodule `x`.\n\n<a id=\"s2.2.3-cons\"></a>\n<a id=\"223-cons\"></a>\n\n<a id=\"imports-cons\"></a>\n#### 2.2.3 Cons \n\nModule names can still collide. Some module names are inconveniently long.\n\n<a id=\"s2.2.4-decision\"></a>\n<a id=\"224-decision\"></a>\n\n<a id=\"imports-decision\"></a>\n#### 2.2.4 Decision \n\n*   Use `import x` for importing packages and modules.\n*   Use `from x import y` where `x` is the package prefix and `y` is the module\n    name with no prefix.\n*   Use `from x import y as z` in any of the following circumstances:\n    -   Two modules named `y` are to be imported.\n    -   `y` conflicts with a top-level name defined in the current module.\n    -   `y` conflicts with a common parameter name that is part of the public\n        API (e.g., `features`).\n    -   `y` is an inconveniently long name.\n    -   `y` is too generic in the context of your code (e.g., `from\n        storage.file_system import options as fs_options`).\n*   Use `import y as z` only when `z` is a standard abbreviation (e.g., `import\n    numpy as np`).\n\nFor example the module `sound.effects.echo` may be imported as follows:\n\n```python\nfrom sound.effects import echo\n...\necho.EchoFilter(input, output, delay=0.7, atten=4)\n```\n\nDo not use relative names in imports. Even if the module is in the same package,\nuse the full package name. This helps prevent unintentionally importing a\npackage twice.\n\n<a id=\"imports-exemptions\"></a>\n##### 2.2.4.1 Exemptions \n\nExemptions from this rule:\n\n*   Symbols from the following modules are used to support static analysis and\n    type checking:\n    *   [`typing` module](#typing-imports)\n    *   [`collections.abc` module](#typing-imports)\n    *   [`typing_extensions` module](https://github.com/python/typing_extensions/blob/main/README.md)\n*   Redirects from the\n    [six.moves module](https://six.readthedocs.io/#module-six.moves).\n\n<a id=\"s2.3-packages\"></a>\n<a id=\"23-packages\"></a>\n\n<a id=\"packages\"></a>\n### 2.3 Packages \n\nImport each module using the full pathname location of the module.\n\n<a id=\"s2.3.1-pros\"></a>\n<a id=\"231-pros\"></a>\n\n<a id=\"packages-pros\"></a>\n#### 2.3.1 Pros \n\nAvoids conflicts in module names or incorrect imports due to the module search\npath not being what the author expected. Makes it easier to find modules.\n\n<a id=\"s2.3.2-cons\"></a>\n<a id=\"232-cons\"></a>\n\n<a id=\"packages-cons\"></a>\n#### 2.3.2 Cons \n\nMakes it harder to deploy code because you have to replicate the package\nhierarchy. Not really a problem with modern deployment mechanisms.\n\n<a id=\"s2.3.3-decision\"></a>\n<a id=\"233-decision\"></a>\n\n<a id=\"packages-decision\"></a>\n#### 2.3.3 Decision \n\nAll new code should import each module by its full package name.\n\nImports should be as follows:\n\n```python\nYes:\n  # Reference absl.flags in code with the complete name (verbose).\n  import absl.flags\n  from doctor.who import jodie\n\n  _FOO = absl.flags.DEFINE_string(...)\n```\n\n```python\nYes:\n  # Reference flags in code with just the module name (common).\n  from absl import flags\n  from doctor.who import jodie\n\n  _FOO = flags.DEFINE_string(...)\n```\n\n*(assume this file lives in `doctor/who/` where `jodie.py` also exists)*\n\n```python\nNo:\n  # Unclear what module the author wanted and what will be imported.  The actual\n  # import behavior depends on external factors controlling sys.path.\n  # Which possible jodie module did the author intend to import?\n  import jodie\n```\n\nThe directory the main binary is located in should not be assumed to be in\n`sys.path` despite that happening in some environments. This being the case,\ncode should assume that `import jodie` refers to a third-party or top-level\npackage named `jodie`, not a local `jodie.py`.\n\n\n<a id=\"s2.4-exceptions\"></a>\n<a id=\"24-exceptions\"></a>\n\n<a id=\"exceptions\"></a>\n### 2.4 Exceptions \n\nExceptions are allowed but must be used carefully.\n\n<a id=\"s2.4.1-definition\"></a>\n<a id=\"241-definition\"></a>\n\n<a id=\"exceptions-definition\"></a>\n#### 2.4.1 Definition \n\nExceptions are a means of breaking out of normal control flow to handle errors\nor other exceptional conditions.\n\n<a id=\"s2.4.2-pros\"></a>\n<a id=\"242-pros\"></a>\n\n<a id=\"exceptions-pros\"></a>\n#### 2.4.2 Pros \n\nThe control flow of normal operation code is not cluttered by error-handling\ncode. It also allows the control flow to skip multiple frames when a certain\ncondition occurs, e.g., returning from N nested functions in one step instead of\nhaving to plumb error codes through.\n\n<a id=\"s2.4.3-cons\"></a>\n<a id=\"243-cons\"></a>\n\n<a id=\"exceptions-cons\"></a>\n#### 2.4.3 Cons \n\nMay cause the control flow to be confusing. Easy to miss error cases when making\nlibrary calls.\n\n<a id=\"s2.4.4-decision\"></a>\n<a id=\"244-decision\"></a>\n\n<a id=\"exceptions-decision\"></a>\n#### 2.4.4 Decision \n\nExceptions must follow certain conditions:\n\n-   Make use of built-in exception classes when it makes sense. For example,\n    raise a `ValueError` to indicate a programming mistake like a violated\n    precondition, such as may happen when validating function arguments.\n\n-   Do not use `assert` statements in place of conditionals or validating\n    preconditions. They must not be critical to the application logic. A litmus\n    test would be that the `assert` could be removed without breaking the code.\n    `assert` conditionals are\n    [not guaranteed](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)\n    to be evaluated. For [pytest](https://pytest.org) based tests, `assert` is\n    okay and expected to verify expectations. For\n    example:\n\n    \n    ```python\n    Yes:\n      def connect_to_next_port(self, minimum: int) -> int:\n        \"\"\"Connects to the next available port.\n\n        Args:\n          minimum: A port value greater or equal to 1024.\n\n        Returns:\n          The new minimum port.\n\n        Raises:\n          ConnectionError: If no available port is found.\n        \"\"\"\n        if minimum < 1024:\n          # Note that this raising of ValueError is not mentioned in the doc\n          # string's \"Raises:\" section because it is not appropriate to\n          # guarantee this specific behavioral reaction to API misuse.\n          raise ValueError(f'Min. port must be at least 1024, not {minimum}.')\n        port = self._find_next_open_port(minimum)\n        if port is None:\n          raise ConnectionError(\n              f'Could not connect to service on port {minimum} or higher.')\n        # The code does not depend on the result of this assert.\n        assert port >= minimum, (\n            f'Unexpected port {port} when minimum was {minimum}.')\n        return port\n    ```\n\n    ```python\n    No:\n      def connect_to_next_port(self, minimum: int) -> int:\n        \"\"\"Connects to the next available port.\n\n        Args:\n          minimum: A port value greater or equal to 1024.\n\n        Returns:\n          The new minimum port.\n        \"\"\"\n        assert minimum >= 1024, 'Minimum port must be at least 1024.'\n        # The following code depends on the previous assert.\n        port = self._find_next_open_port(minimum)\n        assert port is not None\n        # The type checking of the return statement relies on the assert.\n        return port\n    ```\n\n\n-   Libraries or packages may define their own exceptions. When doing so they\n    must inherit from an existing exception class. Exception names should end in\n    `Error` and should not introduce repetition (`foo.FooError`).\n\n-   Never use catch-all `except:` statements, or catch `Exception` or\n    `StandardError`, unless you are\n\n    -   re-raising the exception, or\n    -   creating an isolation point in the program where exceptions are not\n        propagated but are recorded and suppressed instead, such as protecting a\n        thread from crashing by guarding its outermost block.\n\n    Python is very tolerant in this regard and `except:` will really catch\n    everything including misspelled names, sys.exit() calls, Ctrl+C interrupts,\n    unittest failures and all kinds of other exceptions that you simply don't\n    want to catch.\n\n-   Minimize the amount of code in a `try`/`except` block. The larger the body\n    of the `try`, the more likely that an exception will be raised by a line of\n    code that you didn't expect to raise an exception. In those cases, the\n    `try`/`except` block hides a real error.\n\n-   Use the `finally` clause to execute code whether or not an exception is\n    raised in the `try` block. This is often useful for cleanup, i.e., closing a\n    file.\n\n<a id=\"s2.5-global-variables\"></a>\n<a id=\"25-global-variables\"></a>\n<a id=\"s2.5-global-state\"></a>\n<a id=\"25-global-state\"></a>\n\n<a id=\"global-variables\"></a>\n### 2.5 Mutable Global State \n\nAvoid mutable global state.\n\n<a id=\"s2.5.1-definition\"></a>\n<a id=\"251-definition\"></a>\n\n<a id=\"global-variables-definition\"></a>\n#### 2.5.1 Definition \n\nModule-level values or class attributes that can get mutated during program\nexecution.\n\n<a id=\"s2.5.2-pros\"></a>\n<a id=\"252-pros\"></a>\n\n<a id=\"global-variables-pros\"></a>\n#### 2.5.2 Pros \n\nOccasionally useful.\n\n<a id=\"s2.5.3-cons\"></a>\n<a id=\"253-cons\"></a>\n\n<a id=\"global-variables-cons\"></a>\n#### 2.5.3 Cons \n\n*   Breaks encapsulation: Such design can make it hard to achieve valid\n    objectives. For example, if global state is used to manage a database\n    connection, then connecting to two different databases at the same time\n    (such as for computing differences during a migration) becomes difficult.\n    Similar problems easily arise with global registries.\n\n*   Has the potential to change module behavior during the import, because\n    assignments to global variables are done when the module is first imported.\n\n<a id=\"s2.5.4-decision\"></a>\n<a id=\"254-decision\"></a>\n\n<a id=\"global-variables-decision\"></a>\n#### 2.5.4 Decision \n\nAvoid mutable global state.\n\nIn those rare cases where using global state is warranted, mutable global\nentities should be declared at the module level or as a class attribute and made\ninternal by prepending an `_` to the name. If necessary, external access to\nmutable global state must be done through public functions or class methods. See\n[Naming](#s3.16-naming) below. Please explain the design reasons why mutable\nglobal state is being used in a comment or a doc linked to from a comment.\n\nModule-level constants are permitted and encouraged. For example:\n`_MAX_HOLY_HANDGRENADE_COUNT = 3` for an internal use constant or\n`SIR_LANCELOTS_FAVORITE_COLOR = \"blue\"` for a public API constant. Constants\nmust be named using all caps with underscores. See [Naming](#s3.16-naming)\nbelow.\n\n<a id=\"s2.6-nested\"></a>\n<a id=\"26-nested\"></a>\n\n<a id=\"nested-classes-functions\"></a>\n### 2.6 Nested/Local/Inner Classes and Functions \n\nNested local functions or classes are fine when used to close over a local\nvariable. Inner classes are fine.\n\n<a id=\"s2.6.1-definition\"></a>\n<a id=\"261-definition\"></a>\n\n<a id=\"nested-classes-functions-definition\"></a>\n#### 2.6.1 Definition \n\nA class can be defined inside of a method, function, or class. A function can be\ndefined inside a method or function. Nested functions have read-only access to\nvariables defined in enclosing scopes.\n\n<a id=\"s2.6.2-pros\"></a>\n<a id=\"262-pros\"></a>\n\n<a id=\"nested-classes-functions-pros\"></a>\n#### 2.6.2 Pros \n\nAllows definition of utility classes and functions that are only used inside of\na very limited scope. Very\n[ADT](https://en.wikipedia.org/wiki/Abstract_data_type)-y. Commonly used for\nimplementing decorators.\n\n<a id=\"s2.6.3-cons\"></a>\n<a id=\"263-cons\"></a>\n\n<a id=\"nested-classes-functions-cons\"></a>\n#### 2.6.3 Cons \n\nNested functions and classes cannot be directly tested. Nesting can make the\nouter function longer and less readable.\n\n<a id=\"s2.6.4-decision\"></a>\n<a id=\"264-decision\"></a>\n\n<a id=\"nested-classes-functions-decision\"></a>\n#### 2.6.4 Decision \n\nThey are fine with some caveats. Avoid nested functions or classes except when\nclosing over a local value other than `self` or `cls`. Do not nest a function\njust to hide it from users of a module. Instead, prefix its name with an \\_ at\nthe module level so that it can still be accessed by tests.\n\n<a id=\"s2.7-comprehensions\"></a>\n<a id=\"s2.7-list_comprehensions\"></a>\n<a id=\"27-list_comprehensions\"></a>\n<a id=\"list_comprehensions\"></a>\n<a id=\"list-comprehensions\"></a>\n\n<a id=\"comprehensions\"></a>\n### 2.7 Comprehensions & Generator Expressions \n\nOkay to use for simple cases.\n\n<a id=\"s2.7.1-definition\"></a>\n<a id=\"271-definition\"></a>\n\n<a id=\"comprehensions-definition\"></a>\n#### 2.7.1 Definition \n\nList, Dict, and Set comprehensions as well as generator expressions provide a\nconcise and efficient way to create container types and iterators without\nresorting to the use of traditional loops, `map()`, `filter()`, or `lambda`.\n\n<a id=\"s2.7.2-pros\"></a>\n<a id=\"272-pros\"></a>\n\n<a id=\"comprehensions-pros\"></a>\n#### 2.7.2 Pros \n\nSimple comprehensions can be clearer and simpler than other dict, list, or set\ncreation techniques. Generator expressions can be very efficient, since they\navoid the creation of a list entirely.\n\n<a id=\"s2.7.3-cons\"></a>\n<a id=\"273-cons\"></a>\n\n<a id=\"comprehensions-cons\"></a>\n#### 2.7.3 Cons \n\nComplicated comprehensions or generator expressions can be hard to read.\n\n<a id=\"s2.7.4-decision\"></a>\n<a id=\"274-decision\"></a>\n\n<a id=\"comprehensions-decision\"></a>\n#### 2.7.4 Decision \n\nComprehensions are allowed, however multiple `for` clauses or filter expressions\nare not permitted. Optimize for readability, not conciseness.\n\n```python\nYes:\n  result = [mapping_expr for value in iterable if filter_expr]\n\n  result = [\n      is_valid(metric={'key': value})\n      for value in interesting_iterable\n      if a_longer_filter_expression(value)\n  ]\n\n  descriptive_name = [\n      transform({'key': key, 'value': value}, color='black')\n      for key, value in generate_iterable(some_input)\n      if complicated_condition_is_met(key, value)\n  ]\n\n  result = []\n  for x in range(10):\n    for y in range(5):\n      if x * y > 10:\n        result.append((x, y))\n\n  return {\n      x: complicated_transform(x)\n      for x in long_generator_function(parameter)\n      if x is not None\n  }\n\n  return (x**2 for x in range(10))\n\n  unique_names = {user.name for user in users if user is not None}\n```\n\n```python\nNo:\n  result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]\n\n  return (\n      (x, y, z)\n      for x in range(5)\n      for y in range(5)\n      if x != y\n      for z in range(5)\n      if y != z\n  )\n```\n\n<a id=\"s2.8-default-iterators-and-operators\"></a>\n\n<a id=\"default-iterators-operators\"></a>\n### 2.8 Default Iterators and Operators \n\nUse default iterators and operators for types that support them, like lists,\ndictionaries, and files.\n\n<a id=\"s2.8.1-definition\"></a>\n<a id=\"281-definition\"></a>\n\n<a id=\"default-iterators-operators-definition\"></a>\n#### 2.8.1 Definition \n\nContainer types, like dictionaries and lists, define default iterators and\nmembership test operators (\"in\" and \"not in\").\n\n<a id=\"s2.8.2-pros\"></a>\n<a id=\"282-pros\"></a>\n\n<a id=\"default-iterators-operators-pros\"></a>\n#### 2.8.2 Pros \n\nThe default iterators and operators are simple and efficient. They express the\noperation directly, without extra method calls. A function that uses default\noperators is generic. It can be used with any type that supports the operation.\n\n<a id=\"s2.8.3-cons\"></a>\n<a id=\"283-cons\"></a>\n\n<a id=\"default-iterators-operators-cons\"></a>\n#### 2.8.3 Cons \n\nYou can't tell the type of objects by reading the method names (unless the\nvariable has type annotations). This is also an advantage.\n\n<a id=\"s2.8.4-decision\"></a>\n<a id=\"284-decision\"></a>\n\n<a id=\"default-iterators-operators-decision\"></a>\n#### 2.8.4 Decision \n\nUse default iterators and operators for types that support them, like lists,\ndictionaries, and files. The built-in types define iterator methods, too. Prefer\nthese methods to methods that return lists, except that you should not mutate a\ncontainer while iterating over it.\n\n```python\nYes:  for key in adict: ...\n      if obj in alist: ...\n      for line in afile: ...\n      for k, v in adict.items(): ...\n```\n\n```python\nNo:   for key in adict.keys(): ...\n      for line in afile.readlines(): ...\n```\n\n<a id=\"s2.9-generators\"></a>\n<a id=\"29-generators\"></a>\n\n<a id=\"generators\"></a>\n### 2.9 Generators \n\nUse generators as needed.\n\n<a id=\"s2.9.1-definition\"></a>\n<a id=\"291-definition\"></a>\n\n<a id=\"generators-definition\"></a>\n#### 2.9.1 Definition \n\nA generator function returns an iterator that yields a value each time it\nexecutes a yield statement. After it yields a value, the runtime state of the\ngenerator function is suspended until the next value is needed.\n\n<a id=\"s2.9.2-pros\"></a>\n<a id=\"292-pros\"></a>\n\n<a id=\"generators-pros\"></a>\n#### 2.9.2 Pros \n\nSimpler code, because the state of local variables and control flow are\npreserved for each call. A generator uses less memory than a function that\ncreates an entire list of values at once.\n\n<a id=\"s2.9.3-cons\"></a>\n<a id=\"293-cons\"></a>\n\n<a id=\"generators-cons\"></a>\n#### 2.9.3 Cons \n\nLocal variables in the generator will not be garbage collected until the\ngenerator is either consumed to exhaustion or itself garbage collected.\n\n<a id=\"s2.9.4-decision\"></a>\n<a id=\"294-decision\"></a>\n\n<a id=\"generators-decision\"></a>\n#### 2.9.4 Decision \n\nFine. Use \"Yields:\" rather than \"Returns:\" in the docstring for generator\nfunctions.\n\nIf the generator manages an expensive resource, make sure to force the clean up.\n\nA good way to do the clean up is by wrapping the generator with a context\nmanager [PEP-0533](https://peps.python.org/pep-0533/).\n\n<a id=\"s2.10-lambda-functions\"></a>\n<a id=\"210-lambda-functions\"></a>\n\n<a id=\"lambdas\"></a>\n### 2.10 Lambda Functions \n\nOkay for one-liners. Prefer generator expressions over `map()` or `filter()`\nwith a `lambda`.\n\n<a id=\"s2.10.1-definition\"></a>\n<a id=\"2101-definition\"></a>\n\n<a id=\"lambdas-definition\"></a>\n#### 2.10.1 Definition \n\nLambdas define anonymous functions in an expression, as opposed to a statement.\n\n<a id=\"s2.10.2-pros\"></a>\n<a id=\"2102-pros\"></a>\n\n<a id=\"lambdas-pros\"></a>\n#### 2.10.2 Pros \n\nConvenient.\n\n<a id=\"s2.10.3-cons\"></a>\n<a id=\"2103-cons\"></a>\n\n<a id=\"lambdas-cons\"></a>\n#### 2.10.3 Cons \n\nHarder to read and debug than local functions. The lack of names means stack\ntraces are more difficult to understand. Expressiveness is limited because the\nfunction may only contain an expression.\n\n<a id=\"s2.10.4-decision\"></a>\n<a id=\"2104-decision\"></a>\n\n<a id=\"lambdas-decision\"></a>\n#### 2.10.4 Decision \n\nLambdas are allowed. If the code inside the lambda function spans multiple lines\nor is longer than 60-80 chars, it might be better to define it as a regular\n[nested function](#lexical-scoping).\n\nFor common operations like multiplication, use the functions from the `operator`\nmodule instead of lambda functions. For example, prefer `operator.mul` to\n`lambda x, y: x * y`.\n\n<a id=\"s2.11-conditional-expressions\"></a>\n<a id=\"211-conditional-expressions\"></a>\n\n<a id=\"conditional-expressions\"></a>\n### 2.11 Conditional Expressions \n\nOkay for simple cases.\n\n<a id=\"s2.11.1-definition\"></a>\n<a id=\"2111-definition\"></a>\n\n<a id=\"conditional-expressions-definition\"></a>\n#### 2.11.1 Definition \n\nConditional expressions (sometimes called a “ternary operator”) are mechanisms\nthat provide a shorter syntax for if statements. For example: `x = 1 if cond\nelse 2`.\n\n<a id=\"s2.11.2-pros\"></a>\n<a id=\"2112-pros\"></a>\n\n<a id=\"conditional-expressions-pros\"></a>\n#### 2.11.2 Pros \n\nShorter and more convenient than an if statement.\n\n<a id=\"s2.11.3-cons\"></a>\n<a id=\"2113-cons\"></a>\n\n<a id=\"conditional-expressions-cons\"></a>\n#### 2.11.3 Cons \n\nMay be harder to read than an if statement. The condition may be difficult to\nlocate if the expression is long.\n\n<a id=\"s2.11.4-decision\"></a>\n<a id=\"2114-decision\"></a>\n\n<a id=\"conditional-expressions-decision\"></a>\n#### 2.11.4 Decision \n\nOkay to use for simple cases. Each portion must fit on one line:\ntrue-expression, if-expression, else-expression. Use a complete if statement\nwhen things get more complicated.\n\n```python\nYes:\n    one_line = 'yes' if predicate(value) else 'no'\n    slightly_split = ('yes' if predicate(value)\n                      else 'no, nein, nyet')\n    the_longest_ternary_style_that_can_be_done = (\n        'yes, true, affirmative, confirmed, correct'\n        if predicate(value)\n        else 'no, false, negative, nay')\n```\n\n```python\nNo:\n    bad_line_breaking = ('yes' if predicate(value) else\n                         'no')\n    portion_too_long = ('yes'\n                        if some_long_module.some_long_predicate_function(\n                            really_long_variable_name)\n                        else 'no, false, negative, nay')\n```\n\n<a id=\"s2.12-default-argument-values\"></a>\n<a id=\"212-default-argument-values\"></a>\n\n<a id=\"default-arguments\"></a>\n### 2.12 Default Argument Values \n\nOkay in most cases.\n\n<a id=\"s2.12.1-definition\"></a>\n<a id=\"2121-definition\"></a>\n\n<a id=\"default-arguments-definition\"></a>\n#### 2.12.1 Definition \n\nYou can specify values for variables at the end of a function's parameter list,\ne.g., `def foo(a, b=0):`. If `foo` is called with only one argument, `b` is set\nto 0. If it is called with two arguments, `b` has the value of the second\nargument.\n\n<a id=\"s2.12.2-pros\"></a>\n<a id=\"2122-pros\"></a>\n\n<a id=\"default-arguments-pros\"></a>\n#### 2.12.2 Pros \n\nOften you have a function that uses lots of default values, but on rare\noccasions you want to override the defaults. Default argument values provide an\neasy way to do this, without having to define lots of functions for the rare\nexceptions. As Python does not support overloaded methods/functions, default\narguments are an easy way of \"faking\" the overloading behavior.\n\n<a id=\"s2.12.3-cons\"></a>\n<a id=\"2123-cons\"></a>\n\n<a id=\"default-arguments-cons\"></a>\n#### 2.12.3 Cons \n\nDefault arguments are evaluated once at module load time. This may cause\nproblems if the argument is a mutable object such as a list or a dictionary. If\nthe function modifies the object (e.g., by appending an item to a list), the\ndefault value is modified.\n\n<a id=\"s2.12.4-decision\"></a>\n<a id=\"2124-decision\"></a>\n\n<a id=\"default-arguments-decision\"></a>\n#### 2.12.4 Decision \n\nOkay to use with the following caveat:\n\nDo not use mutable objects as default values in the function or method\ndefinition.\n\n```python\nYes: def foo(a, b=None):\n         if b is None:\n             b = []\nYes: def foo(a, b: Sequence | None = None):\n         if b is None:\n             b = []\nYes: def foo(a, b: Sequence = ()):  # Empty tuple OK since tuples are immutable.\n         ...\n```\n\n```python\nfrom absl import flags\n_FOO = flags.DEFINE_string(...)\n\nNo:  def foo(a, b=[]):\n         ...\nNo:  def foo(a, b=time.time()):  # Is `b` supposed to represent when this module was loaded?\n         ...\nNo:  def foo(a, b=_FOO.value):  # sys.argv has not yet been parsed...\n         ...\nNo:  def foo(a, b: Mapping = {}):  # Could still get passed to unchecked code.\n         ...\n```\n\n<a id=\"s2.13-properties\"></a>\n<a id=\"213-properties\"></a>\n\n<a id=\"properties\"></a>\n### 2.13 Properties \n\nProperties may be used to control getting or setting attributes that require\ntrivial computations or logic. Property implementations must match the general\nexpectations of regular attribute access: that they are cheap, straightforward,\nand unsurprising.\n\n<a id=\"s2.13.1-definition\"></a>\n<a id=\"2131-definition\"></a>\n\n<a id=\"properties-definition\"></a>\n#### 2.13.1 Definition \n\nA way to wrap method calls for getting and setting an attribute as a standard\nattribute access.\n\n<a id=\"s2.13.2-pros\"></a>\n<a id=\"2132-pros\"></a>\n\n<a id=\"properties-pros\"></a>\n#### 2.13.2 Pros \n\n*   Allows for an attribute access and assignment API rather than\n    [getter and setter](#getters-and-setters) method calls.\n*   Can be used to make an attribute read-only.\n*   Allows calculations to be lazy.\n*   Provides a way to maintain the public interface of a class when the\n    internals evolve independently of class users.\n\n<a id=\"s2.13.3-cons\"></a>\n<a id=\"2133-cons\"></a>\n\n<a id=\"properties-cons\"></a>\n#### 2.13.3 Cons \n\n*   Can hide side-effects much like operator overloading.\n*   Can be confusing for subclasses.\n\n<a id=\"s2.13.4-decision\"></a>\n<a id=\"2134-decision\"></a>\n\n<a id=\"properties-decision\"></a>\n#### 2.13.4 Decision \n\nProperties are allowed, but, like operator overloading, should only be used when\nnecessary and match the expectations of typical attribute access; follow the\n[getters and setters](#getters-and-setters) rules otherwise.\n\nFor example, using a property to simply both get and set an internal attribute\nisn't allowed: there is no computation occurring, so the property is unnecessary\n([make the attribute public instead](#getters-and-setters)). In comparison,\nusing a property to control attribute access or to calculate a *trivially*\nderived value is allowed: the logic is simple and unsurprising.\n\nProperties should be created with the `@property`\n[decorator](#s2.17-function-and-method-decorators). Manually implementing a\nproperty descriptor is considered a [power feature](#power-features).\n\nInheritance with properties can be non-obvious. Do not use properties to\nimplement computations a subclass may ever want to override and extend.\n\n<a id=\"s2.14-truefalse-evaluations\"></a>\n<a id=\"214-truefalse-evaluations\"></a>\n\n<a id=\"truefalse-evaluations\"></a>\n### 2.14 True/False Evaluations \n\nUse the \"implicit\" false if at all possible (with a few caveats).\n\n<a id=\"s2.14.1-definition\"></a>\n<a id=\"2141-definition\"></a>\n\n<a id=\"truefalse-evaluations-definition\"></a>\n#### 2.14.1 Definition \n\nPython evaluates certain values as `False` when in a boolean context. A quick\n\"rule of thumb\" is that all \"empty\" values are considered false, so `0, None,\n[], {}, ''` all evaluate as false in a boolean context.\n\n<a id=\"s2.14.2-pros\"></a>\n<a id=\"2142-pros\"></a>\n\n<a id=\"truefalse-evaluations-pros\"></a>\n#### 2.14.2 Pros \n\nConditions using Python booleans are easier to read and less error-prone. In\nmost cases, they're also faster.\n\n<a id=\"s2.14.3-cons\"></a>\n<a id=\"2143-cons\"></a>\n\n<a id=\"truefalse-evaluations-cons\"></a>\n#### 2.14.3 Cons \n\nMay look strange to C/C++ developers.\n\n<a id=\"s2.14.4-decision\"></a>\n<a id=\"2144-decision\"></a>\n\n<a id=\"truefalse-evaluations-decision\"></a>\n#### 2.14.4 Decision \n\nUse the \"implicit\" false if possible, e.g., `if foo:` rather than `if foo !=\n[]:`. There are a few caveats that you should keep in mind though:\n\n-   Always use `if foo is None:` (or `is not None`) to check for a `None` value.\n    E.g., when testing whether a variable or argument that defaults to `None`\n    was set to some other value. The other value might be a value that's false\n    in a boolean context!\n\n-   Never compare a boolean variable to `False` using `==`. Use `if not x:`\n    instead. If you need to distinguish `False` from `None` then chain the\n    expressions, such as `if not x and x is not None:`.\n\n-   For sequences (strings, lists, tuples), use the fact that empty sequences\n    are false, so `if seq:` and `if not seq:` are preferable to `if len(seq):`\n    and `if not len(seq):` respectively.\n\n-   When handling integers, implicit false may involve more risk than benefit\n    (i.e., accidentally handling `None` as 0). You may compare a value which is\n    known to be an integer (and is not the result of `len()`) against the\n    integer 0.\n\n    ```python\n    Yes: if not users:\n             print('no users')\n\n         if i % 10 == 0:\n             self.handle_multiple_of_ten()\n\n         def f(x=None):\n             if x is None:\n                 x = []\n    ```\n\n    ```python\n    No:  if len(users) == 0:\n             print('no users')\n\n         if not i % 10:\n             self.handle_multiple_of_ten()\n\n         def f(x=None):\n             x = x or []\n    ```\n\n-   Note that `'0'` (i.e., `0` as string) evaluates to true.\n\n-   Note that Numpy arrays may raise an exception in an implicit boolean\n    context. Prefer the `.size` attribute when testing emptiness of a `np.array`\n    (e.g. `if not users.size`).\n\n<a id=\"s2.16-lexical-scoping\"></a>\n<a id=\"216-lexical-scoping\"></a>\n\n<a id=\"lexical-scoping\"></a>\n### 2.16 Lexical Scoping \n\nOkay to use.\n\n<a id=\"s2.16.1-definition\"></a>\n<a id=\"2161-definition\"></a>\n\n<a id=\"lexical-scoping-definition\"></a>\n#### 2.16.1 Definition \n\nA nested Python function can refer to variables defined in enclosing functions,\nbut cannot assign to them. Variable bindings are resolved using lexical scoping,\nthat is, based on the static program text. Any assignment to a name in a block\nwill cause Python to treat all references to that name as a local variable, even\nif the use precedes the assignment. If a global declaration occurs, the name is\ntreated as a global variable.\n\nAn example of the use of this feature is:\n\n```python\ndef get_adder(summand1: float) -> Callable[[float], float]:\n    \"\"\"Returns a function that adds numbers to a given number.\"\"\"\n    def adder(summand2: float) -> float:\n        return summand1 + summand2\n\n    return adder\n```\n\n<a id=\"s2.16.2-pros\"></a>\n<a id=\"2162-pros\"></a>\n\n<a id=\"lexical-scoping-pros\"></a>\n#### 2.16.2 Pros \n\nOften results in clearer, more elegant code. Especially comforting to\nexperienced Lisp and Scheme (and Haskell and ML and ...) programmers.\n\n<a id=\"s2.16.3-cons\"></a>\n<a id=\"2163-cons\"></a>\n\n<a id=\"lexical-scoping-cons\"></a>\n#### 2.16.3 Cons \n\nCan lead to confusing bugs, such as this example based on\n[PEP-0227](https://peps.python.org/pep-0227/):\n\n```python\ni = 4\ndef foo(x: Iterable[int]):\n    def bar():\n        print(i, end='')\n    # ...\n    # A bunch of code here\n    # ...\n    for i in x:  # Ah, i *is* local to foo, so this is what bar sees\n        print(i, end='')\n    bar()\n```\n\nSo `foo([1, 2, 3])` will print `1 2 3 3`,\nnot `1 2 3 4`.\n\n<a id=\"s2.16.4-decision\"></a>\n<a id=\"2164-decision\"></a>\n\n<a id=\"lexical-scoping-decision\"></a>\n#### 2.16.4 Decision \n\nOkay to use.\n\n<a id=\"s2.17-function-and-method-decorators\"></a>\n<a id=\"217-function-and-method-decorators\"></a>\n<a id=\"function-and-method-decorators\"></a>\n\n<a id=\"decorators\"></a>\n### 2.17 Function and Method Decorators \n\nUse decorators judiciously when there is a clear advantage. Avoid `staticmethod`\nand limit use of `classmethod`.\n\n<a id=\"s2.17.1-definition\"></a>\n<a id=\"2171-definition\"></a>\n\n<a id=\"decorators-definition\"></a>\n#### 2.17.1 Definition \n\n[Decorators for Functions and Methods](https://docs.python.org/3/glossary.html#term-decorator)\n(a.k.a \"the `@` notation\"). One common decorator is `@property`, used for\nconverting ordinary methods into dynamically computed attributes. However, the\ndecorator syntax allows for user-defined decorators as well. Specifically, for\nsome function `my_decorator`, this:\n\n```python\nclass C:\n    @my_decorator\n    def method(self):\n        # method body ...\n```\n\nis equivalent to:\n\n```python\nclass C:\n    def method(self):\n        # method body ...\n    method = my_decorator(method)\n```\n\n<a id=\"s2.17.2-pros\"></a>\n<a id=\"2172-pros\"></a>\n\n<a id=\"decorators-pros\"></a>\n#### 2.17.2 Pros \n\nElegantly specifies some transformation on a method; the transformation might\neliminate some repetitive code, enforce invariants, etc.\n\n<a id=\"s2.17.3-cons\"></a>\n<a id=\"2173-cons\"></a>\n\n<a id=\"decorators-cons\"></a>\n#### 2.17.3 Cons \n\nDecorators can perform arbitrary operations on a function's arguments or return\nvalues, resulting in surprising implicit behavior. Additionally, decorators\nexecute at object definition time. For module-level objects (classes, module\nfunctions, ...) this happens at import time. Failures in decorator code are\npretty much impossible to recover from.\n\n<a id=\"s2.17.4-decision\"></a>\n<a id=\"2174-decision\"></a>\n\n<a id=\"decorators-decision\"></a>\n#### 2.17.4 Decision \n\nUse decorators judiciously when there is a clear advantage. Decorators should\nfollow the same import and naming guidelines as functions. A decorator docstring\nshould clearly state that the function is a decorator. Write unit tests for\ndecorators.\n\nAvoid external dependencies in the decorator itself (e.g. don't rely on files,\nsockets, database connections, etc.), since they might not be available when the\ndecorator runs (at import time, perhaps from `pydoc` or other tools). A\ndecorator that is called with valid parameters should (as much as possible) be\nguaranteed to succeed in all cases.\n\nDecorators are a special case of \"top-level code\" - see [main](#s3.17-main) for\nmore discussion.\n\nNever use `staticmethod` unless forced to in order to integrate with an API\ndefined in an existing library. Write a module-level function instead.\n\nUse `classmethod` only when writing a named constructor, or a class-specific\nroutine that modifies necessary global state such as a process-wide cache.\n\n<a id=\"s2.18-threading\"></a>\n<a id=\"218-threading\"></a>\n\n<a id=\"threading\"></a>\n### 2.18 Threading \n\nDo not rely on the atomicity of built-in types.\n\nWhile Python's built-in data types such as dictionaries appear to have atomic\noperations, there are corner cases where they aren't atomic (e.g. if `__hash__`\nor `__eq__` are implemented as Python methods) and their atomicity should not be\nrelied upon. Neither should you rely on atomic variable assignment (since this\nin turn depends on dictionaries).\n\nUse the `queue` module's `Queue` data type as the preferred way to communicate\ndata between threads. Otherwise, use the `threading` module and its locking\nprimitives. Prefer condition variables and `threading.Condition` instead of\nusing lower-level locks.\n\n<a id=\"s2.19-power-features\"></a>\n<a id=\"219-power-features\"></a>\n\n<a id=\"power-features\"></a>\n### 2.19 Power Features \n\nAvoid these features.\n\n<a id=\"s2.19.1-definition\"></a>\n<a id=\"2191-definition\"></a>\n\n<a id=\"power-features-definition\"></a>\n#### 2.19.1 Definition \n\nPython is an extremely flexible language and gives you many fancy features such\nas custom metaclasses, access to bytecode, on-the-fly compilation, dynamic\ninheritance, object reparenting, import hacks, reflection (e.g. some uses of\n`getattr()`), modification of system internals, `__del__` methods implementing\ncustomized cleanup, etc.\n\n<a id=\"s2.19.2-pros\"></a>\n<a id=\"2192-pros\"></a>\n\n<a id=\"power-features-pros\"></a>\n#### 2.19.2 Pros \n\nThese are powerful language features. They can make your code more compact.\n\n<a id=\"s2.19.3-cons\"></a>\n<a id=\"2193-cons\"></a>\n\n<a id=\"power-features-cons\"></a>\n#### 2.19.3 Cons \n\nIt's very tempting to use these \"cool\" features when they're not absolutely\nnecessary. It's harder to read, understand, and debug code that's using unusual\nfeatures underneath. It doesn't seem that way at first (to the original author),\nbut when revisiting the code, it tends to be more difficult than code that is\nlonger but is straightforward.\n\n<a id=\"s2.19.4-decision\"></a>\n<a id=\"2194-decision\"></a>\n\n<a id=\"power-features-decision\"></a>\n#### 2.19.4 Decision \n\nAvoid these features in your code.\n\nStandard library modules and classes that internally use these features are okay\nto use (for example, `abc.ABCMeta`, `dataclasses`, and `enum`).\n\n<a id=\"s2.20-modern-python\"></a>\n<a id=\"220-modern-python\"></a>\n\n<a id=\"modern-python\"></a>\n### 2.20 Modern Python: from \\_\\_future\\_\\_ imports \n\nNew language version semantic changes may be gated behind a special future\nimport to enable them on a per-file basis within earlier runtimes.\n\n<a id=\"s2.20.1-definition\"></a>\n<a id=\"2201-definition\"></a>\n\n<a id=\"modern-python-definition\"></a>\n#### 2.20.1 Definition \n\nBeing able to turn on some of the more modern features via `from __future__\nimport` statements allows early use of features from expected future Python\nversions.\n\n<a id=\"s2.20.2-pros\"></a>\n<a id=\"2202-pros\"></a>\n\n<a id=\"modern-python-pros\"></a>\n#### 2.20.2 Pros \n\nThis has proven to make runtime version upgrades smoother as changes can be made\non a per-file basis while declaring compatibility and preventing regressions\nwithin those files. Modern code is more maintainable as it is less likely to\naccumulate technical debt that will be problematic during future runtime\nupgrades.\n\n<a id=\"s2.20.3-cons\"></a>\n<a id=\"2203-cons\"></a>\n\n<a id=\"modern-python-cons\"></a>\n#### 2.20.3 Cons \n\nSuch code may not work on very old interpreter versions prior to the\nintroduction of the needed future statement. The need for this is more common in\nprojects supporting an extremely wide variety of environments.\n\n<a id=\"s2.20.4-decision\"></a>\n<a id=\"2204-decision\"></a>\n\n<a id=\"modern-python-decision\"></a>\n#### 2.20.4 Decision \n\n##### from \\_\\_future\\_\\_ imports\n\nUse of `from __future__ import` statements is encouraged. It allows a given\nsource file to start using more modern Python syntax features today. Once you no\nlonger need to run on a version where the features are hidden behind a\n`__future__` import, feel free to remove those lines.\n\nIn code that may execute on versions as old as 3.5 rather than >= 3.7, import:\n\n```python\nfrom __future__ import generator_stop\n```\n\nFor more information read the\n[Python future statement definitions](https://docs.python.org/3/library/__future__.html)\ndocumentation.\n\nPlease don't remove these imports until you are confident the code is only ever\nused in a sufficiently modern environment. Even if you do not currently use the\nfeature a specific future import enables in your code today, keeping it in place\nin the file prevents later modifications of the code from inadvertently\ndepending on the older behavior.\n\nUse other `from __future__` import statements as you see fit.\n\n<a id=\"s2.21-type-annotated-code\"></a>\n<a id=\"s2.21-typed-code\"></a>\n<a id=\"221-type-annotated-code\"></a>\n<a id=\"typed-code\"></a>\n\n<a id=\"typed-code\"></a>\n### 2.21 Type Annotated Code \n\nYou can annotate Python code with\n[type hints](https://docs.python.org/3/library/typing.html). Type-check the code\nat build time with a type checking tool like [pytype](https://github.com/google/pytype).\nIn most cases, when feasible, type annotations are in source files. For\nthird-party or extension modules, annotations can be in\n[stub `.pyi` files](https://peps.python.org/pep-0484/#stub-files).\n\n\n<a id=\"s2.21.1-definition\"></a>\n<a id=\"2211-definition\"></a>\n\n<a id=\"typed-code-definition\"></a>\n#### 2.21.1 Definition \n\nType annotations (or \"type hints\") are for function or method arguments and\nreturn values:\n\n```python\ndef func(a: int) -> list[int]:\n```\n\nYou can also declare the type of a variable using similar syntax:\n\n```python\na: SomeType = some_func()\n```\n\n<a id=\"s2.21.2-pros\"></a>\n<a id=\"2212-pros\"></a>\n\n<a id=\"typed-code-pros\"></a>\n#### 2.21.2 Pros \n\nType annotations improve the readability and maintainability of your code. The\ntype checker will convert many runtime errors to build-time errors, and reduce\nyour ability to use [Power Features](#power-features).\n\n<a id=\"s2.21.3-cons\"></a>\n<a id=\"2213-cons\"></a>\n\n<a id=\"typed-code-cons\"></a>\n#### 2.21.3 Cons \n\nYou will have to keep the type declarations up to date.\nYou might see type errors that you think are\nvalid code. Use of a\n[type checker](https://github.com/google/pytype)\nmay reduce your ability to use [Power Features](#power-features).\n\n<a id=\"s2.21.4-decision\"></a>\n<a id=\"2214-decision\"></a>\n\n<a id=\"typed-code-decision\"></a>\n#### 2.21.4 Decision \n\nYou are strongly encouraged to enable Python type analysis when updating code.\nWhen adding or modifying public APIs, include type annotations and enable\nchecking via pytype in the build system. As static analysis is relatively new to\nPython, we acknowledge that undesired side-effects (such as\nwrongly\ninferred types) may prevent adoption by some projects. In those situations,\nauthors are encouraged to add a comment with a TODO or link to a bug describing\nthe issue(s) currently preventing type annotation adoption in the BUILD file or\nin the code itself as appropriate.\n\n<a id=\"s3-python-style-rules\"></a>\n<a id=\"3-python-style-rules\"></a>\n\n<a id=\"python-style-rules\"></a>\n## 3 Python Style Rules \n\n<a id=\"s3.1-semicolons\"></a>\n<a id=\"31-semicolons\"></a>\n\n<a id=\"semicolons\"></a>\n### 3.1 Semicolons \n\nDo not terminate your lines with semicolons, and do not use semicolons to put\ntwo statements on the same line.\n\n<a id=\"s3.2-line-length\"></a>\n<a id=\"32-line-length\"></a>\n\n<a id=\"line-length\"></a>\n### 3.2 Line length \n\nMaximum line length is *80 characters*.\n\nExplicit exceptions to the 80 character limit:\n\n-   Long import statements.\n-   URLs, pathnames, or long flags in comments.\n-   Long string module-level constants not containing whitespace that would be\n    inconvenient to split across lines such as URLs or pathnames.\n    -   Pylint disable comments. (e.g.: `# pylint: disable=invalid-name`)\n\nDo not use a backslash for\n[explicit line continuation](https://docs.python.org/3/reference/lexical_analysis.html#explicit-line-joining).\n\nInstead, make use of Python's\n[implicit line joining inside parentheses, brackets and braces](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining).\nIf necessary, you can add an extra pair of parentheses around an expression.\n\nNote that this rule doesn't prohibit backslash-escaped newlines within strings\n(see [below](#strings)).\n\n```python\nYes: foo_bar(self, width, height, color='black', design=None, x='foo',\n             emphasis=None, highlight=0)\n```\n\n```python\n\nYes: if (width == 0 and height == 0 and\n         color == 'red' and emphasis == 'strong'):\n\n     (bridge_questions.clarification_on\n      .average_airspeed_of.unladen_swallow) = 'African or European?'\n\n     with (\n         very_long_first_expression_function() as spam,\n         very_long_second_expression_function() as beans,\n         third_thing() as eggs,\n     ):\n       place_order(eggs, beans, spam, beans)\n```\n\n```python\n\nNo:  if width == 0 and height == 0 and \\\n         color == 'red' and emphasis == 'strong':\n\n     bridge_questions.clarification_on \\\n         .average_airspeed_of.unladen_swallow = 'African or European?'\n\n     with very_long_first_expression_function() as spam, \\\n           very_long_second_expression_function() as beans, \\\n           third_thing() as eggs:\n       place_order(eggs, beans, spam, beans)\n```\n\nWhen a literal string won't fit on a single line, use parentheses for implicit\nline joining.\n\n```python\nx = ('This will build a very long long '\n     'long long long long long long string')\n```\n\nPrefer to break lines at the highest possible syntactic level. If you must break\na line twice, break it at the same syntactic level both times.\n\n```python\nYes: bridgekeeper.answer(\n         name=\"Arthur\", quest=questlib.find(owner=\"Arthur\", perilous=True))\n\n     answer = (a_long_line().of_chained_methods()\n               .that_eventually_provides().an_answer())\n\n     if (\n         config is None\n         or 'editor.language' not in config\n         or config['editor.language'].use_spaces is False\n     ):\n       use_tabs()\n```\n\n```python\nNo: bridgekeeper.answer(name=\"Arthur\", quest=questlib.find(\n        owner=\"Arthur\", perilous=True))\n\n    answer = a_long_line().of_chained_methods().that_eventually_provides(\n        ).an_answer()\n\n    if (config is None or 'editor.language' not in config or config[\n        'editor.language'].use_spaces is False):\n      use_tabs()\n\n```\n\nWithin comments, put long URLs on their own line if necessary.\n\n```python\nYes:  # See details at\n      # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html\n```\n\n```python\nNo:  # See details at\n     # http://www.example.com/us/developer/documentation/api/content/\\\n     # v2.0/csv_file_name_extension_full_specification.html\n```\n\nMake note of the indentation of the elements in the line continuation examples\nabove; see the [indentation](#s3.4-indentation) section for explanation.\n\n[Docstring](#docstrings) summary lines must remain within the 80 character\nlimit.\n\nIn all other cases where a line exceeds 80 characters, and the\n[Black](https://github.com/psf/black) or [Pyink](https://github.com/google/pyink)\nauto-formatter does not help bring the line below the limit, the line is allowed\nto exceed this maximum. Authors are encouraged to manually break the line up per\nthe notes above when it is sensible.\n\n<a id=\"s3.3-parentheses\"></a>\n<a id=\"33-parentheses\"></a>\n\n<a id=\"parentheses\"></a>\n### 3.3 Parentheses \n\nUse parentheses sparingly.\n\nIt is fine, though not required, to use parentheses around tuples. Do not use\nthem in return statements or conditional statements unless using parentheses for\nimplied line continuation or to indicate a tuple.\n\n```python\nYes: if foo:\n         bar()\n     while x:\n         x = bar()\n     if x and y:\n         bar()\n     if not x:\n         bar()\n     # For a 1 item tuple the ()s are more visually obvious than the comma.\n     onesie = (foo,)\n     return foo\n     return spam, beans\n     return (spam, beans)\n     for (x, y) in dict.items(): ...\n```\n\n```python\nNo:  if (x):\n         bar()\n     if not(x):\n         bar()\n     return (foo)\n```\n\n<a id=\"s3.4-indentation\"></a>\n<a id=\"34-indentation\"></a>\n\n<a id=\"indentation\"></a>\n### 3.4 Indentation \n\nIndent your code blocks with *4 spaces*.\n\nNever use tabs. Implied line continuation should align wrapped elements\nvertically (see [line length examples](#s3.2-line-length)), or use a hanging\n4-space indent. Closing (round, square or curly) brackets can be placed at the\nend of the expression, or on separate lines, but then should be indented the\nsame as the line with the corresponding opening bracket.\n\n```python\nYes:   # Aligned with opening delimiter.\n       foo = long_function_name(var_one, var_two,\n                                var_three, var_four)\n       meal = (spam,\n               beans)\n\n       # Aligned with opening delimiter in a dictionary.\n       foo = {\n           'long_dictionary_key': value1 +\n                                  value2,\n           ...\n       }\n\n       # 4-space hanging indent; nothing on first line.\n       foo = long_function_name(\n           var_one, var_two, var_three,\n           var_four)\n       meal = (\n           spam,\n           beans)\n\n       # 4-space hanging indent; nothing on first line,\n       # closing parenthesis on a new line.\n       foo = long_function_name(\n           var_one, var_two, var_three,\n           var_four\n       )\n       meal = (\n           spam,\n           beans,\n       )\n\n       # 4-space hanging indent in a dictionary.\n       foo = {\n           'long_dictionary_key':\n               long_dictionary_value,\n           ...\n       }\n```\n\n```python\nNo:    # Stuff on first line forbidden.\n       foo = long_function_name(var_one, var_two,\n           var_three, var_four)\n       meal = (spam,\n           beans)\n\n       # 2-space hanging indent forbidden.\n       foo = long_function_name(\n         var_one, var_two, var_three,\n         var_four)\n\n       # No hanging indent in a dictionary.\n       foo = {\n           'long_dictionary_key':\n           long_dictionary_value,\n           ...\n       }\n```\n\n<a id=\"s3.4.1-trailing-comma\"></a>\n<a id=\"s3.4.1-trailing-commas\"></a>\n<a id=\"s3.4.1-trailing_comma\"></a>\n<a id=\"s3.4.1-trailing_commas\"></a>\n<a id=\"341-trailing_comma\"></a>\n<a id=\"341-trailing_commas\"></a>\n<a id=\"trailing_comma\"></a>\n<a id=\"trailing_commas\"></a>\n\n<a id=\"trailing-comma\"></a>\n#### 3.4.1 Trailing commas in sequences of items? \n\nTrailing commas in sequences of items are recommended only when the closing\ncontainer token `]`, `)`, or `}` does not appear on the same line as the final\nelement, as well as for tuples with a single element. The presence of a trailing\ncomma is also used as a hint to our Python code auto-formatter\n[Black](https://github.com/psf/black) or [Pyink](https://github.com/google/pyink)\nto direct it to auto-format the container of items to one item per line when the\n`,` after the final element is present.\n\n```python\nYes:   golomb3 = [0, 1, 3]\n       golomb4 = [\n           0,\n           1,\n           4,\n           6,\n       ]\n```\n\n```python\nNo:    golomb4 = [\n           0,\n           1,\n           4,\n           6,]\n```\n\n<a id=\"s3.5-blank-lines\"></a>\n<a id=\"35-blank-lines\"></a>\n\n<a id=\"blank-lines\"></a>\n### 3.5 Blank Lines \n\nTwo blank lines between top-level definitions, be they function or class\ndefinitions. One blank line between method definitions and between the docstring\nof a `class` and the first method. No blank line following a `def` line. Use\nsingle blank lines as you judge appropriate within functions or methods.\n\nBlank lines need not be anchored to the definition. For example, related\ncomments immediately preceding function, class, and method definitions can make\nsense. Consider if your comment might be more useful as part of the docstring.\n\n<a id=\"s3.6-whitespace\"></a>\n<a id=\"36-whitespace\"></a>\n\n<a id=\"whitespace\"></a>\n### 3.6 Whitespace \n\nFollow standard typographic rules for the use of spaces around punctuation.\n\nNo whitespace inside parentheses, brackets or braces.\n\n```python\nYes: spam(ham[1], {'eggs': 2}, [])\n```\n\n```python\nNo:  spam( ham[ 1 ], { 'eggs': 2 }, [ ] )\n```\n\nNo whitespace before a comma, semicolon, or colon. Do use whitespace after a\ncomma, semicolon, or colon, except at the end of the line.\n\n```python\nYes: if x == 4:\n         print(x, y)\n     x, y = y, x\n```\n\n```python\nNo:  if x == 4 :\n         print(x , y)\n     x , y = y , x\n```\n\nNo whitespace before the open paren/bracket that starts an argument list,\nindexing or slicing.\n\n```python\nYes: spam(1)\n```\n\n```python\nNo:  spam (1)\n```\n\n```python\nYes: dict['key'] = list[index]\n```\n\n```python\nNo:  dict ['key'] = list [index]\n```\n\nNo trailing whitespace.\n\nSurround binary operators with a single space on either side for assignment\n(`=`), comparisons (`==, <, >, !=, <>, <=, >=, in, not in, is, is not`), and\nBooleans (`and, or, not`). Use your better judgment for the insertion of spaces\naround arithmetic operators (`+`, `-`, `*`, `/`, `//`, `%`, `**`, `@`).\n\n```python\nYes: x == 1\n```\n\n```python\nNo:  x<1\n```\n\nNever use spaces around `=` when passing keyword arguments or defining a default\nparameter value, with one exception:\n[when a type annotation is present](#typing-default-values), *do* use spaces\naround the `=` for the default parameter value.\n\n```python\nYes: def complex(real, imag=0.0): return Magic(r=real, i=imag)\nYes: def complex(real, imag: float = 0.0): return Magic(r=real, i=imag)\n```\n\n```python\nNo:  def complex(real, imag = 0.0): return Magic(r = real, i = imag)\nNo:  def complex(real, imag: float=0.0): return Magic(r = real, i = imag)\n```\n\nDon't use spaces to vertically align tokens on consecutive lines, since it\nbecomes a maintenance burden (applies to `:`, `#`, `=`, etc.):\n\n```python\nYes:\n  foo = 1000  # comment\n  long_name = 2  # comment that should not be aligned\n\n  dictionary = {\n      'foo': 1,\n      'long_name': 2,\n  }\n```\n\n```python\nNo:\n  foo       = 1000  # comment\n  long_name = 2     # comment that should not be aligned\n\n  dictionary = {\n      'foo'      : 1,\n      'long_name': 2,\n  }\n```\n\n\n<a id=\"Python_Interpreter\"></a>\n<a id=\"s3.7-shebang-line\"></a>\n<a id=\"37-shebang-line\"></a>\n\n<a id=\"shebang-line\"></a>\n### 3.7 Shebang Line \n\nMost `.py` files do not need to start with a `#!` line. Start the main file of a\nprogram with\n`#!/usr/bin/env python3` (to support virtualenvs) or `#!/usr/bin/python3` per\n[PEP-394](https://peps.python.org/pep-0394/).\n\nThis line is used by the kernel to find the Python interpreter, but is ignored by Python when importing modules. It is only necessary on a file intended to be executed directly.\n\n<a id=\"s3.8-comments-and-docstrings\"></a>\n<a id=\"s3.8-comments\"></a>\n<a id=\"38-comments-and-docstrings\"></a>\n\n<a id=\"documentation\"></a>\n### 3.8 Comments and Docstrings \n\nBe sure to use the right style for module, function, method docstrings and\ninline comments.\n\n<a id=\"s3.8.1-comments-in-doc-strings\"></a>\n<a id=\"381-docstrings\"></a>\n<a id=\"comments-in-doc-strings\"></a>\n\n<a id=\"docstrings\"></a>\n#### 3.8.1 Docstrings \n\nPython uses *docstrings* to document code. A docstring is a string that is the\nfirst statement in a package, module, class or function. These strings can be\nextracted automatically through the `__doc__` member of the object and are used\nby `pydoc`.\n(Try running `pydoc` on your module to see how it looks.) Always use the\nthree-double-quote `\"\"\"` format for docstrings (per\n[PEP 257](https://peps.python.org/pep-0257/)). A docstring should be organized\nas a summary line (one physical line not exceeding 80 characters) terminated by\na period, question mark, or exclamation point. When writing more (encouraged),\nthis must be followed by a blank line, followed by the rest of the docstring\nstarting at the same cursor position as the first quote of the first line. There\nare more formatting guidelines for docstrings below.\n\n<a id=\"s3.8.2-comments-in-modules\"></a>\n<a id=\"382-modules\"></a>\n<a id=\"comments-in-modules\"></a>\n\n<a id=\"module-docs\"></a>\n#### 3.8.2 Modules \n\nEvery file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL).\n\nFiles should start with a docstring describing the contents and usage of the\nmodule.\n```python\n\"\"\"A one-line summary of the module or program, terminated by a period.\n\nLeave one blank line.  The rest of this docstring should contain an\noverall description of the module or program.  Optionally, it may also\ncontain a brief description of exported classes and functions and/or usage\nexamples.\n\nTypical usage example:\n\n  foo = ClassFoo()\n  bar = foo.function_bar()\n\"\"\"\n```\n\n\n<a id=\"s3.8.2.1-test-modules\"></a>\n\n<a id=\"test-docs\"></a>\n##### 3.8.2.1 Test modules \n\nModule-level docstrings for test files are not required. They should be included\nonly when there is additional information that can be provided.\n\nExamples include some specifics on how the test should be run, an explanation of\nan unusual setup pattern, dependency on the external environment, and so on.\n\n```python\n\"\"\"This blaze test uses golden files.\n\nYou can update those files by running\n`blaze run //foo/bar:foo_test -- --update_golden_files` from the `google3`\ndirectory.\n\"\"\"\n```\n\nDocstrings that do not provide any new information should not be used.\n\n```python\n\"\"\"Tests for foo.bar.\"\"\"\n```\n\n<a id=\"s3.8.3-functions-and-methods\"></a>\n<a id=\"383-functions-and-methods\"></a>\n<a id=\"functions-and-methods\"></a>\n\n<a id=\"function-docs\"></a>\n#### 3.8.3 Functions and Methods \n\nIn this section, \"function\" means a method, function, generator, or property.\n\nA docstring is mandatory for every function that has one or more of the\nfollowing properties:\n\n-   being part of the public API\n-   nontrivial size\n-   non-obvious logic\n\nA docstring should give enough information to write a call to the function\nwithout reading the function's code. The docstring should describe the\nfunction's calling syntax and its semantics, but generally not its\nimplementation details, unless those details are relevant to how the function is\nto be used. For example, a function that mutates one of its arguments as a side\neffect should note that in its docstring. Otherwise, subtle but important\ndetails of a function's implementation that are not relevant to the caller are\nbetter expressed as comments alongside the code than within the function's\ndocstring.\n\nThe docstring may be descriptive-style (`\"\"\"Fetches rows from a Bigtable.\"\"\"`)\nor imperative-style (`\"\"\"Fetch rows from a Bigtable.\"\"\"`), but the style should\nbe consistent within a file. The docstring for a `@property` data descriptor\nshould use the same style as the docstring for an attribute or a\n<a href=\"#doc-function-args\">function argument</a> (`\"\"\"The Bigtable path.\"\"\"`,\nrather than `\"\"\"Returns the Bigtable path.\"\"\"`).\n\nCertain aspects of a function should be documented in special sections, listed\nbelow. Each section begins with a heading line, which ends with a colon. All\nsections other than the heading should maintain a hanging indent of two or four\nspaces (be consistent within a file). These sections can be omitted in cases\nwhere the function's name and signature are informative enough that it can be\naptly described using a one-line docstring.\n\n<a id=\"doc-function-args\"></a>\n[*Args:*](#doc-function-args)\n:   List each parameter by name. A description should follow the name, and be\n    separated by a colon followed by either a space or newline. If the\n    description is too long to fit on a single 80-character line, use a hanging\n    indent of 2 or 4 spaces more than the parameter name (be consistent with the\n    rest of the docstrings in the file). The description should include required\n    type(s) if the code does not contain a corresponding type annotation. If a\n    function accepts `*foo` (variable length argument lists) and/or `**bar`\n    (arbitrary keyword arguments), they should be listed as `*foo` and `**bar`.\n\n<a id=\"doc-function-returns\"></a>\n[*Returns:* (or *Yields:* for generators)](#doc-function-returns)\n:   Describe the semantics of the return value, including any type information\n    that the type annotation does not provide. If the function only returns\n    None, this section is not required. It may also be omitted if the docstring\n    starts with \"Return\", \"Returns\", \"Yield\", or \"Yields\" (e.g. `\"\"\"Returns row\n    from Bigtable as a tuple of strings.\"\"\"`) *and* the opening sentence is\n    sufficient to describe the return value. Do not imitate older 'NumPy style'\n    ([example](https://numpy.org/doc/1.24/reference/generated/numpy.linalg.qr.html)),\n    which frequently documented a tuple return value as if it were multiple\n    return values with individual names (never mentioning the tuple). Instead,\n    describe such a return value as: \"Returns: A tuple (mat_a, mat_b), where\n    mat_a is ..., and ...\". The auxiliary names in the docstring need not\n    necessarily correspond to any internal names used in the function body (as\n    those are not part of the API). If the function uses `yield` (is a\n    generator), the `Yields:` section should document the object returned by\n    `next()`, instead of the generator object itself that the call evaluates to.\n\n<a id=\"doc-function-raises\"></a>\n[*Raises:*](#doc-function-raises)\n:   List all exceptions that are relevant to the interface followed by a\n    description. Use a similar exception name + colon + space or newline and\n    hanging indent style as described in *Args:*. You should not document\n    exceptions that get raised if the API specified in the docstring is violated\n    (because this would paradoxically make behavior under violation of the API\n    part of the API).\n\n```python\ndef fetch_smalltable_rows(\n    table_handle: smalltable.Table,\n    keys: Sequence[bytes | str],\n    require_all_keys: bool = False,\n) -> Mapping[bytes, tuple[str, ...]]:\n    \"\"\"Fetches rows from a Smalltable.\n\n    Retrieves rows pertaining to the given keys from the Table instance\n    represented by table_handle.  String keys will be UTF-8 encoded.\n\n    Args:\n        table_handle: An open smalltable.Table instance.\n        keys: A sequence of strings representing the key of each table\n          row to fetch.  String keys will be UTF-8 encoded.\n        require_all_keys: If True only rows with values set for all keys will be\n          returned.\n\n    Returns:\n        A dict mapping keys to the corresponding table row data\n        fetched. Each row is represented as a tuple of strings. For\n        example:\n\n        {b'Serak': ('Rigel VII', 'Preparer'),\n         b'Zim': ('Irk', 'Invader'),\n         b'Lrrr': ('Omicron Persei 8', 'Emperor')}\n\n        Returned keys are always bytes.  If a key from the keys argument is\n        missing from the dictionary, then that row was not found in the\n        table (and require_all_keys must have been False).\n\n    Raises:\n        IOError: An error occurred accessing the smalltable.\n    \"\"\"\n```\n\nSimilarly, this variation on `Args:` with a line break is also allowed:\n\n```python\ndef fetch_smalltable_rows(\n    table_handle: smalltable.Table,\n    keys: Sequence[bytes | str],\n    require_all_keys: bool = False,\n) -> Mapping[bytes, tuple[str, ...]]:\n    \"\"\"Fetches rows from a Smalltable.\n\n    Retrieves rows pertaining to the given keys from the Table instance\n    represented by table_handle.  String keys will be UTF-8 encoded.\n\n    Args:\n      table_handle:\n        An open smalltable.Table instance.\n      keys:\n        A sequence of strings representing the key of each table row to\n        fetch.  String keys will be UTF-8 encoded.\n      require_all_keys:\n        If True only rows with values set for all keys will be returned.\n\n    Returns:\n      A dict mapping keys to the corresponding table row data\n      fetched. Each row is represented as a tuple of strings. For\n      example:\n\n      {b'Serak': ('Rigel VII', 'Preparer'),\n       b'Zim': ('Irk', 'Invader'),\n       b'Lrrr': ('Omicron Persei 8', 'Emperor')}\n\n      Returned keys are always bytes.  If a key from the keys argument is\n      missing from the dictionary, then that row was not found in the\n      table (and require_all_keys must have been False).\n\n    Raises:\n      IOError: An error occurred accessing the smalltable.\n    \"\"\"\n```\n\n<a id=\"s3.8.3.1-overridden-methods\"></a>\n\n<a id=\"overridden-method-docs\"></a>\n##### 3.8.3.1 Overridden Methods \n\nA method that overrides a method from a base class does not need a docstring if\nit is explicitly decorated with\n[`@override`](https://typing-extensions.readthedocs.io/en/latest/#override)\n(from `typing_extensions` or `typing` modules), unless the overriding method's\nbehavior materially refines the base method's contract, or details need to be\nprovided (e.g., documenting additional side effects), in which case a docstring\nwith at least those differences is required on the overriding method.\n\n```python\nfrom typing_extensions import override\n\nclass Parent:\n  def do_something(self):\n    \"\"\"Parent method, includes docstring.\"\"\"\n\n# Child class, method annotated with override.\nclass Child(Parent):\n  @override\n  def do_something(self):\n    pass\n```\n\n```python\n# Child class, but without @override decorator, a docstring is required.\nclass Child(Parent):\n  def do_something(self):\n    pass\n\n# Docstring is trivial, @override is sufficient to indicate that docs can be\n# found in the base class.\nclass Child(Parent):\n  @override\n  def do_something(self):\n    \"\"\"See base class.\"\"\"\n```\n\n<a id=\"s3.8.4-comments-in-classes\"></a>\n<a id=\"384-classes\"></a>\n<a id=\"comments-in-classes\"></a>\n\n<a id=\"class-docs\"></a>\n#### 3.8.4 Classes \n\nClasses should have a docstring below the class definition describing the class.\nPublic attributes, excluding [properties](#properties), should be documented\nhere in an `Attributes` section and follow the same formatting as a\n[function's `Args`](#doc-function-args) section.\n\n```python\nclass SampleClass:\n    \"\"\"Summary of class here.\n\n    Longer class information...\n    Longer class information...\n\n    Attributes:\n        likes_spam: A boolean indicating if we like SPAM or not.\n        eggs: An integer count of the eggs we have laid.\n    \"\"\"\n\n    def __init__(self, likes_spam: bool = False):\n        \"\"\"Initializes the instance based on spam preference.\n\n        Args:\n          likes_spam: Defines if instance exhibits this preference.\n        \"\"\"\n        self.likes_spam = likes_spam\n        self.eggs = 0\n\n    @property\n    def butter_sticks(self) -> int:\n        \"\"\"The number of butter sticks we have.\"\"\"\n```\n\nAll class docstrings should start with a one-line summary that describes what\nthe class instance represents. This implies that subclasses of `Exception`\nshould also describe what the exception represents, and not the context in which\nit might occur. The class docstring should not repeat unnecessary information,\nsuch as that the class is a class.\n\n```python\n# Yes:\nclass CheeseShopAddress:\n  \"\"\"The address of a cheese shop.\n\n  ...\n  \"\"\"\n\nclass OutOfCheeseError(Exception):\n  \"\"\"No more cheese is available.\"\"\"\n```\n\n```python\n# No:\nclass CheeseShopAddress:\n  \"\"\"Class that describes the address of a cheese shop.\n\n  ...\n  \"\"\"\n\nclass OutOfCheeseError(Exception):\n  \"\"\"Raised when no more cheese is available.\"\"\"\n```\n\n<a id=\"s3.8.5-block-and-inline-comments\"></a>\n<a id=\"comments-in-block-and-inline\"></a>\n<a id=\"s3.8.5-comments-in-block-and-inline\"></a>\n<a id=\"385-block-and-inline-comments\"></a>\n\n<a id=\"comments\"></a>\n#### 3.8.5 Block and Inline Comments \n\nThe final place to have comments is in tricky parts of the code. If you're going\nto have to explain it at the next [code review](http://en.wikipedia.org/wiki/Code_review),\nyou should comment it now. Complicated operations get a few lines of comments\nbefore the operations commence. Non-obvious ones get comments at the end of the\nline.\n\n```python\n# We use a weighted dictionary search to find out where i is in\n# the array.  We extrapolate position based on the largest num\n# in the array and the array size and then do binary search to\n# get the exact number.\n\nif i & (i-1) == 0:  # True if i is 0 or a power of 2.\n```\n\nTo improve legibility, these comments should start at least 2 spaces away from\nthe code with the comment character `#`, followed by at least one space before\nthe text of the comment itself.\n\nOn the other hand, never describe the code. Assume the person reading the code\nknows Python (though not what you're trying to do) better than you do.\n\n```python\n# BAD COMMENT: Now go through the b array and make sure whenever i occurs\n# the next element is i+1\n```\n\n<!-- The next section is copied from the C++ style guide. -->\n\n<a id=\"s3.8.6-punctuation-spelling-and-grammar\"></a>\n<a id=\"386-punctuation-spelling-and-grammar\"></a>\n<a id=\"spelling\"></a>\n<a id=\"punctuation\"></a>\n<a id=\"grammar\"></a>\n\n<a id=\"punctuation-spelling-grammar\"></a>\n#### 3.8.6 Punctuation, Spelling, and Grammar \n\nPay attention to punctuation, spelling, and grammar; it is easier to read\nwell-written comments than badly written ones.\n\nComments should be as readable as narrative text, with proper capitalization and\npunctuation. In many cases, complete sentences are more readable than sentence\nfragments. Shorter comments, such as comments at the end of a line of code, can\nsometimes be less formal, but you should be consistent with your style.\n\nAlthough it can be frustrating to have a code reviewer point out that you are\nusing a comma when you should be using a semicolon, it is very important that\nsource code maintain a high level of clarity and readability. Proper\npunctuation, spelling, and grammar help with that goal.\n\n<a id=\"s3.10-strings\"></a>\n<a id=\"310-strings\"></a>\n\n<a id=\"strings\"></a>\n### 3.10 Strings \n\nUse an\n[f-string](https://docs.python.org/3/reference/lexical_analysis.html#f-strings),\nthe `%` operator, or the `format` method for formatting strings, even when the\nparameters are all strings. Use your best judgment to decide between string\nformatting options. A single join with `+` is okay but do not format with `+`.\n\n```python\nYes: x = f'name: {name}; score: {n}'\n     x = '%s, %s!' % (imperative, expletive)\n     x = '{}, {}'.format(first, second)\n     x = 'name: %s; score: %d' % (name, n)\n     x = 'name: %(name)s; score: %(score)d' % {'name':name, 'score':n}\n     x = 'name: {}; score: {}'.format(name, n)\n     x = a + b\n```\n\n```python\nNo: x = first + ', ' + second\n    x = 'name: ' + name + '; score: ' + str(n)\n```\n\nAvoid using the `+` and `+=` operators to accumulate a string within a loop. In\nsome conditions, accumulating a string with addition can lead to quadratic\nrather than linear running time. Although common accumulations of this sort may\nbe optimized on CPython, that is an implementation detail. The conditions under\nwhich an optimization applies are not easy to predict and may change. Instead,\nadd each substring to a list and `''.join` the list after the loop terminates,\nor write each substring to an `io.StringIO` buffer. These techniques\nconsistently have amortized-linear run-time complexity.\n\n```python\nYes: items = ['<table>']\n     for last_name, first_name in employee_list:\n         items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))\n     items.append('</table>')\n     employee_table = ''.join(items)\n```\n\n```python\nNo: employee_table = '<table>'\n    for last_name, first_name in employee_list:\n        employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)\n    employee_table += '</table>'\n```\n\nBe consistent with your choice of string quote character within a file. Pick `'`\nor `\"` and stick with it. It is okay to use the other quote character on a\nstring to avoid the need to backslash-escape quote characters within the string.\n\n```python\nYes:\n  Python('Why are you hiding your eyes?')\n  Gollum(\"I'm scared of lint errors.\")\n  Narrator('\"Good!\" thought a happy Python reviewer.')\n```\n\n```python\nNo:\n  Python(\"Why are you hiding your eyes?\")\n  Gollum('The lint. It burns. It burns us.')\n  Gollum(\"Always the great lint. Watching. Watching.\")\n```\n\nPrefer `\"\"\"` for multi-line strings rather than `'''`. Projects may choose to\nuse `'''` for all non-docstring multi-line strings if and only if they also use\n`'` for regular strings. Docstrings must use `\"\"\"` regardless.\n\nMulti-line strings do not flow with the indentation of the rest of the program.\nIf you need to avoid embedding extra space in the string, use either\nconcatenated single-line strings or a multi-line string with\n[`textwrap.dedent()`](https://docs.python.org/3/library/textwrap.html#textwrap.dedent)\nto remove the initial space on each line:\n\n```python\n  No:\n  long_string = \"\"\"This is pretty ugly.\nDon't do this.\n\"\"\"\n```\n\n```python\n  Yes:\n  long_string = \"\"\"This is fine if your use case can accept\n      extraneous leading spaces.\"\"\"\n```\n\n```python\n  Yes:\n  long_string = (\"And this is fine if you cannot accept\\n\" +\n                 \"extraneous leading spaces.\")\n```\n\n```python\n  Yes:\n  long_string = (\"And this too is fine if you cannot accept\\n\"\n                 \"extraneous leading spaces.\")\n```\n\n```python\n  Yes:\n  import textwrap\n\n  long_string = textwrap.dedent(\"\"\"\\\n      This is also fine, because textwrap.dedent()\n      will collapse common leading spaces in each line.\"\"\")\n```\n\nNote that using a backslash here does not violate the prohibition against\n[explicit line continuation](#line-length); in this case, the backslash is\n[escaping a newline](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals)\nin a string literal.\n\n<a id=\"s3.10.1-logging\"></a>\n<a id=\"3101-logging\"></a>\n<a id=\"logging\"></a>\n\n<a id=\"logging\"></a>\n#### 3.10.1 Logging \n\nFor logging functions that expect a pattern-string (with %-placeholders) as\ntheir first argument: Always call them with a string literal (not an f-string!)\nas their first argument with pattern-parameters as subsequent arguments. Some\nlogging implementations collect the unexpanded pattern-string as a queryable\nfield. It also prevents spending time rendering a message that no logger is\nconfigured to output.\n\n```python\n  Yes:\n  import tensorflow as tf\n  logger = tf.get_logger()\n  logger.info('TensorFlow Version is: %s', tf.__version__)\n```\n\n```python\n  Yes:\n  import os\n  from absl import logging\n\n  logging.info('Current $PAGER is: %s', os.getenv('PAGER', default=''))\n\n  homedir = os.getenv('HOME')\n  if homedir is None or not os.access(homedir, os.W_OK):\n    logging.error('Cannot write to home directory, $HOME=%r', homedir)\n```\n\n```python\n  No:\n  import os\n  from absl import logging\n\n  logging.info('Current $PAGER is:')\n  logging.info(os.getenv('PAGER', default=''))\n\n  homedir = os.getenv('HOME')\n  if homedir is None or not os.access(homedir, os.W_OK):\n    logging.error(f'Cannot write to home directory, $HOME={homedir!r}')\n```\n\n<a id=\"s3.10.2-error-messages\"></a>\n<a id=\"3102-error-messages\"></a>\n<a id=\"error-messages\"></a>\n\n<a id=\"error-messages\"></a>\n#### 3.10.2 Error Messages \n\nError messages (such as: message strings on exceptions like `ValueError`, or\nmessages shown to the user) should follow three guidelines:\n\n1.  The message needs to precisely match the actual error condition.\n\n2.  Interpolated pieces need to always be clearly identifiable as such.\n\n3.  They should allow simple automated processing (e.g. grepping).\n\n```python\n  Yes:\n  if not 0 <= p <= 1:\n    raise ValueError(f'Not a probability: {p=}')\n\n  try:\n    os.rmdir(workdir)\n  except OSError as error:\n    logging.warning('Could not remove directory (reason: %r): %r',\n                    error, workdir)\n```\n\n```python\n  No:\n  if p < 0 or p > 1:  # PROBLEM: also false for float('nan')!\n    raise ValueError(f'Not a probability: {p=}')\n\n  try:\n    os.rmdir(workdir)\n  except OSError:\n    # PROBLEM: Message makes an assumption that might not be true:\n    # Deletion might have failed for some other reason, misleading\n    # whoever has to debug this.\n    logging.warning('Directory already was deleted: %s', workdir)\n\n  try:\n    os.rmdir(workdir)\n  except OSError:\n    # PROBLEM: The message is harder to grep for than necessary, and\n    # not universally non-confusing for all possible values of `workdir`.\n    # Imagine someone calling a library function with such code\n    # using a name such as workdir = 'deleted'. The warning would read:\n    # \"The deleted directory could not be deleted.\"\n    logging.warning('The %s directory could not be deleted.', workdir)\n```\n\n<a id=\"s3.11-files-sockets-closeables\"></a>\n<a id=\"s3.11-files-and-sockets\"></a>\n<a id=\"311-files-and-sockets\"></a>\n<a id=\"files-and-sockets\"></a>\n\n<a id=\"files\"></a>\n### 3.11 Files, Sockets, and similar Stateful Resources \n\nExplicitly close files and sockets when done with them. This rule naturally\nextends to closeable resources that internally use sockets, such as database\nconnections, and also other resources that need to be closed down in a similar\nfashion. To name only a few examples, this also includes\n[mmap](https://docs.python.org/3/library/mmap.html) mappings,\n[h5py File objects](https://docs.h5py.org/en/stable/high/file.html), and\n[matplotlib.pyplot figure windows](https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html).\n\nLeaving files, sockets or other such stateful objects open unnecessarily has\nmany downsides:\n\n-   They may consume limited system resources, such as file descriptors. Code\n    that deals with many such objects may exhaust those resources unnecessarily\n    if they're not returned to the system promptly after use.\n-   Holding files open may prevent other actions such as moving or deleting\n    them, or unmounting a filesystem.\n-   Files and sockets that are shared throughout a program may inadvertently be\n    read from or written to after logically being closed. If they are actually\n    closed, attempts to read or write from them will raise exceptions, making\n    the problem known sooner.\n\nFurthermore, while files and sockets (and some similarly behaving resources) are\nautomatically closed when the object is destructed, coupling the lifetime of the\nobject to the state of the resource is poor practice:\n\n-   There are no guarantees as to when the runtime will actually invoke the\n    `__del__` method. Different Python implementations use different memory\n    management techniques, such as delayed garbage collection, which may\n    increase the object's lifetime arbitrarily and indefinitely.\n-   Unexpected references to the file, e.g. in globals or exception tracebacks,\n    may keep it around longer than intended.\n\nRelying on finalizers to do automatic cleanup that has observable side effects\nhas been rediscovered over and over again to lead to major problems, across many\ndecades and multiple languages (see e.g.\n[this article](https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers)\nfor Java).\n\nThe preferred way to manage files and similar resources is using the\n[`with` statement](http://docs.python.org/reference/compound_stmts.html#the-with-statement):\n\n```python\nwith open(\"hello.txt\") as hello_file:\n    for line in hello_file:\n        print(line)\n```\n\nFor file-like objects that do not support the `with` statement, use\n`contextlib.closing()`:\n\n```python\nimport contextlib\n\nwith contextlib.closing(urllib.urlopen(\"http://www.python.org/\")) as front_page:\n    for line in front_page:\n        print(line)\n```\n\nIn rare cases where context-based resource management is infeasible, code\ndocumentation must explain clearly how resource lifetime is managed.\n\n<a id=\"s3.12-todo-comments\"></a>\n<a id=\"312-todo-comments\"></a>\n\n<a id=\"todo\"></a>\n### 3.12 TODO Comments \n\nUse `TODO` comments for code that is temporary, a short-term solution, or\ngood-enough but not perfect.\n\nA `TODO` comment begins with the word `TODO` in all caps, a following colon, and\na link to a resource that contains the context, ideally a bug reference. A bug\nreference is preferable because bugs are tracked and have follow-up comments.\nFollow this piece of context with an explanatory string introduced with a hyphen\n`-`. \nThe purpose is to have a consistent `TODO` format that can be searched to find\nout how to get more details. \n\n```python\n# TODO: crbug.com/192795 - Investigate cpufreq optimizations.\n```\n\nOld style, formerly recommended, but discouraged for use in new code:\n\n\n```python\n# TODO(crbug.com/192795): Investigate cpufreq optimizations.\n# TODO(yourusername): Use a \"\\*\" here for concatenation operator.\n```\n\nAvoid adding TODOs that refer to an individual or team as the context:\n\n```python\n# TODO: @yourusername - File an issue and use a '*' for repetition.\n```\n\nIf your `TODO` is of the form \"At a future date do something\" make sure that you\neither include a very specific date (\"Fix by November 2009\") or a very specific\nevent (\"Remove this code when all clients can handle XML responses.\") that\nfuture code maintainers will comprehend. Issues are ideal for tracking this.\n\n<a id=\"s3.13-imports-formatting\"></a>\n<a id=\"313-imports-formatting\"></a>\n\n<a id=\"imports-formatting\"></a>\n### 3.13 Imports formatting \n\nImports should be on separate lines; there are\n[exceptions for `typing` and `collections.abc` imports](#typing-imports).\n\nE.g.:\n\n```python\nYes: from collections.abc import Mapping, Sequence\n     import os\n     import sys\n     from typing import Any, NewType\n```\n\n```python\nNo:  import os, sys\n```\n\n\nImports are always put at the top of the file, just after any module comments\nand docstrings and before module globals and constants. Imports should be\ngrouped from most generic to least generic:\n\n1.  Python future import statements. For example:\n\n    ```python\n    from __future__ import annotations\n    ```\n\n    See [above](#from-future-imports) for more information about those.\n\n2.  Python standard library imports. For example:\n\n    ```python\n    import sys\n    ```\n\n3.  [third-party](https://pypi.org/) module\n    or package imports. For example:\n\n    \n    ```python\n    import tensorflow as tf\n    ```\n\n4.  Code repository\n    sub-package imports. For example:\n\n    \n    ```python\n    from otherproject.ai import mind\n    ```\n\n5.  **Deprecated:** application-specific imports that are part of the same\n    top-level\n    sub-package as this file. For example:\n\n    \n    ```python\n    from myproject.backend.hgwells import time_machine\n    ```\n\n    You may find older Google Python Style code doing this, but it is no longer\n    required. **New code is encouraged not to bother with this.** Simply treat\n    application-specific sub-package imports the same as other sub-package\n    imports.\n\n    \nWithin each grouping, imports should be sorted lexicographically, ignoring case,\naccording to each module's full package path (the `path` in `from path import\n...`). Code may optionally place a blank line between import sections.\n\n```python\nimport collections\nimport queue\nimport sys\n\nfrom absl import app\nfrom absl import flags\nimport bs4\nimport cryptography\nimport tensorflow as tf\n\nfrom book.genres import scifi\nfrom myproject.backend import huxley\nfrom myproject.backend.hgwells import time_machine\nfrom myproject.backend.state_machine import main_loop\nfrom otherproject.ai import body\nfrom otherproject.ai import mind\nfrom otherproject.ai import soul\n\n# Older style code may have these imports down here instead:\n#from myproject.backend.hgwells import time_machine\n#from myproject.backend.state_machine import main_loop\n```\n\n\n<a id=\"s3.14-statements\"></a>\n<a id=\"314-statements\"></a>\n\n<a id=\"statements\"></a>\n### 3.14 Statements \n\nGenerally only one statement per line.\n\nHowever, you may put the result of a test on the same line as the test only if\nthe entire statement fits on one line. In particular, you can never do so with\n`try`/`except` since the `try` and `except` can't both fit on the same line, and\nyou can only do so with an `if` if there is no `else`.\n\n```python\nYes:\n\n  if foo: bar(foo)\n```\n\n```python\nNo:\n\n  if foo: bar(foo)\n  else:   baz(foo)\n\n  try:               bar(foo)\n  except ValueError: baz(foo)\n\n  try:\n      bar(foo)\n  except ValueError: baz(foo)\n```\n\n<a id=\"s3.15-accessors\"></a>\n<a id=\"s3.15-access-control\"></a>\n<a id=\"315-access-control\"></a>\n<a id=\"access-control\"></a>\n<a id=\"accessors\"></a>\n\n<a id=\"getters-and-setters\"></a>\n### 3.15 Getters and Setters \n\nGetter and setter functions (also called accessors and mutators) should be used\nwhen they provide a meaningful role or behavior for getting or setting a\nvariable's value.\n\nIn particular, they should be used when getting or setting the variable is\ncomplex or the cost is significant, either currently or in a reasonable future.\n\nIf, for example, a pair of getters/setters simply read and write an internal\nattribute, the internal attribute should be made public instead. By comparison,\nif setting a variable means some state is invalidated or rebuilt, it should be a\nsetter function. The function invocation hints that a potentially non-trivial\noperation is occurring. Alternatively, [properties](#properties) may be an\noption when simple logic is needed, or refactoring to no longer need getters and\nsetters.\n\nGetters and setters should follow the [Naming](#s3.16-naming) guidelines, such\nas `get_foo()` and `set_foo()`.\n\nIf the past behavior allowed access through a property, do not bind the new\ngetter/setter functions to the property. Any code still attempting to access the\nvariable by the old method should break visibly so they are made aware of the\nchange in complexity.\n\n<a id=\"s3.16-naming\"></a>\n<a id=\"316-naming\"></a>\n\n<a id=\"naming\"></a>\n### 3.16 Naming \n\n`module_name`, `package_name`, `ClassName`, `method_name`, `ExceptionName`,\n`function_name`, `GLOBAL_CONSTANT_NAME`, `global_var_name`, `instance_var_name`,\n`function_parameter_name`, `local_var_name`, `query_proper_noun_for_thing`,\n`send_acronym_via_https`.\n\n\nNames should be descriptive. This includes functions, classes, variables,\nattributes, files and any other type of named entities.\n\nAvoid abbreviation. In particular, do not use abbreviations that are ambiguous\nor unfamiliar to readers outside your project, and do not abbreviate by deleting\nletters within a word.\n\nAlways use a `.py` filename extension. Never use dashes.\n\n<a id=\"s3.16.1-names-to-avoid\"></a>\n<a id=\"3161-names-to-avoid\"></a>\n\n<a id=\"names-to-avoid\"></a>\n#### 3.16.1 Names to Avoid \n\n-   single character names, except for specifically allowed cases:\n\n    -   counters or iterators (e.g. `i`, `j`, `k`, `v`, et al.)\n    -   `e` as an exception identifier in `try/except` statements.\n    -   `f` as a file handle in `with` statements\n    -   private [type variables](#typing-type-var) with no constraints (e.g.\n        `_T = TypeVar(\"_T\")`, `_P = ParamSpec(\"_P\")`)\n    -   names that match established notation in a reference paper or algorithm\n        (see [Mathematical Notation](#math-notation))\n\n    Please be mindful not to abuse single-character naming. Generally speaking,\n    descriptiveness should be proportional to the name's scope of visibility.\n    For example, `i` might be a fine name for 5-line code block but within\n    multiple nested scopes, it is likely too vague.\n\n-   dashes (`-`) in any package/module name\n\n-   `__double_leading_and_trailing_underscore__` names (reserved by Python)\n\n-   offensive terms\n\n-   names that needlessly include the type of the variable (for example:\n    `id_to_name_dict`)\n\n<a id=\"s3.16.2-naming-conventions\"></a>\n<a id=\"3162-naming-convention\"></a>\n\n<a id=\"naming-conventions\"></a>\n#### 3.16.2 Naming Conventions \n\n-   \"Internal\" means internal to a module, or protected or private within a\n    class.\n\n-   Prepending a single underscore (`_`) has some support for protecting module\n    variables and functions (linters will flag protected member access). Note\n    that it is okay for unit tests to access protected constants from the\n    modules under test.\n\n-   Prepending a double underscore (`__` aka \"dunder\") to an instance variable\n    or method effectively makes the variable or method private to its class\n    (using name mangling); we discourage its use as it impacts readability and\n    testability, and isn't *really* private. Prefer a single underscore.\n\n-   Place related classes and top-level functions together in a\n    module.\n    Unlike Java, there is no need to limit yourself to one class per module.\n\n-   Use CapWords for class names, but lower\\_with\\_under.py for module names.\n    Although there are some old modules named CapWords.py, this is now\n    discouraged because it's confusing when the module happens to be named after\n    a class. (\"wait -- did I write `import StringIO` or `from StringIO import\n    StringIO`?\")\n\n-   New *unit test* files follow PEP 8 compliant lower\\_with\\_under method\n    names, for example, `test_<method_under_test>_<state>`. For consistency(\\*)\n    with legacy modules that follow CapWords function names, underscores may\n    appear in method names starting with `test` to separate logical components\n    of the name. One possible pattern is `test<MethodUnderTest>_<state>`.\n\n<a id=\"s3.16.3-file-naming\"></a>\n<a id=\"3163-file-naming\"></a>\n\n<a id=\"file-naming\"></a>\n#### 3.16.3 File Naming \n\nPython filenames must have a `.py` extension and must not contain dashes (`-`).\nThis allows them to be imported and unittested. If you want an executable to be\naccessible without the extension, use a symbolic link or a simple bash wrapper\ncontaining `exec \"$0.py\" \"$@\"`.\n\n<a id=\"s3.16.4-guidelines-derived-from-guidos-recommendations\"></a>\n<a id=\"3164-guidelines-derived-from-guidos-recommendations\"></a>\n\n<a id=\"guidelines-derived-from-guidos-recommendations\"></a>\n#### 3.16.4 Guidelines derived from [Guido](https://en.wikipedia.org/wiki/Guido_van_Rossum)'s Recommendations \n\n<table rules=\"all\" border=\"1\" summary=\"Guidelines from Guido's Recommendations\"\n       cellspacing=\"2\" cellpadding=\"2\">\n\n  <tr>\n    <th>Type</th>\n    <th>Public</th>\n    <th>Internal</th>\n  </tr>\n\n  <tr>\n    <td>Packages</td>\n    <td><code>lower_with_under</code></td>\n    <td></td>\n  </tr>\n\n  <tr>\n    <td>Modules</td>\n    <td><code>lower_with_under</code></td>\n    <td><code>_lower_with_under</code></td>\n  </tr>\n\n  <tr>\n    <td>Classes</td>\n    <td><code>CapWords</code></td>\n    <td><code>_CapWords</code></td>\n  </tr>\n\n  <tr>\n    <td>Exceptions</td>\n    <td><code>CapWords</code></td>\n    <td></td>\n  </tr>\n\n  <tr>\n    <td>Functions</td>\n    <td><code>lower_with_under()</code></td>\n    <td><code>_lower_with_under()</code></td>\n  </tr>\n\n  <tr>\n    <td>Global/Class Constants</td>\n    <td><code>CAPS_WITH_UNDER</code></td>\n    <td><code>_CAPS_WITH_UNDER</code></td>\n  </tr>\n\n  <tr>\n    <td>Global/Class Variables</td>\n    <td><code>lower_with_under</code></td>\n    <td><code>_lower_with_under</code></td>\n  </tr>\n\n  <tr>\n    <td>Instance Variables</td>\n    <td><code>lower_with_under</code></td>\n    <td><code>_lower_with_under</code> (protected)</td>\n  </tr>\n\n  <tr>\n    <td>Method Names</td>\n    <td><code>lower_with_under()</code></td>\n    <td><code>_lower_with_under()</code> (protected)</td>\n  </tr>\n\n  <tr>\n    <td>Function/Method Parameters</td>\n    <td><code>lower_with_under</code></td>\n    <td></td>\n  </tr>\n\n  <tr>\n    <td>Local Variables</td>\n    <td><code>lower_with_under</code></td>\n    <td></td>\n  </tr>\n\n</table>\n\n\n<a id=\"s3.17-main\"></a>\n<a id=\"317-main\"></a>\n\n<a id=\"math-notation\"></a>\n#### 3.16.5 Mathematical Notation \n\nFor mathematically-heavy code, short variable names that would otherwise violate\nthe style guide are preferred when they match established notation in a\nreference paper or algorithm.\n\nWhen using names based on established notation:\n\n1.  Cite the source of all naming conventions, preferably with a hyperlink to\n    academic resource itself, in a comment or docstring. If the source is not\n    accessible, clearly document the naming conventions.\n2.  Prefer PEP8-compliant `descriptive_names` for public APIs, which are much\n    more likely to be encountered out of context.\n3.  Use a narrowly-scoped `pylint: disable=invalid-name` directive to silence\n    warnings. For just a few variables, use the directive as an endline comment\n    for each one; for more, apply the directive at the beginning of a block.\n\n<a id=\"main\"></a>\n### 3.17 Main \n\nIn Python, `pydoc` as well as unit tests require modules to be importable. If a\nfile is meant to be used as an executable, its main functionality should be in a\n`main()` function, and your code should always check `if __name__ == '__main__'`\nbefore executing your main program, so that it is not executed when the module\nis imported.\n\nWhen using [absl](https://github.com/abseil/abseil-py), use `app.run`:\n\n```python\nfrom absl import app\n...\n\ndef main(argv: Sequence[str]):\n    # process non-flag arguments\n    ...\n\nif __name__ == '__main__':\n    app.run(main)\n```\n\nOtherwise, use:\n\n```python\ndef main():\n    ...\n\nif __name__ == '__main__':\n    main()\n```\n\nAll code at the top level will be executed when the module is imported. Be\ncareful not to call functions, create objects, or perform other operations that\nshould not be executed when the file is being `pydoc`ed.\n\n<a id=\"s3.18-function-length\"></a>\n<a id=\"318-function-length\"></a>\n\n<a id=\"function-length\"></a>\n### 3.18 Function length \n\nPrefer small and focused functions.\n\nWe recognize that long functions are sometimes appropriate, so no hard limit is\nplaced on function length. If a function exceeds about 40 lines, think about\nwhether it can be broken up without harming the structure of the program.\n\nEven if your long function works perfectly now, someone modifying it in a few\nmonths may add new behavior. This could result in bugs that are hard to find.\nKeeping your functions short and simple makes it easier for other people to read\nand modify your code.\n\nYou could find long and complicated functions when working with\nsome\ncode. Do not be intimidated by modifying existing code: if working with such a\nfunction proves to be difficult, you find that errors are hard to debug, or you\nwant to use a piece of it in several different contexts, consider breaking up\nthe function into smaller and more manageable pieces.\n\n<a id=\"s3.19-type-annotations\"></a>\n<a id=\"319-type-annotations\"></a>\n\n<a id=\"type-annotations\"></a>\n### 3.19 Type Annotations \n\n<a id=\"s3.19.1-general-rules\"></a>\n<a id=\"s3.19.1-general\"></a>\n<a id=\"3191-general-rules\"></a>\n\n<a id=\"typing-general\"></a>\n#### 3.19.1 General Rules \n\n*   Familiarize yourself with\n    [type hints](https://docs.python.org/3/library/typing.html).\n\n*   Annotating `self` or `cls` is generally not necessary.\n    [`Self`](https://docs.python.org/3/library/typing.html#typing.Self) can be\n    used if it is necessary for proper type information, e.g.\n\n    ```python\n    from typing import Self\n\n    class BaseClass:\n      @classmethod\n      def create(cls) -> Self:\n        ...\n\n      def difference(self, other: Self) -> float:\n        ...\n    ```\n\n*   Similarly, don't feel compelled to annotate the return value of `__init__`\n    (where `None` is the only valid option).\n\n*   If any other variable or a returned type should not be expressed, use `Any`.\n\n*   You are not required to annotate all the functions in a module.\n\n    -   At least annotate your public APIs.\n    -   Use judgment to get to a good balance between safety and clarity on the\n        one hand, and flexibility on the other.\n    -   Annotate code that is prone to type-related errors (previous bugs or\n        complexity).\n    -   Annotate code that is hard to understand.\n    -   Annotate code as it becomes stable from a types perspective. In many\n        cases, you can annotate all the functions in mature code without losing\n        too much flexibility.\n\n<a id=\"s3.19.2-line-breaking\"></a>\n<a id=\"3192-line-breaking\"></a>\n\n<a id=\"typing-line-breaking\"></a>\n#### 3.19.2 Line Breaking \n\nTry to follow the existing [indentation](#indentation) rules.\n\nAfter annotating, many function signatures will become \"one parameter per line\".\nTo ensure the return type is also given its own line, a comma can be placed\nafter the last parameter.\n\n```python\ndef my_method(\n    self,\n    first_var: int,\n    second_var: Foo,\n    third_var: Bar | None,\n) -> int:\n  ...\n```\n\nAlways prefer breaking between variables, and not, for example, between variable\nnames and type annotations. However, if everything fits on the same line, go for\nit.\n\n```python\ndef my_method(self, first_var: int) -> int:\n  ...\n```\n\nIf the combination of the function name, the last parameter, and the return type\nis too long, indent by 4 in a new line. When using line breaks, prefer putting\neach parameter and the return type on their own lines and aligning the closing\nparenthesis with the `def`:\n\n```python\nYes:\ndef my_method(\n    self,\n    other_arg: MyLongType | None,\n) -> tuple[MyLongType1, MyLongType1]:\n  ...\n```\n\nOptionally, the return type may be put on the same line as the last parameter:\n\n```python\nOkay:\ndef my_method(\n    self,\n    first_var: int,\n    second_var: int) -> dict[OtherLongType, MyLongType]:\n  ...\n```\n\n`pylint`\nallows you to move the closing parenthesis to a new line and align with the\nopening one, but this is less readable.\n\n```python\nNo:\ndef my_method(self,\n              other_arg: MyLongType | None,\n             ) -> dict[OtherLongType, MyLongType]:\n  ...\n```\n\nAs in the examples above, prefer not to break types. However, sometimes they are\ntoo long to be on a single line (try to keep sub-types unbroken).\n\n```python\ndef my_method(\n    self,\n    first_var: tuple[list[MyLongType1],\n                     list[MyLongType2]],\n    second_var: list[dict[\n        MyLongType3, MyLongType4]],\n) -> None:\n  ...\n```\n\nIf a single name and type is too long, consider using an\n[alias](#typing-aliases) for the type. The last resort is to break after the\ncolon and indent by 4.\n\n```python\nYes:\ndef my_function(\n    long_variable_name:\n        long_module_name.LongTypeName,\n) -> None:\n  ...\n```\n\n```python\nNo:\ndef my_function(\n    long_variable_name: long_module_name.\n        LongTypeName,\n) -> None:\n  ...\n```\n\n<a id=\"s3.19.3-forward-declarations\"></a>\n<a id=\"3193-forward-declarations\"></a>\n\n<a id=\"forward-declarations\"></a>\n#### 3.19.3 Forward Declarations \n\nIf you need to use a class name (from the same module) that is not yet\ndefined -- for example, if you need the class name inside the declaration of\nthat class, or if you use a class that is defined later in the code -- either\nuse `from __future__ import annotations` or use a string for the class name.\n\n```python\nYes:\nfrom __future__ import annotations\n\nclass MyClass:\n  def __init__(self, stack: Sequence[MyClass], item: OtherClass) -> None:\n\nclass OtherClass:\n  ...\n```\n\n```python\nYes:\nclass MyClass:\n  def __init__(self, stack: Sequence['MyClass'], item: 'OtherClass') -> None:\n\nclass OtherClass:\n  ...\n```\n\n<a id=\"s3.19.4-default-values\"></a>\n<a id=\"3194-default-values\"></a>\n\n<a id=\"typing-default-values\"></a>\n#### 3.19.4 Default Values \n\nAs per [PEP-008](https://peps.python.org/pep-0008/#other-recommendations), use\nspaces around the `=` *only* for arguments that have both a type annotation and\na default value.\n\n```python\nYes:\ndef func(a: int = 0) -> int:\n  ...\n```\n\n```python\nNo:\ndef func(a:int=0) -> int:\n  ...\n```\n\n<a id=\"s3.19.5-nonetype\"></a>\n<a id=\"s3.19.5-none-type\"></a>\n<a id=\"3195-nonetype\"></a>\n\n<a id=\"none-type\"></a>\n#### 3.19.5 NoneType \n\nIn the Python type system, `NoneType` is a \"first class\" type, and for typing\npurposes, `None` is an alias for `NoneType`. If an argument can be `None`, it\nhas to be declared! You can use `|` union type expressions (recommended in new\nPython 3.10+ code), or the older `Optional` and `Union` syntaxes.\n\nUse explicit `X | None` instead of implicit. Earlier versions of type checkers\nallowed `a: str = None` to be interpreted as `a: str | None = None`, but that is\nno longer the preferred behavior.\n\n```python\nYes:\ndef modern_or_union(a: str | int | None, b: str | None = None) -> str:\n  ...\ndef union_optional(a: Union[str, int, None], b: Optional[str] = None) -> str:\n  ...\n```\n\n```python\nNo:\ndef nullable_union(a: Union[None, str]) -> str:\n  ...\ndef implicit_optional(a: str = None) -> str:\n  ...\n```\n\n<a id=\"s3.19.6-type-aliases\"></a>\n<a id=\"s3.19.6-aliases\"></a>\n<a id=\"3196-type-aliases\"></a>\n<a id=\"typing-aliases\"></a>\n\n<a id=\"type-aliases\"></a>\n#### 3.19.6 Type Aliases \n\nYou can declare aliases of complex types. The name of an alias should be\nCapWorded. If the alias is used only in this module, it should be \\_Private.\n\nNote that the `: TypeAlias` annotation is only supported in versions 3.10+.\n\n```python\nfrom typing import TypeAlias\n\n_LossAndGradient: TypeAlias = tuple[tf.Tensor, tf.Tensor]\nComplexTFMap: TypeAlias = Mapping[str, _LossAndGradient]\n```\n\n<a id=\"s3.19.7-ignoring-types\"></a>\n<a id=\"s3.19.7-ignore\"></a>\n<a id=\"3197-ignoring-types\"></a>\n\n<a id=\"typing-ignore\"></a>\n#### 3.19.7 Ignoring Types \n\nYou can disable type checking on a line with the special comment `# type:\nignore`.\n\n`pytype` has a disable option for specific errors (similar to lint):\n\n```python\n# pytype: disable=attribute-error\n```\n\n<a id=\"s3.19.8-typing-variables\"></a>\n<a id=\"s3.19.8-comments\"></a>\n<a id=\"3198-typing-internal-variables\"></a>\n\n<a id=\"typing-variables\"></a>\n#### 3.19.8 Typing Variables \n\n<a id=\"annotated-assignments\"></a>\n[*Annotated Assignments*](#annotated-assignments)\n:   If an internal variable has a type that is hard or impossible to infer,\n    specify its type with an annotated assignment - use a colon and type between\n    the variable name and value (the same as is done with function arguments\n    that have a default value):\n\n    ```python\n    a: Foo = SomeUndecoratedFunction()\n    ```\n\n<a id=\"type-comments\"></a>\n[*Type Comments*](#type-comments)\n:   Though you may see them remaining in the codebase (they were necessary\n    before Python 3.6), do not add any more uses of a `# type: <type name>`\n    comment on the end of the line:\n\n    ```python\n    a = SomeUndecoratedFunction()  # type: Foo\n    ```\n\n<a id=\"s3.19.9-tuples-vs-lists\"></a>\n<a id=\"s3.19.9-tuples\"></a>\n<a id=\"3199-tuples-vs-lists\"></a>\n\n<a id=\"typing-tuples\"></a>\n#### 3.19.9 Tuples vs Lists \n\nTyped lists can only contain objects of a single type. Typed tuples can either\nhave a single repeated type or a set number of elements with different types.\nThe latter is commonly used as the return type from a function.\n\n```python\na: list[int] = [1, 2, 3]\nb: tuple[int, ...] = (1, 2, 3)\nc: tuple[int, str, float] = (1, \"2\", 3.5)\n```\n\n<a id=\"s3.19.10-typevars\"></a>\n<a id=\"s3.19.10-type-var\"></a>\n<a id=\"31910-typevar\"></a>\n<a id=\"typing-type-var\"></a>\n\n<a id=\"typevars\"></a>\n#### 3.19.10 Type variables \n\nThe Python type system has\n[generics](https://docs.python.org/3/library/typing.html#generics). A type\nvariable, such as `TypeVar` and `ParamSpec`, is a common way to use them.\n\nExample:\n\n```python\nfrom collections.abc import Callable\nfrom typing import ParamSpec, TypeVar\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n...\ndef next(l: list[_T]) -> _T:\n  return l.pop()\n\ndef print_when_called(f: Callable[_P, _T]) -> Callable[_P, _T]:\n  def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T:\n    print(\"Function was called\")\n    return f(*args, **kwargs)\n  return inner\n```\n\nA `TypeVar` can be constrained:\n\n```python\nAddableType = TypeVar(\"AddableType\", int, float, str)\ndef add(a: AddableType, b: AddableType) -> AddableType:\n  return a + b\n```\n\nA common predefined type variable in the `typing` module is `AnyStr`. Use it for\nmultiple annotations that can be `bytes` or `str` and must all be the same type.\n\n```python\nfrom typing import AnyStr\ndef check_length(x: AnyStr) -> AnyStr:\n  if len(x) <= 42:\n    return x\n  raise ValueError()\n```\n\nA type variable must have a descriptive name, unless it meets all of the\nfollowing criteria:\n\n*   not externally visible\n*   not constrained\n\n```python\nYes:\n  _T = TypeVar(\"_T\")\n  _P = ParamSpec(\"_P\")\n  AddableType = TypeVar(\"AddableType\", int, float, str)\n  AnyFunction = TypeVar(\"AnyFunction\", bound=Callable)\n```\n\n```python\nNo:\n  T = TypeVar(\"T\")\n  P = ParamSpec(\"P\")\n  _T = TypeVar(\"_T\", int, float, str)\n  _F = TypeVar(\"_F\", bound=Callable)\n```\n\n<a id=\"s3.19.11-string-types\"></a>\n<a id=\"s3.19.11-strings\"></a>\n<a id=\"31911-string-types\"></a>\n\n<a id=\"typing-strings\"></a>\n#### 3.19.11 String types \n\n> Do not use `typing.Text` in new code. It's only for Python 2/3 compatibility.\n\nUse `str` for string/text data. For code that deals with binary data, use\n`bytes`.\n\n```python\ndef deals_with_text_data(x: str) -> str:\n  ...\ndef deals_with_binary_data(x: bytes) -> bytes:\n  ...\n```\n\nIf all the string types of a function are always the same, for example if the\nreturn type is the same as the argument type in the code above, use\n[AnyStr](#typing-type-var).\n\n<a id=\"s3.19.12-imports-for-typing\"></a>\n<a id=\"s3.19.12-imports\"></a>\n<a id=\"31912-imports-for-typing\"></a>\n\n<a id=\"typing-imports\"></a>\n#### 3.19.12 Imports For Typing \n\nFor symbols (including types, functions, and constants) from the `typing` or\n`collections.abc` modules used to support static analysis and type checking,\nalways import the symbol itself. This keeps common annotations more concise and\nmatches typing practices used around the world. You are explicitly allowed to\nimport multiple specific symbols on one line from the `typing` and\n`collections.abc` modules. For example:\n\n```python\nfrom collections.abc import Mapping, Sequence\nfrom typing import Any, Generic, cast, TYPE_CHECKING\n```\n\nGiven that this way of importing adds items to the local namespace, names in\n`typing` or `collections.abc` should be treated similarly to keywords, and not\nbe defined in your Python code, typed or not. If there is a collision between a\ntype and an existing name in a module, import it using `import x as y`.\n\n```python\nfrom typing import Any as AnyType\n```\n\nWhen annotating function signatures, prefer abstract container types like\n`collections.abc.Sequence` over concrete types like `list`. If you need to use a\nconcrete type (for example, a `tuple` of typed elements), prefer built-in types\nlike `tuple` over the parametric type aliases from the `typing` module (e.g.,\n`typing.Tuple`).\n\n```python\nfrom typing import List, Tuple\n\ndef transform_coordinates(original: List[Tuple[float, float]]) ->\n    List[Tuple[float, float]]:\n  ...\n```\n\n```python\nfrom collections.abc import Sequence\n\ndef transform_coordinates(original: Sequence[tuple[float, float]]) ->\n    Sequence[tuple[float, float]]:\n  ...\n```\n\n<a id=\"s3.19.13-conditional-imports\"></a>\n<a id=\"31913-conditional-imports\"></a>\n\n<a id=\"typing-conditional-imports\"></a>\n#### 3.19.13 Conditional Imports \n\nUse conditional imports only in exceptional cases where the additional imports\nneeded for type checking must be avoided at runtime. This pattern is\ndiscouraged; alternatives such as refactoring the code to allow top-level\nimports should be preferred.\n\nImports that are needed only for type annotations can be placed within an `if\nTYPE_CHECKING:` block.\n\n-   Conditionally imported types need to be referenced as strings, to be forward\n    compatible with Python 3.6 where the annotation expressions are actually\n    evaluated.\n-   Only entities that are used solely for typing should be defined here; this\n    includes aliases. Otherwise it will be a runtime error, as the module will\n    not be imported at runtime.\n-   The block should be right after all the normal imports.\n-   There should be no empty lines in the typing imports list.\n-   Sort this list as if it were a regular imports list.\n```python\nimport typing\nif typing.TYPE_CHECKING:\n  import sketch\ndef f(x: \"sketch.Sketch\"): ...\n```\n\n<a id=\"s3.19.14-circular-dependencies\"></a>\n<a id=\"s3.19.14-circular-deps\"></a>\n<a id=\"31914-circular-dependencies\"></a>\n\n<a id=\"typing-circular-deps\"></a>\n#### 3.19.14 Circular Dependencies \n\nCircular dependencies that are caused by typing are code smells. Such code is a\ngood candidate for refactoring. Although technically it is possible to keep\ncircular dependencies, various build systems will not let you do so\nbecause each module has to depend on the other.\n\nReplace modules that create circular dependency imports with `Any`. Set an\n[alias](#typing-aliases) with a meaningful name, and use the real type name from\nthis module (any attribute of `Any` is `Any`). Alias definitions should be\nseparated from the last import by one line.\n\n```python\nfrom typing import Any\n\nsome_mod = Any  # some_mod.py imports this module.\n...\n\ndef my_method(self, var: \"some_mod.SomeType\") -> None:\n  ...\n```\n\n<a id=\"typing-generics\"></a>\n<a id=\"s3.19.15-generics\"></a>\n<a id=\"31915-generics\"></a>\n\n<a id=\"generics\"></a>\n#### 3.19.15 Generics \n\nWhen annotating, prefer to specify type parameters for\n[generic](https://docs.python.org/3/library/typing.html#generics) types in a\nparameter list; otherwise, the generics' parameters will be assumed to be\n[`Any`](https://docs.python.org/3/library/typing.html#the-any-type).\n\n```python\n# Yes:\ndef get_names(employee_ids: Sequence[int]) -> Mapping[int, str]:\n  ...\n```\n\n```python\n# No:\n# This is interpreted as get_names(employee_ids: Sequence[Any]) -> Mapping[Any, Any]\ndef get_names(employee_ids: Sequence) -> Mapping:\n  ...\n```\n\nIf the best type parameter for a generic is `Any`, make it explicit, but\nremember that in many cases [`TypeVar`](#typing-type-var) might be more\nappropriate:\n\n```python\n# No:\ndef get_names(employee_ids: Sequence[Any]) -> Mapping[Any, str]:\n  \"\"\"Returns a mapping from employee ID to employee name for given IDs.\"\"\"\n```\n\n```python\n# Yes:\n_T = TypeVar('_T')\ndef get_names(employee_ids: Sequence[_T]) -> Mapping[_T, str]:\n  \"\"\"Returns a mapping from employee ID to employee name for given IDs.\"\"\"\n```\n\n\n<a id=\"4-parting-words\"></a>\n\n<a id=\"consistency\"></a>\n## 4 Parting Words \n\n*BE CONSISTENT*.\n\nIf you're editing code, take a few minutes to look at the code around you and\ndetermine its style. If they use `_idx` suffixes in index variable names, you\nshould too. If their comments have little boxes of hash marks around them, make\nyour comments have little boxes of hash marks around them too.\n\nThe point of having style guidelines is to have a common vocabulary of coding so\npeople can concentrate on what you're saying rather than on how you're saying\nit. We present global style rules here so people know the vocabulary, but local\nstyle is also important. If code you add to a file looks drastically different\nfrom the existing code around it, it throws readers out of their rhythm when\nthey go to read it.\n\nHowever, there are limits to consistency. It applies more heavily locally and on\nchoices unspecified by the global style. Consistency should not generally be\nused as a justification to do things in an old style without considering the\nbenefits of the new style, or the tendency of the codebase to converge on newer\nstyles over time.\n\n"
  },
  {
    "path": "pylintrc",
    "content": "# This Pylint rcfile contains a best-effort configuration to uphold the\n# best-practices and style described in the Google Python style guide:\n#   https://google.github.io/styleguide/pyguide.html\n#\n# Its canonical open-source location is:\n#   https://google.github.io/styleguide/pylintrc\n\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n[MAIN]\n\n# Files or directories to be skipped. They should be base names, not paths.\nignore=third_party\n\n# Files or directories matching the regex patterns are skipped. The regex\n# matches against base names, not paths.\nignore-patterns=\n\n# Pickle collected data for later comparisons.\npersistent=no\n\n# List of plugins (as comma separated values of python modules names) to load,\n# usually to register additional checkers.\nload-plugins=\n\n# Use multiple processes to speed up Pylint.\njobs=4\n\n# Allow loading of arbitrary C extensions. Extensions are imported into the\n# active Python interpreter and may run arbitrary code.\nunsafe-load-any-extension=no\n\n\n[MESSAGES CONTROL]\n\n# Only show warnings with the listed confidence levels. Leave empty to show\n# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED\nconfidence=\n\n# Enable the message, report, category or checker with the given id(s). You can\n# either give multiple identifier separated by comma (,) or put this option\n# multiple time (only on the command line, not in the configuration file where\n# it should appear only once). See also the \"--disable\" option for examples.\n#enable=\n\n# Disable the message, report, category or checker with the given id(s). You\n# can either give multiple identifiers separated by comma (,) or put this\n# option multiple times (only on the command line, not in the configuration\n# file where it should appear only once).You can also use \"--disable=all\" to\n# disable everything first and then reenable specific checks. For example, if\n# you want to run only the similarities checker, you can use \"--disable=all\n# --enable=similarities\". If you want to run only the classes checker, but have\n# no Warning level messages displayed, use\"--disable=all --enable=classes\n# --disable=W\"\ndisable=R,\n        abstract-method,\n        apply-builtin,\n        arguments-differ,\n        attribute-defined-outside-init,\n        backtick,\n        bad-option-value,\n        basestring-builtin,\n        buffer-builtin,\n        c-extension-no-member,\n        consider-using-enumerate,\n        cmp-builtin,\n        cmp-method,\n        coerce-builtin,\n        coerce-method,\n        delslice-method,\n        div-method,\n        eq-without-hash,\n        execfile-builtin,\n        file-builtin,\n        filter-builtin-not-iterating,\n        fixme,\n        getslice-method,\n        global-statement,\n        hex-method,\n        idiv-method,\n        implicit-str-concat,\n        import-error,\n        import-self,\n        import-star-module-level,\n        input-builtin,\n        intern-builtin,\n        invalid-str-codec,\n        locally-disabled,\n        long-builtin,\n        long-suffix,\n        map-builtin-not-iterating,\n        misplaced-comparison-constant,\n        missing-function-docstring,\n        metaclass-assignment,\n        next-method-called,\n        next-method-defined,\n        no-absolute-import,\n        no-init,  # added\n        no-member,\n        no-name-in-module,\n        no-self-use,\n        nonzero-method,\n        oct-method,\n        old-division,\n        old-ne-operator,\n        old-octal-literal,\n        old-raise-syntax,\n        parameter-unpacking,\n        print-statement,\n        raising-string,\n        range-builtin-not-iterating,\n        raw_input-builtin,\n        rdiv-method,\n        reduce-builtin,\n        relative-import,\n        reload-builtin,\n        round-builtin,\n        setslice-method,\n        signature-differs,\n        standarderror-builtin,\n        suppressed-message,\n        sys-max-int,\n        trailing-newlines,\n        unichr-builtin,\n        unicode-builtin,\n        unnecessary-pass,\n        unpacking-in-except,\n        useless-else-on-loop,\n        useless-suppression,\n        using-cmp-argument,\n        wrong-import-order,\n        xrange-builtin,\n        zip-builtin-not-iterating,\n\n\n[REPORTS]\n\n# Set the output format. Available formats are text, parseable, colorized, msvs\n# (visual studio) and html. You can also give a reporter class, eg\n# mypackage.mymodule.MyReporterClass.\noutput-format=text\n\n# Tells whether to display a full report or only the messages\nreports=no\n\n# Activate the evaluation score.\nscore=no\n\n# Python expression which should return a note less than 10 (10 is the highest\n# note). You have access to the variables errors warning, statement which\n# respectively contain the number of errors / warnings messages and the total\n# number of statements analyzed. This is used by the global evaluation report\n# (RP0004).\nevaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)\n\n# Template used to display messages. This is a python new-style format string\n# used to format the message information. See doc for all details\n#msg-template=\n\n\n[BASIC]\n\n# Good variable names which should always be accepted, separated by a comma\ngood-names=main,_\n\n# Bad variable names which should always be refused, separated by a comma\nbad-names=\n\n# Colon-delimited sets of names that determine each other's naming style when\n# the name regexes allow several styles.\nname-group=\n\n# Include a hint for the correct naming format with invalid-name\ninclude-naming-hint=no\n\n# List of decorators that produce properties, such as abc.abstractproperty. Add\n# to this list to register other decorators that produce valid properties.\nproperty-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl\n\n# Regular expression matching correct function names\nfunction-rgx=^(?:(?P<exempt>setUp|tearDown|setUpModule|tearDownModule)|(?P<camel_case>_?[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_?[a-z][a-z0-9_]*))$\n\n# Regular expression matching correct variable names\nvariable-rgx=^[a-z][a-z0-9_]*$\n\n# Regular expression matching correct constant names\nconst-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$\n\n# Regular expression matching correct attribute names\nattr-rgx=^_{0,2}[a-z][a-z0-9_]*$\n\n# Regular expression matching correct argument names\nargument-rgx=^[a-z][a-z0-9_]*$\n\n# Regular expression matching correct class attribute names\nclass-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$\n\n# Regular expression matching correct inline iteration names\ninlinevar-rgx=^[a-z][a-z0-9_]*$\n\n# Regular expression matching correct class names\nclass-rgx=^_?[A-Z][a-zA-Z0-9]*$\n\n# Regular expression matching correct module names\nmodule-rgx=^(_?[a-z][a-z0-9_]*|__init__)$\n\n# Regular expression matching correct method names\nmethod-rgx=(?x)^(?:(?P<exempt>_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P<camel_case>_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P<snake_case>_{0,2}[a-z][a-z0-9_]*))$\n\n# Regular expression which should only match function or class names that do\n# not require a docstring.\nno-docstring-rgx=(__.*__|main|test.*|.*test|.*Test)$\n\n# Minimum line length for functions/classes that require docstrings, shorter\n# ones are exempt.\ndocstring-min-length=12\n\n\n[TYPECHECK]\n\n# List of decorators that produce context managers, such as\n# contextlib.contextmanager. Add to this list to register other decorators that\n# produce valid context managers.\ncontextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager\n\n# List of module names for which member attributes should not be checked\n# (useful for modules/projects where namespaces are manipulated during runtime\n# and thus existing member attributes cannot be deduced by static analysis. It\n# supports qualified module names, as well as Unix pattern matching.\nignored-modules=\n\n# List of class names for which member attributes should not be checked (useful\n# for classes with dynamically set attributes). This supports the use of\n# qualified names.\nignored-classes=optparse.Values,thread._local,_thread._local\n\n# List of members which are set dynamically and missed by pylint inference\n# system, and so shouldn't trigger E1101 when accessed. Python regular\n# expressions are accepted.\ngenerated-members=\n\n\n[FORMAT]\n\n# Maximum number of characters on a single line.\nmax-line-length=80\n\n# TODO(https://github.com/pylint-dev/pylint/issues/3352): Direct pylint to exempt\n# lines made too long by directives to pytype.\n\n# Regexp for a line that is allowed to be longer than the limit.\nignore-long-lines=(?x)(\n  ^\\s*(\\#\\ )?<?https?://\\S+>?$|\n  ^\\s*(from\\s+\\S+\\s+)?import\\s+.+$)\n\n# Allow the body of an if to be on the same line as the test if there is no\n# else.\nsingle-line-if-stmt=yes\n\n# Maximum number of lines in a module\nmax-module-lines=99999\n\n# String used as indentation unit.  The internal Google style guide mandates 2\n# spaces.  Google's externaly-published style guide says 4, consistent with\n# PEP 8.\nindent-string='    '\n\n# Number of spaces of indent required inside a hanging  or continued line.\nindent-after-paren=4\n\n# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.\nexpected-line-ending-format=\n\n\n[MISCELLANEOUS]\n\n# List of note tags to take in consideration, separated by a comma.\nnotes=TODO\n\n\n[STRING]\n\n# This flag controls whether inconsistent-quotes generates a warning when the\n# character used as a quote delimiter is used inconsistently within a module.\ncheck-quote-consistency=yes\n\n\n[VARIABLES]\n\n# Tells whether we should check for unused import in __init__ files.\ninit-import=no\n\n# A regular expression matching the name of dummy variables (i.e. expectedly\n# not used).\ndummy-variables-rgx=^\\*{0,2}(_$|unused_|dummy_)\n\n# List of additional names supposed to be defined in builtins. Remember that\n# you should avoid to define new builtins when possible.\nadditional-builtins=\n\n# List of strings which can identify a callback function by name. A callback\n# name must start or end with one of those strings.\ncallbacks=cb_,_cb\n\n# List of qualified module names which can have objects that can redefine\n# builtins.\nredefining-builtins-modules=six,six.moves,past.builtins,future.builtins,functools\n\n\n[LOGGING]\n\n# Logging modules to check that the string format arguments are in logging\n# function parameter format\nlogging-modules=logging,absl.logging,tensorflow.io.logging\n\n\n[SIMILARITIES]\n\n# Minimum lines number of a similarity.\nmin-similarity-lines=4\n\n# Ignore comments when computing similarities.\nignore-comments=yes\n\n# Ignore docstrings when computing similarities.\nignore-docstrings=yes\n\n# Ignore imports when computing similarities.\nignore-imports=no\n\n\n[SPELLING]\n\n# Spelling dictionary name. Available dictionaries: none. To make it working\n# install python-enchant package.\nspelling-dict=\n\n# List of comma separated words that should not be checked.\nspelling-ignore-words=\n\n# A path to a file that contains private dictionary; one word per line.\nspelling-private-dict-file=\n\n# Tells whether to store unknown words to indicated private dictionary in\n# --spelling-private-dict-file option instead of raising a message.\nspelling-store-unknown-words=no\n\n\n[IMPORTS]\n\n# Deprecated modules which should not be used, separated by a comma\ndeprecated-modules=regsub,\n                   TERMIOS,\n                   Bastion,\n                   rexec,\n                   sets\n\n# Create a graph of every (i.e. internal and external) dependencies in the\n# given file (report RP0402 must not be disabled)\nimport-graph=\n\n# Create a graph of external dependencies in the given file (report RP0402 must\n# not be disabled)\next-import-graph=\n\n# Create a graph of internal dependencies in the given file (report RP0402 must\n# not be disabled)\nint-import-graph=\n\n# Force import order to recognize a module as part of the standard\n# compatibility libraries.\nknown-standard-library=\n\n# Force import order to recognize a module as part of a third party library.\nknown-third-party=enchant, absl\n\n# Analyse import fallback blocks. This can be used to support both Python 2 and\n# 3 compatible code, which means that the block might have code that exists\n# only in one or another interpreter, leading to false positives when analysed.\nanalyse-fallback-blocks=no\n\n\n[CLASSES]\n\n# List of method names used to declare (i.e. assign) instance attributes.\ndefining-attr-methods=__init__,\n                      __new__,\n                      setUp\n\n# List of member names, which should be excluded from the protected access\n# warning.\nexclude-protected=_asdict,\n                  _fields,\n                  _replace,\n                  _source,\n                  _make\n\n# List of valid names for the first argument in a class method.\nvalid-classmethod-first-arg=cls,\n                            class_\n\n# List of valid names for the first argument in a metaclass class method.\nvalid-metaclass-classmethod-first-arg=mcs\n"
  },
  {
    "path": "shell.xml",
    "content": "<?xml version=\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"shell.xsl\"?>\n\n<GUIDE title=\"Shell Style Guide\"> \nThe guide has been moved to <a href=\"https://google.github.io/styleguide/shellguide.html\">shellguide.html</a>.\n</GUIDE> \n\n"
  },
  {
    "path": "shell.xsl",
    "content": "<xsl:stylesheet version=\"1.0\"\nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\nxmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\nxmlns:dc=\"http://purl.org/dc/elements/1.1/\"\nxmlns:dcq=\"http://purl.org/dc/qualifiers/1.0/\"\nxmlns:fo=\"http://www.w3.org/1999/XSL/Format\"\nxmlns:fn=\"http://www.w3.org/2005/xpath-functions\">\n  <xsl:output method=\"html\"/>\n  <!-- Set to 1 to show explanations by default.  Set to 0 to hide them -->\n  <xsl:variable name=\"show_explanation_default\" select=\"0\" />\n  <!-- The characters within the Webdings font that show the triangles -->\n  <xsl:variable name=\"show_button_text\" select=\"'&#x25B6;'\" />\n  <xsl:variable name=\"hide_button_text\" select=\"'&#x25BD;'\" />\n  <!-- The suffix for names -->\n  <xsl:variable name=\"button_suffix\" select=\"'__button'\"/>\n  <xsl:variable name=\"body_suffix\" select=\"'__body'\"/>\n  <!-- For easy reference, the name of the button -->\n  <xsl:variable name=\"show_hide_all_button\" select=\"'show_hide_all_button'\"/>\n\n  <!-- The top-level element -->\n  <xsl:template match=\"GUIDE\">\n      <HTML>\n          <HEAD>\n              <TITLE><xsl:value-of select=\"@title\"/></TITLE>\n              <META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n              <META http-equiv=\"refresh\" content=\"0;url=https://google.github.io/styleguide/shellguide.html\" />\n              <LINK rel=\"canonical\" href=\"https://google.github.io/styleguide/shellguide.html\" />\n              <LINK HREF=\"/styleguide/favicon.ico\" type=\"image/x-icon\"\n                    rel=\"shortcut icon\"/>\n              <LINK HREF=\"styleguide.css\"\n                    type=\"text/css\" rel=\"stylesheet\"/>\n\n              <SCRIPT language=\"javascript\" type=\"text/javascript\">\n\n                function GetElementsByName(name) {\n                  // Workaround a bug on old versions of opera.\n                  if (document.getElementsByName) {\n                    return document.getElementsByName(name);\n                  } else {\n                    return [document.getElementById(name)];\n                  }\n                }\n\n                /**\n                 * @param {string} namePrefix The prefix of the body name.\n                 * @param {function(boolean): boolean} getVisibility Computes the new\n                 *     visibility state, given the current one.\n                 */\n                function ChangeVisibility(namePrefix, getVisibility) {\n                  var bodyName = namePrefix + '<xsl:value-of select=\"$body_suffix\"/>';\n                  var buttonName = namePrefix + '<xsl:value-of select=\"$button_suffix\"/>';\n                  var bodyElements = GetElementsByName(bodyName);\n                  var linkElement = GetElementsByName('link-' + buttonName)[0];\n                  if (bodyElements.length != 1) {\n                    throw Error('ShowHideByName() got the wrong number of bodyElements:  ' + \n                        bodyElements.length);\n                  } else {\n                    var bodyElement = bodyElements[0];\n                    var buttonElement = GetElementsByName(buttonName)[0];\n                    var isVisible = bodyElement.style.display != \"none\";\n                    if (getVisibility(isVisible)) {\n                      bodyElement.style.display = \"inline\";\n                      linkElement.style.display = \"block\";\n                      buttonElement.innerHTML = '<xsl:value-of select=\"$hide_button_text\"/>';\n                    } else {\n                      bodyElement.style.display = \"none\";\n                      linkElement.style.display = \"none\";\n                      buttonElement.innerHTML = '<xsl:value-of select=\"$show_button_text\"/>';\n                    }\n                  }\n                }\n\n                function ShowHideByName(namePrefix) {\n                  ChangeVisibility(namePrefix, function(old) { return !old; });\n                }\n\n                function ShowByName(namePrefix) {\n                  ChangeVisibility(namePrefix, function() { return true; });\n                }\n\n                function ShowHideAll() {\n                  var allButton = GetElementsByName(\"show_hide_all_button\")[0];\n                  if (allButton.innerHTML == '<xsl:value-of select=\"$hide_button_text\"/>') {\n                    allButton.innerHTML = '<xsl:value-of select=\"$show_button_text\"/>';\n                    SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \"none\", '<xsl:value-of select=\"$show_button_text\"/>');\n                  } else {\n                    allButton.innerHTML = '<xsl:value-of select=\"$hide_button_text\"/>';\n                    SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \"inline\", '<xsl:value-of select=\"$hide_button_text\"/>');\n                  }\n                }\n\n                // Recursively sets state of all children\n                // of a particular node.\n                function SetHiddenState(root, newState, newButton) {\n                  for (var i = 0; i != root.length; i++) {\n                    SetHiddenState(root[i].childNodes, newState, newButton);\n                    if (root[i].className == 'showhide_button')  {\n                      root[i].innerHTML = newButton;\n                    }\n                    if (root[i].className == 'stylepoint_body' ||\n                        root[i].className == 'link_button')  {\n                      root[i].style.display = newState;\n                    }\n                  }\n                }\n\n\n                function EndsWith(str, suffix) {\n                  var l = str.length - suffix.length;\n                  return l >= 0 &amp;&amp; str.indexOf(suffix, l) == l;\n                }\n\n                function RefreshVisibilityFromHashParam() {\n                  var hashRegexp = new RegExp('#([^&amp;#]*)$');\n                  var hashMatch = hashRegexp.exec(window.location.href);\n                  var anchor = hashMatch &amp;&amp; GetElementsByName(hashMatch[1])[0];\n                  var node = anchor;\n                  var suffix = '<xsl:value-of select=\"$body_suffix\"/>';\n                  while (node) {\n                    var id = node.id;\n                    var matched = id &amp;&amp; EndsWith(id, suffix);\n                    if (matched) {\n                      var len = id.length - suffix.length;\n                      ShowByName(id.substring(0, len));\n                      if (anchor.scrollIntoView) {\n                        anchor.scrollIntoView();\n                      }\n\n                      return;\n                    }\n                    node = node.parentNode;\n                  }\n                }\n\n                window.onhashchange = RefreshVisibilityFromHashParam;\n\n                window.onload = function() {\n                  // if the URL contains \"?showall=y\", expand the details of all children\n                  var showHideAllRegex = new RegExp(\"[\\\\?&amp;](showall)=([^&amp;#]*)\");\n                  var showHideAllValue = showHideAllRegex.exec(window.location.href);\n                  if (showHideAllValue != null) {\n                    if (showHideAllValue[2] == \"y\") {\n                      SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \n                          \"inline\", '<xsl:value-of select=\"$hide_button_text\"/>');\n                    } else {\n                      SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \n                          \"none\", '<xsl:value-of select=\"$show_button_text\"/>');\n                    }\n                  }\n                  var showOneRegex = new RegExp(\"[\\\\?&amp;](showone)=([^&amp;#]*)\");\n                  var showOneValue = showOneRegex.exec(window.location.href);\n                  if (showOneValue) {\n                    ShowHideByName(showOneValue[2]);\n                  }\n\n\n                  RefreshVisibilityFromHashParam();\n                }\n              </SCRIPT>\n          </HEAD>\n          <BODY>\n            <H1><xsl:value-of select=\"@title\"/></H1>\n              <xsl:apply-templates/>\n          </BODY>\n      </HTML>\n  </xsl:template>\n\n  <!-- This passes through any HTML elements that the\n    XML doc uses for minor formatting -->\n  <xsl:template match=\"a|address|blockquote|br|center|cite|code|dd|div|dl|dt|em|hr|i|img|li|ol|p|pre|span|table|td|th|tr|ul|var|A|ADDRESS|BLOCKQUOTE|BR|CENTER|CITE|CODE|DD|DIV|DL|DT|EM|HR|I|LI|OL|P|PRE|SPAN|TABLE|TD|TH|TR|UL|VAR\">\n      <xsl:element name=\"{local-name()}\">\n          <xsl:copy-of select=\"@*\"/>\n          <xsl:apply-templates/>\n      </xsl:element>\n  </xsl:template>\n\n</xsl:stylesheet>\n\n"
  },
  {
    "path": "shellguide.md",
    "content": "<!--\nAUTHORS:\nPrefer only GitHub-flavored Markdown in external text.\nSee README.md for details.\n-->\n\n# Shell Style Guide\n\n\nAuthored, revised and maintained by many Googlers.\n\n## Table of Contents\n\nSection                                                                              | Contents\n------------------------------------------------------------------------------------ | --------\n[Background](#s1-background)                                                         | [Which Shell to Use](#s1.1-which-shell-to-use) - [When to use Shell](#s1.2-when-to-use-shell)\n[Shell Files and Interpreter Invocation](#s2-shell-files-and-interpreter-invocation) | [File Extensions](#s2.1-file-extensions) - [SUID/SGID](#s2.2-suid-sgid)\n[Environment](#s3-environment)                                                       | [STDOUT vs STDERR](#s3.1-stdout-vs-stderr)\n[Comments](#s4-comments)                                                             | [File Header](#s4.1-file-header) - [Function Comments](#s4.2-function-comments) - [Implementation Comments](#s4.3-implementation-comments) - [TODO Comments](#s4.4-todo-comments)\n[Formatting](#s5-formatting)                                                         | [Indentation](#s5.1-indentation) - [Line Length and Long Strings](#s5.2-line-length-and-long-strings) - [Pipelines](#s5.3-pipelines) - [Control Flow](#s5.4-control-flow) - [Case statement](#s5.5-case-statement) - [Variable expansion](#s5.6-variable-expansion) - [Quoting](#s5.7-quoting)\n[Features and Bugs](#s6-features-and-bugs)                                           |    [ShellCheck](#s6.1-shellcheck) - [Command Substitution](#s6.2-command-substitution) - [Test, `[… ]`, and `[[… ]]`](#s6.3-tests) - [Testing Strings](#s6.4-testing-strings) - [Wildcard Expansion of Filenames](#s6.5-wildcard-expansion-of-filenames) - [Eval](#s6.6-eval) - [Arrays](#s6.7-arrays) - [Pipes to While](#s6.8-pipes-to-while) - [Arithmetic](#s6.9-arithmetic) - [Aliases](#s6.10-aliases)\n[Naming Conventions](#s7-naming-conventions)                                         | [Function Names](#s7.1-function-names) - [Variable Names](#s7.2-variable-names) - [Constants and Environment Variable Names](#s7.3-constants-and-environment-variable-names) - [Source Filenames](#s7.4-source-filenames) - [Use Local Variables](#s7.5-use-local-variables) - [Function Location](#s7.6-function-location) - [main](#s7.7-main)\n[Calling Commands](#s8-calling-commands)                                             | [Checking Return Values](#s8.1-checking-return-values) - [Builtin Commands vs. External Commands](#s8.2-builtin-commands-vs-external-commands)\n[When in Doubt: Be Consistent](#s9-conclusion)                                       |\n\n<a id=\"s1-background\"></a>\n\n## Background\n\n\n<a id=\"s1.1-which-shell-to-use\"></a>\n\n### Which Shell to Use\n\nBash is the only shell scripting language permitted for executables.\n\nExecutables must start with `#!/bin/bash` and minimal flags. Use `set` to set\nshell options so that calling your script as `bash script_name` does not break\nits functionality.\n\nRestricting all executable shell scripts to *bash* gives us a consistent shell\nlanguage that's installed on all our machines. In particular, this means there\nis generally no need to strive for POSIX-compatibility or otherwise avoid\n\"bashisms\".\n\nThe only exception to the above is where you're forced to by whatever you're\ncoding for. For example some legacy operating systems or constrained execution\nenvironments may require plain Bourne shell for certain scripts.\n\n<a id=\"s1.2-when-to-use-shell\"></a>\n\n### When to use Shell\n\nShell should only be used for small utilities or simple wrapper\nscripts.\n\nWhile shell scripting isn't a development language, it is used for\nwriting various utility scripts throughout Google. This style guide\nis more a recognition of its use rather than a suggestion that it be\nused for widespread deployment.\n\nSome guidelines:\n\n*   If you're mostly calling other utilities and are doing relatively little\n    data manipulation, shell is an acceptable choice for the task.\n*   If performance matters, use something other than shell.\n*   If you are writing a script that is more than 100 lines long, or that uses\n    non-straightforward control flow logic, you should rewrite it in a more\n    structured language *now*. Bear in mind that scripts grow. Rewrite your\n    script early to avoid a more time-consuming rewrite at a later date.\n*   When assessing the complexity of your code (e.g. to decide whether to switch\n    languages) consider whether the code is easily maintainable by people other\n    than its author. \n\n<a id=\"s2-shell-files-and-interpreter-invocation\"></a>\n\n## Shell Files and Interpreter Invocation\n\n<a id=\"s2.1-file-extensions\"></a>\n\n### File Extensions\n\nExecutables should have a `.sh` extension or no extension.\n\n-   If the executable will have a build rule that renames the source file\n    then prefer to use a `.sh` extension.\n    This enables you to use the recommended naming convention, with a source\n    file like `foo.sh` and a build rule named `foo`.\n-   If the executable will be added directly to the user's `PATH`, then prefer\n    to use no extension. It is not necessary to know what language a program is\n    written in when executing it and shell doesn't require an extension so we\n    prefer not to use one for executables that will be directly invoked by\n    users. At the same time, consider whether it is preferable to deploy the\n    output of a build rule rather than deploying the source file directly.\n-   If neither of the above apply, then either choice is acceptable.\n\nLibraries must have a `.sh` extension and should not be executable.\n\n<a id=\"s2.2-suid-sgid\"></a>\n\n### SUID/SGID\n\nSUID and SGID are *forbidden* on shell scripts.\n\nThere are too many security issues with shell that make it nearly\nimpossible to secure sufficiently to allow SUID/SGID. While bash does\nmake it difficult to run SUID, it's still possible on some platforms\nwhich is why we're being explicit about banning it.\n\nUse `sudo` to provide elevated access if you need it.\n\n<a id=\"s3-environment\"></a>\n\n## Environment\n\n<a id=\"s3.1-stdout-vs-stderr\"></a>\n\n### STDOUT vs STDERR\n\nAll error messages should go to `STDERR`.\n\nThis makes it easier to separate normal status from actual issues.\n\nA function to print out error messages along with other status\ninformation is recommended.\n\n```shell\nerr() {\n  echo \"[$(date +'%Y-%m-%dT%H:%M:%S%z')]: $*\" >&2\n}\n\nif ! do_something; then\n  err \"Unable to do_something\"\n  exit 1\nfi\n```\n\n<a id=\"s4-comments\"></a>\n\n## Comments\n\n<a id=\"s4.1-file-header\"></a>\n\n### File Header\n\nStart each file with a description of its contents.\n\nEvery file must have a top-level comment including a brief overview of\nits contents. A\ncopyright notice\nand author information are optional.\n\nExample:\n\n```shell\n#!/bin/bash\n#\n# Perform hot backups of Oracle databases.\n```\n\n<a id=\"s4.2-function-comments\"></a>\n\n### Function Comments\n\nAny function that is not both obvious and short must have a function header\ncomment. Any function in a library must have a function header comment\nregardless of length or complexity.\n\nIt should be possible for someone else to learn how to use your\nprogram or to use a function in your library by reading the comments\n(and self-help, if provided) without reading the code.\n\nAll function header comments should describe the intended API behaviour using:\n\n*   Description of the function.\n*   Globals: List of global variables used and modified.\n*   Arguments: Arguments taken.\n*   Outputs: Output to STDOUT or STDERR.\n*   Returns: Returned values other than the default exit status of the last\n    command run.\n\nExample:\n\n```shell\n#######################################\n# Cleanup files from the backup directory.\n# Globals:\n#   BACKUP_DIR\n#   ORACLE_SID\n# Arguments:\n#   None\n#######################################\nfunction cleanup() {\n  …\n}\n\n#######################################\n# Get configuration directory.\n# Globals:\n#   SOMEDIR\n# Arguments:\n#   None\n# Outputs:\n#   Writes location to stdout\n#######################################\nfunction get_dir() {\n  echo \"${SOMEDIR}\"\n}\n\n#######################################\n# Delete a file in a sophisticated manner.\n# Arguments:\n#   File to delete, a path.\n# Returns:\n#   0 if thing was deleted, non-zero on error.\n#######################################\nfunction del_thing() {\n  rm \"$1\"\n}\n```\n\n<a id=\"s4.3-implementation-comments\"></a>\n\n### Implementation Comments\n\nComment tricky, non-obvious, interesting or important parts of your\ncode.\n\nThis follows general Google coding comment practice. Don't comment\neverything. If there's a complex algorithm or you're doing something\nout of the ordinary, put a short comment in.\n\n<a id=\"s4.4-todo-comments\"></a>\n\n### TODO Comments\n\nUse TODO comments for code that is temporary, a short-term solution, or\ngood-enough but not perfect.\n\nThis matches the convention in the [C++ Guide](https://google.github.io/styleguide/cppguide.html#TODO_Comments).\n\n\n`TODO`s should include the string `TODO` in all caps, followed by the name,\ne-mail address, or other identifier of the person with the best context about\nthe problem referenced by the `TODO`. The main purpose is to have a consistent\n`TODO` that can be searched to find out how to get more details upon request. A\n`TODO` is not a commitment that the person referenced will fix the problem. Thus\nwhen you create a `TODO`, it is almost always your name that is given.\n\nExamples:\n\n```shell\n# TODO(mrmonkey): Handle the unlikely edge cases (bug ####)\n```\n\n<a id=\"s5-formatting\"></a>\n\n## Formatting\n\nWhile you should follow the style that's already there for files that\nyou're modifying, the following are required for any new code.\n\n<a id=\"s5.1-indentation\"></a>\n\n### Indentation\n\nIndent 2 spaces. No tabs.\n\nUse blank lines between blocks to improve readability. Indentation is\ntwo spaces. Whatever you do, don't use tabs. For existing files, stay\nfaithful to the existing indentation.\n\n**Exception:** The only exception for using tabs is for the body of `<<-`\ntab-indented\n[here-document](https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Documents).\n\n<a id=\"s5.2-line-length-and-long-strings\"></a>\n\n### Line Length and Long Strings\n\nMaximum line length is 80 characters.\n\nIf you have to write literal strings that are longer than 80 characters, this\nshould be done with a\n[here document](https://www.gnu.org/software/bash/manual/html_node/Redirections.html#Here-Documents)\nor an embedded newline if possible.\n\nWords that are longer than 80 chars and can't sensibly be split are ok, but\nwhere possible these items should be on a line of their own, or factored into a\nvariable. Examples include file paths and URLs, particularly where\nstring-matching them (such as `grep`) is valuable for maintenance.\n\n```shell\n# DO use 'here document's\ncat <<END\nI am an exceptionally long\nstring.\nEND\n\n# Embedded newlines are ok too\nlong_string=\"I am an exceptionally\nlong string.\"\n\nlong_file=\"/i/am/an/exceptionally/loooooooooooooooooooooooooooooooooooooooooooooooooooong_file\"\n\nlong_string_with_long_file=\"i am including an exceptionally \\\n/very/long/file\\\n in this long string.\"\n\n# Long file converted into a shorter variable name with cleaner line breaking.\nlong_string_alt=\"i am an including an exceptionally ${long_file} in this long\\\n string\"\n```\n\n```shell\n# Just because a line contains an exception doesn't mean the rest of the\n# line shouldn't be wrapped like usual.\n\nbad_long_string_with_long_file=\"i am including an exceptionally /very/long/file in this long string.\"\n```\n\n<a id=\"s5.3-pipelines\"></a>\n\n### Pipelines\n\nPipelines should be split one per line if they don't all fit on one line.\n\nIf a pipeline all fits on one line, it should be on one line.\n\nIf not, it should be split at one pipe segment per line with the pipe on the\nnewline and a 2 space indent for the next section of the pipe. `\\ ` should be\nconsistently used to indicate line continuation. This applies to a chain of\ncommands combined using `|` as well as to logical compounds using `||` and `&&`.\n\n```shell\n# All fits on one line\ncommand1 | command2\n\n# Long commands\ncommand1 \\\n  | command2 \\\n  | command3 \\\n  | command4\n```\n\nThis helps readability when distinguishing a pipeline from a regular long\ncommand continuation, particularly if the line is using both.\n\nComments will need to precede the whole pipeline. If the comment and pipeline\nare large and complex, then it is worth considering moving low level details of\nthem aside by using a helper function.\n\n<a id=\"s5.4-control-flow\"></a>\n\n<!-- section was previously titled \"Loops\" -->\n\n<a id=\"s5.4-loops\"></a>\n<a id=\"loops\"></a>\n\n### Control Flow\n\nPut `; then` and `; do` on the same line as the `if`, `for`, or `while`.\n\nControl flow statements in shell are a bit different, but we follow the same\nprinciples as with braces when declaring functions. That is: `; then` and `; do`\nshould be on the same line as the `if`/`for`/`while`/`until`/`select`. `else`\nshould be on its own line and closing statements (`fi` and `done`) should be on\ntheir own line vertically aligned with the opening statement.\n\nExample:\n\n```shell\n# If inside a function remember to declare the loop variable as\n# a local to avoid it leaking into the global environment:\nlocal dir\nfor dir in \"${dirs_to_cleanup[@]}\"; do\n  if [[ -d \"${dir}/${SESSION_ID}\" ]]; then\n    log_date \"Cleaning up old files in ${dir}/${SESSION_ID}\"\n    rm \"${dir}/${SESSION_ID}/\"* || error_message\n  else\n    mkdir -p \"${dir}/${SESSION_ID}\" || error_message\n  fi\ndone\n```\n\nAlthough it is possible to\n[omit `in \"$@\"`](https://www.gnu.org/software/bash/manual/html_node/Looping-Constructs.html#index-for)\nin for loops we recommend consistently including it for clarity.\n\n```shell\nfor arg in \"$@\"; do\n  echo \"argument: ${arg}\"\ndone\n```\n\n<a id=\"s5.5-case-statement\"></a>\n\n### Case statement\n\n*   Indent alternatives by 2 spaces.\n*   A one-line alternative needs a space after the close parenthesis of the\n    pattern and before the `;;`.\n*   Long or multi-command alternatives should be split over multiple lines with\n    the pattern, actions, and `;;` on separate lines.\n\nThe matching expressions are indented one level from the `case` and `esac`.\nMultiline actions are indented another level. In general, there is no need to\nquote match expressions. Pattern expressions should not be preceded by an open\nparenthesis. Avoid the `;&` and `;;&` notations.\n\n```shell\ncase \"${expression}\" in\n  a)\n    variable=\"…\"\n    some_command \"${variable}\" \"${other_expr}\" …\n    ;;\n  absolute)\n    actions=\"relative\"\n    another_command \"${actions}\" \"${other_expr}\" …\n    ;;\n  *)\n    error \"Unexpected expression '${expression}'\"\n    ;;\nesac\n```\n\nSimple commands may be put on the same line as the pattern <i>and</i>\n`;;` as long as the expression remains readable. This is\noften appropriate for single-letter option processing. When the\nactions don't fit on a single line, put the pattern on a line on its\nown, then the actions, then `;;` also on a line of its own.\nWhen on the same line as the actions, use a space after the close\nparenthesis of the pattern and another before the `;;`.\n\n```shell\nverbose='false'\naflag=''\nbflag=''\nfiles=''\nwhile getopts 'abf:v' flag; do\n  case \"${flag}\" in\n    a) aflag='true' ;;\n    b) bflag='true' ;;\n    f) files=\"${OPTARG}\" ;;\n    v) verbose='true' ;;\n    *) error \"Unexpected option ${flag}\" ;;\n  esac\ndone\n```\n\n<a id=\"s5.6-variable-expansion\"></a>\n\n### Variable expansion\n\nIn order of precedence: Stay consistent with what you find; quote your\nvariables; prefer `\"${var}\"` over `\"$var\"`.\n\nThese are strongly recommended guidelines but not mandatory\nregulation. Nonetheless, the fact that it's a recommendation and\nnot mandatory doesn't mean it should be taken lightly or downplayed.\n\nThey are listed in order of precedence.\n\n*   Stay consistent with what you find for existing code.\n*   Quote variables, see [Quoting section below](#quoting).\n*   Don't brace-delimit single character shell specials / positional parameters,\n    unless strictly necessary or avoiding deep confusion.\n\nPrefer brace-delimiting all other variables.\n\n```shell\n# Section of *recommended* cases.\n\n# Preferred style for 'special' variables:\necho \"Positional: $1\" \"$5\" \"$3\"\necho \"Specials: !=$!, -=$-, _=$_. ?=$?, #=$# *=$* @=$@ \\$=$$ …\"\n\n# Braces necessary:\necho \"many parameters: ${10}\"\n\n# Braces avoiding confusion:\n# Output is \"a0b0c0\"\nset -- a b c\necho \"${1}0${2}0${3}0\"\n\n# Preferred style for other variables:\necho \"PATH=${PATH}, PWD=${PWD}, mine=${some_var}\"\nwhile read -r f; do\n  echo \"file=${f}\"\ndone < <(find /tmp)\n```\n\n```shell\n# Section of *discouraged* cases\n\n# Unquoted vars, unbraced vars, brace-delimited single letter\n# shell specials.\necho a=$avar \"b=$bvar\" \"PID=${$}\" \"${1}\"\n\n# Confusing use: this is expanded as \"${1}0${2}0${3}0\",\n# not \"${10}${20}${30}\nset -- a b c\necho \"$10$20$30\"\n```\n\nNOTE: Using braces in `${var}` is *not* a form of quoting. \"Double quotes\" must\nbe used *as well*.\n\n<a id=\"s5.7-quoting\"></a>\n\n### Quoting\n\n*   Always quote strings containing variables, command substitutions, spaces or\n    shell meta characters, unless careful unquoted expansion is required or it's\n    a shell-internal integer (see next point).\n*   Use arrays for safe quoting of lists of elements, especially command-line\n    flags. See [Arrays](#arrays) below.\n*   Optionally quote shell-internal, readonly\n    [special variables](https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html)\n    that are defined to be integers: `$?`, `$#`, `$$`, `$!`. Prefer quoting of\n    \"named\" internal integer variables, e.g. PPID etc for consistency.\n*   Prefer quoting strings that are \"words\" (as opposed to command options or\n    path names).\n*   Be aware of the quoting rules for pattern matches in `[[ … ]]`. See the\n    [Test, `[ … ]`, and `[[ … ]]`](#tests) section below.\n*   Use `\"$@\"` unless you have a specific reason to use `$*`, such as simply\n    appending the arguments to a string in a message or log.\n\n```shell\n# 'Single' quotes indicate that no substitution is desired.\n# \"Double\" quotes indicate that substitution is required/tolerated.\n\n# Simple examples\n\n# \"quote command substitutions\"\n# Note that quotes nested inside \"$()\" don't need escaping.\nflag=\"$(some_command and its args \"$@\" 'quoted separately')\"\n\n# \"quote variables\"\necho \"${flag}\"\n\n# Use arrays with quoted expansion for lists.\ndeclare -a FLAGS\nFLAGS=( --foo --bar='baz' )\nreadonly FLAGS\nmybinary \"${FLAGS[@]}\"\n\n# It's ok to not quote internal integer variables.\nif (( $# > 3 )); then\n  echo \"ppid=${PPID}\"\nfi\n\n# \"never quote literal integers\"\nvalue=32\n# \"quote command substitutions\", even when you expect integers\nnumber=\"$(generate_number)\"\n\n# \"prefer quoting words\", not compulsory\nreadonly USE_INTEGER='true'\n\n# \"quote shell meta characters\"\necho 'Hello stranger, and well met. Earn lots of $$$'\necho \"Process $$: Done making \\$\\$\\$.\"\n\n# \"command options or path names\"\n# ($1 is assumed to contain a value here)\ngrep -li Hugo /dev/null \"$1\"\n\n# Less simple examples\n# \"quote variables, unless proven false\": ccs might be empty\ngit send-email --to \"${reviewers}\" ${ccs:+\"--cc\" \"${ccs}\"}\n\n# Positional parameter precautions: $1 might be unset\n# Single quotes leave regex as-is.\ngrep -cP '([Ss]pecial|\\|?characters*)$' ${1:+\"$1\"}\n\n# For passing on arguments,\n# \"$@\" is right almost every time, and\n# $* is wrong almost every time:\n#\n# * $* and $@ will split on spaces, clobbering up arguments\n#   that contain spaces and dropping empty strings;\n# * \"$@\" will retain arguments as-is, so no args\n#   provided will result in no args being passed on;\n#   This is in most cases what you want to use for passing\n#   on arguments.\n# * \"$*\" expands to one argument, with all args joined\n#   by (usually) spaces,\n#   so no args provided will result in one empty string\n#   being passed on.\n#\n# Consult\n# https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html and\n# https://mywiki.wooledge.org/BashGuide/Arrays for more\n\n(set -- 1 \"2 two\" \"3 three tres\"; echo $#; set -- \"$*\"; echo \"$#, $@\")\n(set -- 1 \"2 two\" \"3 three tres\"; echo $#; set -- \"$@\"; echo \"$#, $@\")\n```\n\n<a id=\"s6-features-and-bugs\"></a>\n\n## Features and Bugs\n\n<a id=\"s6.1-shellcheck\"></a>\n\n### ShellCheck\n\nThe [ShellCheck project](https://www.shellcheck.net/) identifies common bugs and\nwarnings for your shell scripts. It is recommended for all scripts, large or\nsmall.\n\n<a id=\"s6.2-command-substitution\"></a>\n\n### Command Substitution\n\nUse `$(command)` instead of backticks.\n\nNested backticks require escaping the inner ones with `\\ `.\nThe `$(command)` format doesn't change when nested and is\neasier to read.\n\nExample:\n\n```shell\n# This is preferred:\nvar=\"$(command \"$(command1)\")\"\n```\n\n```shell\n# This is not:\nvar=\"`command \\`command1\\``\"\n```\n\n<a id=\"s6.3-tests\"></a>\n\n<a id=\"tests\"></a>\n### Test, `[ … ]`, and `[[ … ]]` \n\n`[[ … ]]` is preferred over `[ … ]`, `test` and `/usr/bin/[`.\n\n`[[ … ]]` reduces errors as no pathname expansion or word splitting takes place\nbetween `[[` and `]]`. In addition, `[[ … ]]` allows for pattern and regular\nexpression matching, while `[ … ]` does not.\n\n```shell\n# This ensures the string on the left is made up of characters in\n# the alnum character class followed by the string name.\n# Note that the RHS should not be quoted here.\nif [[ \"filename\" =~ ^[[:alnum:]]+name ]]; then\n  echo \"Match\"\nfi\n\n# This matches the exact pattern \"f*\" (Does not match in this case)\nif [[ \"filename\" == \"f*\" ]]; then\n  echo \"Match\"\nfi\n```\n\n```shell\n# This gives a \"too many arguments\" error as f* is expanded to the\n# contents of the current directory. It might also trigger the\n# \"unexpected operator\" error because `[` does not support `==`, only `=`.\nif [ \"filename\" == f* ]; then\n  echo \"Match\"\nfi\n```\n\nFor the gory details, see E14 in the [Bash FAQ](http://tiswww.case.edu/php/chet/bash/FAQ)\n\n<a id=\"s6.4-testing-strings\"></a>\n\n### Testing Strings\n\nUse quotes rather than filler characters where possible.\n\nBash is smart enough to deal with an empty string in a test. So, given\nthat the code is much easier to read, use tests for empty/non-empty\nstrings or empty strings rather than filler characters.\n\n```shell\n# Do this:\nif [[ \"${my_var}\" == \"some_string\" ]]; then\n  do_something\nfi\n\n# -z (string length is zero) and -n (string length is not zero) are\n# preferred over testing for an empty string\nif [[ -z \"${my_var}\" ]]; then\n  do_something\nfi\n\n# This is OK (ensure quotes on the empty side), but not preferred:\nif [[ \"${my_var}\" == \"\" ]]; then\n  do_something\nfi\n```\n\n```shell\n# Not this:\nif [[ \"${my_var}X\" == \"some_stringX\" ]]; then\n  do_something\nfi\n```\n\nTo avoid confusion about what you're testing for, explicitly use\n`-z` or `-n`.\n\n```shell\n# Use this\nif [[ -n \"${my_var}\" ]]; then\n  do_something\nfi\n```\n\n```shell\n# Instead of this\nif [[ \"${my_var}\" ]]; then\n  do_something\nfi\n```\n\nFor clarity, use `==` for equality rather than\n`=` even though both work. The former encourages the use of\n`[[` and the latter can be confused with an assignment.\nHowever, be careful when using `<` and `>`\nin `[[ … ]]` which performs a lexicographical comparison.\nUse `(( … ))` or `-lt` and `-gt` for\nnumerical comparison.\n\n```shell\n# Use this\nif [[ \"${my_var}\" == \"val\" ]]; then\n  do_something\nfi\n\nif (( my_var > 3 )); then\n  do_something\nfi\n\nif [[ \"${my_var}\" -gt 3 ]]; then\n  do_something\nfi\n```\n\n```shell\n# Instead of this\nif [[ \"${my_var}\" = \"val\" ]]; then\n  do_something\nfi\n\n# Probably unintended lexicographical comparison.\nif [[ \"${my_var}\" > 3 ]]; then\n  # True for 4, false for 22.\n  do_something\nfi\n```\n\n<a id=\"s6.5-wildcard-expansion-of-filenames\"></a>\n\n### Wildcard Expansion of Filenames\n\nUse an explicit path when doing wildcard expansion of filenames.\n\nAs filenames can begin with a `-`, it's a lot safer to\nexpand wildcards with `./*` instead of `*`.\n\n```shell\n# Here's the contents of the directory:\n# -f  -r  somedir  somefile\n\n# Incorrectly deletes almost everything in the directory by force\npsa@bilby$ rm -v *\nremoved directory: `somedir'\nremoved `somefile'\n```\n\n```shell\n# As opposed to:\npsa@bilby$ rm -v ./*\nremoved `./-f'\nremoved `./-r'\nrm: cannot remove `./somedir': Is a directory\nremoved `./somefile'\n```\n\n<a id=\"s6.6-eval\"></a>\n\n### Eval\n\n`eval` should be avoided.\n\n\nEval munges the input when used for assignment to variables and can\nset variables without making it possible to check what those variables\nwere.\n\n```shell\n# What does this set?\n# Did it succeed? In part or whole?\neval $(set_my_variables)\n\n# What happens if one of the returned values has a space in it?\nvariable=\"$(eval some_function)\"\n```\n\n<a id=\"s6.7-arrays\"></a>\n\n### Arrays\n\nBash arrays should be used to store lists of elements, to avoid quoting\ncomplications. This particularly applies to argument lists. Arrays\nshould not be used to facilitate more complex data structures (see\n[When to use Shell](#when-to-use-shell) above).\n\nArrays store an ordered collection of strings, and can be safely\nexpanded into individual elements for a command or loop.\n\nUsing a single string for multiple command arguments should be\navoided, as it inevitably leads to authors using `eval`\nor trying to nest quotes inside the string, which does not give\nreliable or readable results and leads to needless complexity.\n\n```shell\n# An array is assigned using parentheses, and can be appended to\n# with +=( … ).\ndeclare -a flags\nflags=(--foo --bar='baz')\nflags+=(--greeting=\"Hello ${name}\")\nmybinary \"${flags[@]}\"\n```\n\n```shell\n# Don’t use strings for sequences.\nflags='--foo --bar=baz'\nflags+=' --greeting=\"Hello world\"'  # This won’t work as intended.\nmybinary ${flags}\n```\n\n```shell\n# Command expansions return single strings, not arrays. Avoid\n# unquoted expansion in array assignments because it won’t\n# work correctly if the command output contains special\n# characters or whitespace.\n\n# This expands the listing output into a string, then does special keyword\n# expansion, and then whitespace splitting.  Only then is it turned into a\n# list of words.  The ls command may also change behavior based on the user's\n# active environment!\ndeclare -a files=($(ls /directory))\n\n# The get_arguments writes everything to STDOUT, but then goes through the\n# same expansion process above before turning into a list of arguments.\nmybinary $(get_arguments)\n```\n\n<a id=\"s6.7.1-arrays-pros\"></a>\n\n#### Arrays Pros\n\n*   Using Arrays allows lists of things without confusing quoting semantics.\n    Conversely, not using arrays leads to misguided attempts to nest quoting\n    inside a string.\n*   Arrays make it possible to safely store sequences/lists of arbitrary\n    strings, including strings containing whitespace.\n\n<a id=\"s6.7.2-arrays-cons\"></a>\n\n#### Arrays Cons\n\nUsing arrays can risk a script’s complexity growing.\n\n<a id=\"s6.7.3-arrays-decision\"></a>\n\n#### Arrays Decision\n\nArrays should be used to safely create and pass around lists. In\nparticular, when building a set of command arguments, use arrays to\navoid confusing quoting issues. Use quoted expansion –\n`\"${array[@]}\"` – to access arrays. However, if more\nadvanced data manipulation is required, shell scripting should be\navoided altogether; see [above](#when-to-use-shell).\n\n<a id=\"s6.8-pipes-to-while\"></a>\n\n### Pipes to While\n\nUse process substitution or the `readarray` builtin (bash4+) in preference to\npiping to `while`. Pipes create a subshell, so any variables modified within a\npipeline do not propagate to the parent shell.\n\nThe implicit subshell in a pipe to `while` can introduce subtle bugs that are\nhard to track down.\n\n```shell\nlast_line='NULL'\nyour_command | while read -r line; do\n  if [[ -n \"${line}\" ]]; then\n    last_line=\"${line}\"\n  fi\ndone\n\n# This will always output 'NULL'!\necho \"${last_line}\"\n```\n\nUsing process substitution also creates a subshell. However, it allows\nredirecting from a subshell to a `while` without putting the `while` (or any\nother command) in a subshell.\n\n```shell\nlast_line='NULL'\nwhile read line; do\n  if [[ -n \"${line}\" ]]; then\n    last_line=\"${line}\"\n  fi\ndone < <(your_command)\n\n# This will output the last non-empty line from your_command\necho \"${last_line}\"\n```\n\nAlternatively, use the `readarray` builtin to read the file into an array, then\nloop over the array's contents. Notice that (for the same reason as above) you\nneed to use a process substitution with `readarray` rather than a pipe, but with\nthe advantage that the input generation for the loop is located before it,\nrather than after.\n\n```shell\nlast_line='NULL'\nreadarray -t lines < <(your_command)\nfor line in \"${lines[@]}\"; do\n  if [[ -n \"${line}\" ]]; then\n    last_line=\"${line}\"\n  fi\ndone\necho \"${last_line}\"\n```\n\n> Note: Be cautious using a for-loop to iterate over output, as in `for var in\n> $(...)`, as the output is split by whitespace, not by line. Sometimes you will\n> know this is safe because the output can't contain any unexpected whitespace,\n> but where this isn't obvious or doesn't improve readability (such as a long\n> command inside `$(...)`), a `while read` loop or `readarray` is often safer\n> and clearer.\n\n<a id=\"s6.9-arithmetic\"></a>\n\n### Arithmetic\n\nAlways use `(( … ))` or `$(( … ))` rather than\n`let` or `$[ … ]` or `expr`.\n\nNever use the `$[ … ]` syntax, the `expr`\ncommand, or the `let` built-in.\n\n`<` and `>` don't perform numerical\ncomparison inside `[[ … ]]` expressions (they perform\nlexicographical comparisons instead; see [Testing Strings](#testing-strings)).\nFor preference, don't use `[[ … ]]` *at all* for numeric comparisons, use\n`(( … ))` instead.\n\nIt is recommended to avoid using `(( … ))` as a standalone\nstatement, and otherwise be wary of its expression evaluating to zero\n- particularly with `set -e` enabled. For example,\n`set -e; i=0; (( i++ ))` will cause the shell to exit.\n\n```shell\n# Simple calculation used as text - note the use of $(( … )) within\n# a string.\necho \"$(( 2 + 2 )) is 4\"\n\n# When performing arithmetic comparisons for testing\nif (( a < b )); then\n  …\nfi\n\n# Some calculation assigned to a variable.\n(( i = 10 * j + 400 ))\n```\n\n```shell\n# This form is non-portable and deprecated\ni=$[2 * 10]\n\n# Despite appearances, 'let' isn't one of the declarative keywords,\n# so unquoted assignments are subject to globbing wordsplitting.\n# For the sake of simplicity, avoid 'let' and use (( … ))\nlet i=\"2 + 2\"\n\n# The expr utility is an external program and not a shell builtin.\ni=$( expr 4 + 4 )\n\n# Quoting can be error prone when using expr too.\ni=$( expr 4 '*' 4 )\n```\n\nStylistic considerations aside, the shell's built-in arithmetic is\nmany times faster than `expr`.\n\nWhen using variables, the `${var}` (and `$var`)\nforms are not required within `$(( … ))`. The shell knows\nto look up `var` for you, and omitting the\n`${…}` leads to cleaner code. This is slightly contrary to\nthe previous rule about always using braces, so this is a\nrecommendation only.\n\n```shell\n# N.B.: Remember to declare your variables as integers when\n# possible, and to prefer local variables over globals.\nlocal -i hundred=\"$(( 10 * 10 ))\"\ndeclare -i five=\"$(( 10 / 2 ))\"\n\n# Increment the variable \"i\" by three.\n# Note that:\n#  - We do not write ${i} or $i.\n#  - We put a space after the (( and before the )).\n(( i += 3 ))\n\n# To decrement the variable \"i\" by five:\n(( i -= 5 ))\n\n# Do some complicated computations.\n# Note that normal arithmetic operator precedence is observed.\nhr=2\nmin=5\nsec=30\necho \"$(( hr * 3600 + min * 60 + sec ))\" # prints 7530 as expected\n```\n\n<a id=\"s6.10-aliases\"></a>\n\n## Aliases\n\nAlthough commonly seen in `.bashrc` files, aliases should be avoided in scripts.\nAs the\n[Bash manual](https://www.gnu.org/software/bash/manual/html_node/Aliases.html)\nnotes:\n\n> For almost every purpose, shell functions are preferred over aliases.\n\nAliases are cumbersome to work with because they require carefully quoting and\nescaping their contents, and mistakes can be hard to notice.\n\n```shell\n# this evaluates $RANDOM once when the alias is defined,\n# so the echo'ed string will be the same on each invocation\nalias random_name=\"echo some_prefix_${RANDOM}\"\n```\n\nFunctions provide a superset of alias' functionality and should always be\npreferred. .\n\n```shell\nrandom_name() {\n  echo \"some_prefix_${RANDOM}\"\n}\n\n# Note that unlike aliases function's arguments are accessed via $@\nfancy_ls() {\n  ls -lh \"$@\"\n}\n```\n\n<a id=\"s7-naming-conventions\"></a>\n\n## Naming Conventions\n\n<a id=\"s7.1-function-names\"></a>\n\n### Function Names\n\nLower-case, with underscores to separate words. Separate libraries with `::`.\nParentheses are required after the function name. The keyword `function` is\noptional, but must be used consistently throughout a project.\n\nIf you're writing single functions, use lowercase and separate words with\nunderscore. If you're writing a package, separate package names with `::`.\nHowever, functions intended for interactive use may choose to avoid colons as it\ncan confuse bash auto-completion.\n\nBraces must be on the same line as the function name (as with other languages at\nGoogle) and no space between the function name and the parenthesis.\n\n```shell\n# Single function\nmy_func() {\n  …\n}\n\n# Part of a package\nmypackage::my_func() {\n  …\n}\n```\n\nThe `function` keyword is extraneous when \"()\" is present\nafter the function name, but enhances quick identification of\nfunctions.\n\n<a id=\"s7.2-variable-names\"></a>\n\n### Variable Names\n\nSame as for function names.\n\nVariables names for loops should be similarly named for any variable\nyou're looping through.\n\n```shell\nfor zone in \"${zones[@]}\"; do\n  something_with \"${zone}\"\ndone\n```\n\n<a id=\"s7.3-constants-and-environment-variable-names\"></a>\n<a id=\"s7.5-read-only-variables\"></a>\n\n### Constants, Environment Variables, and readonly Variables\n\nConstants and anything exported to the environment should be capitalized,\nseparated with underscores, and declared at the top of the file.\n\n```shell\n# Constant\nreadonly PATH_TO_FILES='/some/path'\n\n# Both constant and exported to the environment\ndeclare -xr ORACLE_SID='PROD'\n```\n\nFor the sake of clarity `readonly` or `export` is recommended vs. the equivalent\n`declare` commands. You can do one after the other, like:\n\n```shell\n# Constant\nreadonly PATH_TO_FILES='/some/path'\nexport PATH_TO_FILES\n```\n\nIt's OK to set a constant at runtime or in a conditional, but it should be made\nreadonly immediately afterwards.\n\n```shell\nZIP_VERSION=\"$(dpkg --status zip | sed -n 's/^Version: //p')\"\nif [[ -z \"${ZIP_VERSION}\" ]]; then\n  ZIP_VERSION=\"$(pacman -Q --info zip | sed -n 's/^Version *: //p')\"\nfi\nif [[ -z \"${ZIP_VERSION}\" ]]; then\n  handle_error_and_quit\nfi\nreadonly ZIP_VERSION\n```\n\n<a id=\"s7.4-source-filenames\"></a>\n\n### Source Filenames\n\nLowercase, with underscores to separate words if desired.\n\nThis is for consistency with other code styles in Google:\n`maketemplate` or `make_template` but not\n`make-template`.\n\n<a id=\"s7.5-use-local-variables\"></a>\n<a id=\"s7.6-use-local-variables\"></a>\n\n### Use Local Variables\n\nDeclare function-specific variables with `local`.\n\nEnsure that local variables are only seen inside a function and its children by\nusing `local` when declaring them. This avoids polluting the global namespace\nand inadvertently setting variables that may have significance outside the\nfunction.\n\nDeclaration and assignment must be separate statements when the\nassignment value is provided by a command substitution; as the\n`local` builtin does not propagate the exit code from the\ncommand substitution.\n\n```shell\nmy_func2() {\n  local name=\"$1\"\n\n  # Separate lines for declaration and assignment:\n  local my_var\n  my_var=\"$(my_func)\"\n  (( $? == 0 )) || return\n\n  …\n}\n```\n\n```shell\nmy_func2() {\n  # DO NOT do this:\n  # $? will always be zero, as it contains the exit code of 'local', not my_func\n  local my_var=\"$(my_func)\"\n  (( $? == 0 )) || return\n\n  …\n}\n```\n\n<a id=\"s7.6-function-location\"></a>\n<a id=\"s7.7-function-location\"></a>\n\n### Function Location\n\nPut all functions together in the file just below constants. Don't hide\nexecutable code between functions. Doing so makes the code difficult to follow\nand results in nasty surprises when debugging.\n\nIf you've got functions, put them all together near the top of the\nfile. Only includes, `set` statements and setting constants\nmay be done before declaring functions.\n\n<a id=\"s7.7-main\"></a>\n<a id=\"s7.8-main\"></a>\n\n### main\n\nA function called `main` is required for scripts long enough\nto contain at least one other function.\n\nIn order to easily find the start of the program, put the main program in a\nfunction called `main` as the bottom-most function. This provides consistency\nwith the rest of the code base as well as allowing you to define more variables\nas `local` (which can't be done if the main code is not a function). The last\nnon-comment line in the file should be a call to `main`:\n\n```shell\nmain \"$@\"\n```\n\nObviously, for short scripts where it's just a linear flow,\n`main` is overkill and so is not required.\n\n<a id=\"s8-calling-commands\"></a>\n\n## Calling Commands\n\n<a id=\"s8.1-checking-return-values\"></a>\n\n### Checking Return Values\n\nAlways check return values and give informative return values.\n\nFor unpiped commands, use `$?` or check directly via an\n`if` statement to keep it simple.\n\nExample:\n\n```shell\nif ! mv \"${file_list[@]}\" \"${dest_dir}/\"; then\n  echo \"Unable to move ${file_list[*]} to ${dest_dir}\" >&2\n  exit 1\nfi\n\n# Or\nmv \"${file_list[@]}\" \"${dest_dir}/\"\nif (( $? != 0 )); then\n  echo \"Unable to move ${file_list[*]} to ${dest_dir}\" >&2\n  exit 1\nfi\n```\n\nBash also has the `PIPESTATUS` variable that allows\nchecking of the return code from all parts of a pipe. If it's only\nnecessary to check success or failure of the whole pipe, then the\nfollowing is acceptable:\n\n```shell\ntar -cf - ./* | ( cd \"${dir}\" && tar -xf - )\nif (( PIPESTATUS[0] != 0 || PIPESTATUS[1] != 0 )); then\n  echo \"Unable to tar files to ${dir}\" >&2\nfi\n```\n\nHowever, as `PIPESTATUS` will be overwritten as soon as you\ndo any other command, if you need to act differently on errors based\non where it happened in the pipe, you'll need to assign\n`PIPESTATUS` to another variable immediately after running\nthe command (don't forget that `[` is a command and will\nwipe out `PIPESTATUS`).\n\n```shell\ntar -cf - ./* | ( cd \"${DIR}\" && tar -xf - )\nreturn_codes=( \"${PIPESTATUS[@]}\" )\nif (( return_codes[0] != 0 )); then\n  do_something\nfi\nif (( return_codes[1] != 0 )); then\n  do_something_else\nfi\n```\n\n<a id=\"s8.2-builtin-commands-vs-external-commands\"></a>\n\n### Builtin Commands vs. External Commands\n\nGiven the choice between invoking a shell builtin and invoking a\nseparate process, choose the builtin.\n\nWe prefer the use of builtins such as the\n[*Parameter Expansion*](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)\nfunctionality provided by `bash` as it's more efficient, robust, and portable\n(especially when compared to things like `sed`). See also the\n[`=~` operator](https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#index-_005b_005b).\n\nExamples:\n\n```shell\n# Prefer this:\naddition=\"$(( X + Y ))\"\nsubstitution=\"${string/#foo/bar}\"\nif [[ \"${string}\" =~ foo:(\\d+) ]]; then\n  extraction=\"${BASH_REMATCH[1]}\"\nfi\n```\n\n```shell\n# Instead of this:\naddition=\"$(expr \"${X}\" + \"${Y}\")\"\nsubstitution=\"$(echo \"${string}\" | sed -e 's/^foo/bar/')\"\nextraction=\"$(echo \"${string}\" | sed -e 's/foo:\\([0-9]\\)/\\1/')\"\n```\n\n<a id=\"s9-conclusion\"></a>\n\n## When in Doubt: Be Consistent\n\nUsing one style consistently through our codebase lets us focus on other (more\nimportant) issues. Consistency also allows for automation. In many cases, rules\nthat are attributed to “Be Consistent” boil down to “Just pick one and stop\nworrying about it”; the potential value of allowing flexibility on these points\nis outweighed by the cost of having people argue over them.\n\nHowever, there are limits to consistency. It is a good tie breaker when there is\nno clear technical argument, nor a long-term direction. Consistency should not\ngenerally be used as a justification to do things in an old style without\nconsidering the benefits of the new style, or the tendency of the codebase to\nconverge on newer styles over time.\n"
  },
  {
    "path": "styleguide.css",
    "content": "body {\n  background-color: #fff;\n  color: #333;\n  font-family: sans-serif;\n  font-size: 10pt;\n  margin-right: 100px;\n  margin-left: 100px;\n}\n\nh1,\nh2,\nh3,\nh4,\nh5,\nh6,\n.toc_title {\n  color: #06c;\n  margin-top: 2em;\n  margin-bottom: 1em;\n}\n\nh1 {\n  text-align: center;\n  font-size: 18pt;\n}\n\nh2,\n.toc_title {\n  font-weight: bold;\n  font-size: 12pt;\n  margin-left: -40px;\n}\n\nh3,\nh4,\nh5,\nh6 {\n  font-size: 10pt;\n  margin-left: -20px;\n}\n\n.toc_category,\n.toc_stylepoint {\n  font-size: 10pt;\n  padding-top: 0.3em;\n  padding-bottom: 0.3em;\n}\n\ntable {\n  border-collapse: collapse;\n}\n\ntd,\nth {\n  border: 1px solid #ccc;\n  padding: 2px 12px;\n  font-size: 10pt;\n}\n\n.toc td,\n.toc th {\n  border-width: 1px 5px;\n}\n\ncode,\nsamp,\nvar {\n  color: #060;\n}\n\npre {\n  font-size: 10pt;\n  display: block;\n  color: #060;\n  background-color: #f8fff8;\n  border: 1px solid #f0fff0;\n  border-left-width: 5px;\n  padding: 4px 12px;\n}\n\npre.badcode {\n  color: #c00;\n  background-color: #fff8f8;\n  border-color: #fff0f0;\n}\n\n.showhide_button {\n  float: left;\n  cursor: pointer;\n  border: 1px solid;\n  border-color: #ddd #aaa #aaa #ddd;\n  padding: 0 3px 1px;\n  margin: 0 4px 8px 0;\n  border-radius: 3px;\n  -webkit-border-radius: 3px;\n  -moz-border-radius: 3px;\n}\n\n.link_button {\n  float: left;\n  display: none;\n  background-color: #f8f8ff;\n  border: 1px solid #f0f0ff;\n  font-size: 75%;\n  margin-top: 0;\n  margin-left: -50px;\n  padding: 4px;\n  border-radius: 3px;\n  -webkit-border-radius: 3px;\n  -moz-border-radius: 3px;\n}\n\naddress {\n  text-align: right;\n}\n\nhr {\n  margin-top: 3.5em;\n  border-width: 1px;\n  color: #fff;\n}\n\n.stylepoint_section {\n  display: block;\n  margin-bottom: 1em;\n  color: #58f;\n  font-family: sans-serif;\n  font-size: 90%;\n  font-weight: bold;\n  margin-left: -2%;\n}\n\n.stylepoint_subsection {\n  color: #679;\n  font-family: sans-serif;\n  font-size: 90%;\n  font-weight: bold;\n  margin-left: -1%;\n}\n\n.stylepoint_subsubsection {\n  color: #679;\n  font-family: sans-serif;\n  font-size: 80%;\n  font-weight: bold;\n  margin-left: 0;\n}\n\n.revision {\n  text-align: right;\n}\n"
  },
  {
    "path": "styleguide.xsl",
    "content": "<xsl:stylesheet version=\"1.0\"\nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\nxmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\nxmlns:dc=\"http://purl.org/dc/elements/1.1/\"\nxmlns:dcq=\"http://purl.org/dc/qualifiers/1.0/\"\nxmlns:fo=\"http://www.w3.org/1999/XSL/Format\"\nxmlns:fn=\"http://www.w3.org/2005/xpath-functions\">\n  <xsl:output method=\"html\"/>\n  <!-- Set to 1 to show explanations by default.  Set to 0 to hide them -->\n  <xsl:variable name=\"show_explanation_default\" select=\"0\" />\n  <!-- The characters within the Webdings font that show the triangles -->\n  <xsl:variable name=\"show_button_text\" select=\"'&#x25B6;'\" />\n  <xsl:variable name=\"hide_button_text\" select=\"'&#x25BD;'\" />\n  <!-- The suffix for names -->\n  <xsl:variable name=\"button_suffix\" select=\"'__button'\"/>\n  <xsl:variable name=\"body_suffix\" select=\"'__body'\"/>\n  <!-- For easy reference, the name of the button -->\n  <xsl:variable name=\"show_hide_all_button\" select=\"'show_hide_all_button'\"/>\n\n  <!-- The top-level element -->\n  <xsl:template match=\"GUIDE\">\n      <HTML>\n          <HEAD>\n              <TITLE><xsl:value-of select=\"@title\"/></TITLE>\n              <META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>\n              <LINK HREF=\"/styleguide/favicon.ico\" type=\"image/x-icon\"\n                    rel=\"shortcut icon\"/>\n              <LINK HREF=\"styleguide.css\"\n                    type=\"text/css\" rel=\"stylesheet\"/>\n\n              <SCRIPT language=\"javascript\" type=\"text/javascript\">\n\n                function GetElementsByName(name) {\n                  // Workaround a bug on old versions of opera.\n                  if (document.getElementsByName) {\n                    return document.getElementsByName(name);\n                  } else {\n                    return [document.getElementById(name)];\n                  }\n                }\n\n                /**\n                 * @param {string} namePrefix The prefix of the body name.\n                 * @param {function(boolean): boolean} getVisibility Computes the new\n                 *     visibility state, given the current one.\n                 */\n                function ChangeVisibility(namePrefix, getVisibility) {\n                  var bodyName = namePrefix + '<xsl:value-of select=\"$body_suffix\"/>';\n                  var buttonName = namePrefix + '<xsl:value-of select=\"$button_suffix\"/>';\n                  var bodyElements = GetElementsByName(bodyName);\n                  var linkElement = GetElementsByName('link-' + buttonName)[0];\n                  if (bodyElements.length != 1) {\n                    throw Error('ShowHideByName() got the wrong number of bodyElements:  ' + \n                        bodyElements.length);\n                  } else {\n                    var bodyElement = bodyElements[0];\n                    var buttonElement = GetElementsByName(buttonName)[0];\n                    var isVisible = bodyElement.style.display != \"none\";\n                    if (getVisibility(isVisible)) {\n                      bodyElement.style.display = \"inline\";\n                      linkElement.style.display = \"block\";\n                      buttonElement.innerHTML = '<xsl:value-of select=\"$hide_button_text\"/>';\n                    } else {\n                      bodyElement.style.display = \"none\";\n                      linkElement.style.display = \"none\";\n                      buttonElement.innerHTML = '<xsl:value-of select=\"$show_button_text\"/>';\n                    }\n                  }\n                }\n\n                function ShowHideByName(namePrefix) {\n                  ChangeVisibility(namePrefix, function(old) { return !old; });\n                }\n\n                function ShowByName(namePrefix) {\n                  ChangeVisibility(namePrefix, function() { return true; });\n                }\n\n                function ShowHideAll() {\n                  var allButton = GetElementsByName(\"show_hide_all_button\")[0];\n                  if (allButton.innerHTML == '<xsl:value-of select=\"$hide_button_text\"/>') {\n                    allButton.innerHTML = '<xsl:value-of select=\"$show_button_text\"/>';\n                    SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \"none\", '<xsl:value-of select=\"$show_button_text\"/>');\n                  } else {\n                    allButton.innerHTML = '<xsl:value-of select=\"$hide_button_text\"/>';\n                    SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \"inline\", '<xsl:value-of select=\"$hide_button_text\"/>');\n                  }\n                }\n\n                // Recursively sets state of all children\n                // of a particular node.\n                function SetHiddenState(root, newState, newButton) {\n                  for (var i = 0; i != root.length; i++) {\n                    SetHiddenState(root[i].childNodes, newState, newButton);\n                    if (root[i].className == 'showhide_button')  {\n                      root[i].innerHTML = newButton;\n                    }\n                    if (root[i].className == 'stylepoint_body' ||\n                        root[i].className == 'link_button')  {\n                      root[i].style.display = newState;\n                    }\n                  }\n                }\n\n\n                function EndsWith(str, suffix) {\n                  var l = str.length - suffix.length;\n                  return l >= 0 &amp;&amp; str.indexOf(suffix, l) == l;\n                }\n\n                function RefreshVisibilityFromHashParam() {\n                  var hashRegexp = new RegExp('#([^&amp;#]*)$');\n                  var hashMatch = hashRegexp.exec(window.location.href);\n                  var anchor = hashMatch &amp;&amp; GetElementsByName(hashMatch[1])[0];\n                  var node = anchor;\n                  var suffix = '<xsl:value-of select=\"$body_suffix\"/>';\n                  while (node) {\n                    var id = node.id;\n                    var matched = id &amp;&amp; EndsWith(id, suffix);\n                    if (matched) {\n                      var len = id.length - suffix.length;\n                      ShowByName(id.substring(0, len));\n                      if (anchor.scrollIntoView) {\n                        anchor.scrollIntoView();\n                      }\n\n                      return;\n                    }\n                    node = node.parentNode;\n                  }\n                }\n\n                window.onhashchange = RefreshVisibilityFromHashParam;\n\n                window.onload = function() {\n                  // if the URL contains \"?showall=y\", expand the details of all children\n                  var showHideAllRegex = new RegExp(\"[\\\\?&amp;](showall)=([^&amp;#]*)\");\n                  var showHideAllValue = showHideAllRegex.exec(window.location.href);\n                  if (showHideAllValue != null) {\n                    if (showHideAllValue[2] == \"y\") {\n                      SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \n                          \"inline\", '<xsl:value-of select=\"$hide_button_text\"/>');\n                    } else {\n                      SetHiddenState(document.getElementsByTagName(\"body\")[0].childNodes, \n                          \"none\", '<xsl:value-of select=\"$show_button_text\"/>');\n                    }\n                  }\n                  var showOneRegex = new RegExp(\"[\\\\?&amp;](showone)=([^&amp;#]*)\");\n                  var showOneValue = showOneRegex.exec(window.location.href);\n                  if (showOneValue) {\n                    ShowHideByName(showOneValue[2]);\n                  }\n\n\n                  RefreshVisibilityFromHashParam();\n                }\n              </SCRIPT>\n          </HEAD>\n          <BODY>\n            <H1><xsl:value-of select=\"@title\"/></H1>\n              <xsl:apply-templates/>\n          </BODY>\n      </HTML>\n  </xsl:template>\n\n  <xsl:template match=\"OVERVIEW\">\n    <xsl:variable name=\"button_text\">\n      <xsl:choose>\n        <xsl:when test=\"$show_explanation_default\">\n          <xsl:value-of select=\"$hide_button_text\"/>\n        </xsl:when>\n        <xsl:otherwise>\n          <xsl:value-of select=\"$show_button_text\"/>\n        </xsl:otherwise>\n      </xsl:choose>\n    </xsl:variable>\n    <DIV style=\"margin-left: 50%; font-size: 75%;\">\n      <P>\n        Each style point has a summary for which additional information is available\n        by toggling the accompanying arrow button that looks this way:\n        <SPAN class=\"showhide_button\" style=\"margin-left: 0; float: none\">\n          <xsl:value-of select=\"$show_button_text\"/></SPAN>.\n        You may toggle all summaries with the big arrow button:\n      </P>\n      <DIV style=\" font-size: larger; margin-left: +2em;\">\n        <SPAN class=\"showhide_button\" style=\"font-size: 180%; float: none\">\n          <xsl:attribute name=\"onclick\"><xsl:value-of select=\"'javascript:ShowHideAll()'\"/></xsl:attribute>\n          <xsl:attribute name=\"name\"><xsl:value-of select=\"$show_hide_all_button\"/></xsl:attribute>\n          <xsl:attribute name=\"id\"><xsl:value-of select=\"$show_hide_all_button\"/></xsl:attribute>\n          <xsl:value-of select=\"$button_text\"/>\n        </SPAN>\n        Toggle all summaries\n      </DIV>\n    </DIV>\n    <xsl:call-template name=\"TOC\">\n      <xsl:with-param name=\"root\" select=\"..\"/>\n    </xsl:call-template>\n    <xsl:apply-templates/>\n  </xsl:template>\n\n  <xsl:template match=\"PARTING_WORDS\">\n    <H2>Parting Words</H2>\n    <xsl:apply-templates/>\n  </xsl:template>\n\n  <xsl:template match=\"CATEGORY\">\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <H2>\n        <xsl:variable name=\"category_name\">\n          <xsl:call-template name=\"anchorname\">\n            <xsl:with-param name=\"sectionname\" select=\"@title\"/>\n          </xsl:call-template>\n        </xsl:variable>\n        <xsl:attribute name=\"name\"><xsl:value-of select=\"$category_name\"/></xsl:attribute>\n        <xsl:attribute name=\"id\"><xsl:value-of select=\"$category_name\"/></xsl:attribute>\n        <xsl:value-of select=\"@title\"/>\n      </H2>\n      <xsl:apply-templates/>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"STYLEPOINT\">\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <xsl:variable name=\"stylepoint_name\">\n        <xsl:call-template name=\"anchorname\">\n          <xsl:with-param name=\"sectionname\" select=\"@title\"/>\n        </xsl:call-template>\n      </xsl:variable>\n      <xsl:variable name=\"button_text\">\n        <xsl:choose>\n          <xsl:when test=\"$show_explanation_default\">\n            <xsl:value-of select=\"$hide_button_text\"/>\n          </xsl:when>\n          <xsl:otherwise>\n            <xsl:value-of select=\"$show_button_text\"/>\n          </xsl:otherwise>\n        </xsl:choose>\n      </xsl:variable>\n      <H3>\n        <A>\n          <xsl:attribute name=\"name\"><xsl:value-of select=\"$stylepoint_name\"/></xsl:attribute>\n          <xsl:attribute name=\"id\"><xsl:value-of select=\"$stylepoint_name\"/></xsl:attribute>\n          <xsl:value-of select=\"@title\"/>\n        </A>\n      </H3>\n      <xsl:variable name=\"buttonName\">\n        <xsl:value-of select=\"$stylepoint_name\"/><xsl:value-of select=\"$button_suffix\"/>\n      </xsl:variable>\n      <xsl:variable name=\"onclick_definition\">\n        <xsl:text>javascript:ShowHideByName('</xsl:text>\n        <xsl:value-of select=\"$stylepoint_name\"/>\n        <xsl:text>')</xsl:text>\n      </xsl:variable>\n      <SPAN class=\"link_button\" id=\"link-{$buttonName}\" name=\"link-{$buttonName}\">\n        <A>\n          <xsl:attribute name=\"href\">?showone=<xsl:value-of select=\"$stylepoint_name\"/>#<xsl:value-of select=\"$stylepoint_name\"/></xsl:attribute>\n          link\n        </A>\n      </SPAN>\n      <SPAN class=\"showhide_button\">\n        <xsl:attribute name=\"onclick\"><xsl:value-of select=\"$onclick_definition\"/></xsl:attribute>\n        <xsl:attribute name=\"name\"><xsl:value-of select=\"$buttonName\"/></xsl:attribute>\n        <xsl:attribute name=\"id\"><xsl:value-of select=\"$buttonName\"/></xsl:attribute>\n        <xsl:value-of select=\"$button_text\"/>\n      </SPAN>\n      <xsl:apply-templates>\n        <xsl:with-param name=\"anchor_prefix\" select=\"$stylepoint_name\" />\n      </xsl:apply-templates>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"SUMMARY\">\n    <xsl:param name=\"anchor_prefix\" />\n    <DIV style=\"display:inline;\">\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <xsl:apply-templates/>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"BODY\">\n    <xsl:param name=\"anchor_prefix\" />\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <DIV class=\"stylepoint_body\">\n        <xsl:attribute name=\"name\"><xsl:value-of select=\"$anchor_prefix\"/><xsl:value-of select=\"$body_suffix\"/></xsl:attribute>\n        <xsl:attribute name=\"id\"><xsl:value-of select=\"$anchor_prefix\"/><xsl:value-of select=\"$body_suffix\"/></xsl:attribute>\n        <xsl:attribute name=\"style\">\n          <xsl:choose>\n            <xsl:when test=\"$show_explanation_default\">display: inline</xsl:when>\n            <xsl:otherwise>display: none</xsl:otherwise>\n          </xsl:choose>\n        </xsl:attribute>\n        <xsl:apply-templates/>\n      </DIV>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"DEFINITION\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <SPAN class=\"stylepoint_section\">Definition:  </SPAN>\n      <xsl:apply-templates/>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"PROS\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <SPAN class=\"stylepoint_section\">Pros:  </SPAN>\n      <xsl:apply-templates/>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"CONS\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <SPAN class=\"stylepoint_section\">Cons: </SPAN>\n      <xsl:apply-templates/>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"DECISION\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <SPAN class=\"stylepoint_section\">Decision:  </SPAN>\n      <xsl:apply-templates/>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"TODO\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <DIV style=\"font-size: 150%;\">TODO:\n        <xsl:apply-templates/>\n      </DIV>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"SUBSECTION\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <SPAN class=\"stylepoint_subsection\"><xsl:value-of select=\"@title\"/>  </SPAN>\n      <xsl:apply-templates/>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"SUBSUBSECTION\">\n    <P>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <SPAN class=\"stylepoint_subsubsection\"><xsl:value-of select=\"@title\"/>  </SPAN>\n      <xsl:apply-templates/>\n    </P>\n  </xsl:template>\n\n  <xsl:template match=\"CODE_SNIPPET\">\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <PRE><xsl:call-template name=\"print_without_leading_chars\">\n           <xsl:with-param name=\"text\" select=\".\"/>\n           <xsl:with-param name=\"strip\" select=\"1\"/>\n           <xsl:with-param name=\"is_firstline\" select=\"1\"/>\n           <xsl:with-param name=\"trim_count\">\n             <xsl:call-template name=\"num_leading_spaces\">\n               <xsl:with-param name=\"text\" select=\".\"/>\n               <xsl:with-param name=\"max_so_far\" select=\"1000\"/>\n             </xsl:call-template>\n           </xsl:with-param>\n         </xsl:call-template></PRE>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"BAD_CODE_SNIPPET\">\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <PRE class=\"badcode\"><xsl:call-template name=\"print_without_leading_chars\">\n           <xsl:with-param name=\"text\" select=\".\"/>\n           <xsl:with-param name=\"strip\" select=\"1\"/>\n           <xsl:with-param name=\"is_firstline\" select=\"1\"/>\n           <xsl:with-param name=\"trim_count\">\n             <xsl:call-template name=\"num_leading_spaces\">\n               <xsl:with-param name=\"text\" select=\".\"/>\n               <xsl:with-param name=\"max_so_far\" select=\"1000\"/>\n             </xsl:call-template>\n           </xsl:with-param>\n         </xsl:call-template></PRE>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"PY_CODE_SNIPPET\">\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <PRE><xsl:call-template name=\"print_python_code\">\n             <xsl:with-param name=\"text\" select=\".\"/>\n           </xsl:call-template></PRE>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"BAD_PY_CODE_SNIPPET\">\n    <DIV>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <PRE class=\"badcode\"><xsl:call-template name=\"print_python_code\">\n                             <xsl:with-param name=\"text\" select=\".\"/>\n                           </xsl:call-template></PRE>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template match=\"FUNCTION\">\n    <xsl:call-template name=\"print_function_name\">\n      <xsl:with-param name=\"text\" select=\".\"/>\n    </xsl:call-template>\n  </xsl:template>\n\n  <xsl:template match=\"SYNTAX\">\n    <I>\n      <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n      <xsl:apply-templates/>\n    </I>\n  </xsl:template>\n\n\n  <!-- This passes through any HTML elements that the\n    XML doc uses for minor formatting -->\n  <xsl:template match=\"a|address|blockquote|br|center|cite|code|dd|div|dl|dt|em|hr|i|img|li|ol|p|pre|span|table|td|th|tr|ul|var|A|ADDRESS|BLOCKQUOTE|BR|CENTER|CITE|CODE|DD|DIV|DL|DT|EM|HR|I|LI|OL|P|PRE|SPAN|TABLE|TD|TH|TR|UL|VAR\">\n      <xsl:element name=\"{local-name()}\">\n          <xsl:copy-of select=\"@*\"/>\n          <xsl:apply-templates/>\n      </xsl:element>\n  </xsl:template>\n\n    <!-- Builds the table of contents -->\n  <xsl:template name=\"TOC\">\n    <xsl:param name=\"root\"/>\n    <DIV class=\"toc\">\n      <DIV class=\"toc_title\">Table of Contents</DIV>\n      <TABLE>\n      <xsl:for-each select=\"$root/CATEGORY\">\n        <TR valign=\"top\">\n          <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n          <TD>\n          <DIV class=\"toc_category\">\n            <A>\n              <xsl:attribute name=\"href\">\n                <xsl:text>#</xsl:text>\n                <xsl:call-template name=\"anchorname\">\n                  <xsl:with-param name=\"sectionname\" select=\"@title\"/>\n                </xsl:call-template>\n              </xsl:attribute>\n              <xsl:value-of select=\"@title\"/>\n            </A>\n          </DIV>\n          </TD><TD>\n            <DIV class=\"toc_stylepoint\">\n              <xsl:for-each select=\"./STYLEPOINT\">\n                <SPAN style=\"padding-right: 1em; white-space:nowrap;\">\n                  <xsl:attribute name=\"class\"><xsl:value-of select=\"@class\"/></xsl:attribute>\n                  <A>\n                    <xsl:attribute name=\"href\">\n                      <xsl:text>#</xsl:text>\n                      <xsl:call-template name=\"anchorname\">\n                        <xsl:with-param name=\"sectionname\" select=\"@title\"/>\n                      </xsl:call-template>\n                    </xsl:attribute>\n                    <xsl:value-of select=\"@title\"/>\n                  </A>\n                </SPAN>\n                <xsl:text> </xsl:text>\n              </xsl:for-each>\n            </DIV>\n          </TD>\n        </TR>\n      </xsl:for-each>\n      </TABLE>\n    </DIV>\n  </xsl:template>\n\n  <xsl:template name=\"TOC_one_stylepoint\">\n    <xsl:param name=\"stylepoint\"/>\n  </xsl:template>\n\n  <!-- Creates a standard anchor given any text.\n       Substitutes underscore for characters unsuitable for URLs  -->\n  <xsl:template name=\"anchorname\">\n    <xsl:param name=\"sectionname\"/>\n    <!-- strange quoting necessary to strip apostrophes -->\n    <xsl:variable name=\"bad_characters\" select=\"&quot; ()#'&quot;\"/>\n    <xsl:value-of select=\"translate($sectionname,$bad_characters,'_____')\"/>\n  </xsl:template>\n\n  <!-- Given text, evaluates to the number of leading spaces. -->\n  <!-- TODO(csilvers): deal well with leading tabs (treat as 8 spaces?) -->\n  <xsl:template name=\"num_leading_spaces_one_line\">\n    <xsl:param name=\"text\"/>\n    <xsl:param name=\"current_count\"/>\n    <xsl:choose>\n      <xsl:when test=\"starts-with($text, ' ')\">\n        <xsl:call-template name=\"num_leading_spaces_one_line\">\n          <xsl:with-param name=\"text\" select=\"substring($text, 2)\"/>\n          <xsl:with-param name=\"current_count\" select=\"$current_count + 1\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:value-of select=\"$current_count\"/>\n      </xsl:otherwise>\n    </xsl:choose>\n  </xsl:template>\n\n  <!-- Given a block of text, each line terminated by \\n, evaluates to\n       the indentation-level of that text; that is, the largest number\n       n such that every non-blank line starts with at least n spaces. -->\n  <xsl:template name=\"num_leading_spaces\">\n    <xsl:param name=\"text\"/>\n    <xsl:param name=\"max_so_far\"/>\n    <!-- TODO(csilvers): deal with case text doesn't end in a newline -->\n    <xsl:variable name=\"line\" select=\"substring-before($text, '&#xA;')\"/>\n    <xsl:variable name=\"rest\" select=\"substring-after($text, '&#xA;')\"/>\n    <xsl:variable name=\"num_spaces_this_line\">\n      <xsl:choose>\n        <xsl:when test=\"$line=''\">\n           <xsl:value-of select=\"$max_so_far\"/>\n        </xsl:when>\n        <xsl:otherwise>\n          <xsl:call-template name=\"num_leading_spaces_one_line\">\n            <xsl:with-param name=\"text\" select=\"$line\"/>\n            <xsl:with-param name=\"current_count\" select=\"0\"/>\n          </xsl:call-template>\n        </xsl:otherwise>\n      </xsl:choose>\n    </xsl:variable>\n    <xsl:variable name=\"new_max_so_far\">\n       <xsl:choose>\n         <xsl:when test=\"$num_spaces_this_line &lt; $max_so_far\">\n           <xsl:value-of select=\"$num_spaces_this_line\"/>\n         </xsl:when>\n         <xsl:otherwise>\n           <xsl:value-of select=\"$max_so_far\"/>\n         </xsl:otherwise>\n       </xsl:choose>\n    </xsl:variable>\n    <!-- now check if we're on the last line, and if not, recurse -->\n    <xsl:if test=\"$rest=''\">\n      <xsl:value-of select=\"$new_max_so_far\"/>\n    </xsl:if>\n    <xsl:if test=\"not($rest='')\">\n      <xsl:call-template name=\"num_leading_spaces\">\n        <xsl:with-param name=\"text\" select=\"$rest\"/>\n        <xsl:with-param name=\"max_so_far\" select=\"$new_max_so_far\"/>\n      </xsl:call-template>\n    </xsl:if>\n  </xsl:template>\n\n  <!-- Given text, determine the starting position of code.\n       This similar to num_leading_spaces_one_line but treats \"Yes:\" and \"No:\" \n       as spaces. Also, if there is no code on the first line, it searches \n       subsequent lines until a non-empty line is found.\n       Used to find the start of code in snippets like:\n       Yes: if(foo):\n       No : if(foo):\n       As well as:\n       Yes:\n         if (foo):\n  -->\n  <xsl:template name=\"code_start_index\">\n    <xsl:param name=\"text\"/>\n    <xsl:param name=\"current_count\"/>\n    <xsl:choose>\n      <xsl:when test=\"starts-with($text, ' ')\">\n        <xsl:call-template name=\"code_start_index\">\n          <xsl:with-param name=\"text\" select=\"substring($text, 2)\"/>\n          <xsl:with-param name=\"current_count\" select=\"$current_count + 1\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:when test=\"starts-with($text, 'Yes:')\">\n        <xsl:call-template name=\"code_start_index\">\n          <xsl:with-param name=\"text\" select=\"substring($text, 5)\"/>\n          <xsl:with-param name=\"current_count\" select=\"$current_count + 4\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:when test=\"starts-with($text, 'No:')\">\n        <xsl:call-template name=\"code_start_index\">\n          <xsl:with-param name=\"text\" select=\"substring($text, 4)\"/>\n          <xsl:with-param name=\"current_count\" select=\"$current_count + 3\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <!-- This is only reached if the first line is entirely whitespace or \n           contains nothing but \"Yes:\" or \"No:\"-->\n      <xsl:when test=\"starts-with($text, '&#xA;')\">\n        <xsl:call-template name=\"code_start_index\">\n          <xsl:with-param name=\"text\" select=\"substring($text, 2)\"/>\n          <xsl:with-param name=\"current_count\" select=\"0\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:value-of select=\"$current_count\"/>\n      </xsl:otherwise>\n    </xsl:choose>\n  </xsl:template>\n\n  <!-- Helper for ends_with_colon. Determine whether the given line is nothing\n       but spaces and python-style comments. -->\n  <xsl:template name=\"is_blank_or_comment\">\n    <xsl:param name=\"line\"/>\n    <xsl:choose>\n      <xsl:when test=\"$line = ''\">\n        <xsl:value-of select=\"1\"/>\n      </xsl:when>\n      <xsl:when test=\"starts-with($line, '&#xA;')\">\n        <xsl:value-of select=\"1\"/>\n      </xsl:when>\n      <xsl:when test=\"starts-with($line, '#')\">\n        <xsl:value-of select=\"1\"/>\n      </xsl:when>\n      <xsl:when test=\"starts-with($line, ' ')\">\n        <xsl:call-template name=\"is_blank_or_comment\">\n          <xsl:with-param name=\"line\" select=\"substring($line, 2)\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:value-of select=\"0\"/>\n      </xsl:otherwise>\n    </xsl:choose>\n  </xsl:template>\n\n  <!-- Determine whether the given line ends with a colon. Note that Python\n       style comments are ignored so the following lines return True:\n       - def foo():\n       - def foo():  # Bar\n       - if(foo):\n\n       But some code may confuse this function. For example the following are\n       also consider to \"end_with_colon\" even though they don't for Python\n       - foo(\":  #\")\n       - foo() # No need for :\n  -->\n  <xsl:template name=\"ends_with_colon\">\n    <xsl:param name=\"line\"/>\n    <xsl:param name=\"found_colon\"/>\n    <xsl:choose>\n      <xsl:when test=\"$line = ''\">\n        <xsl:value-of select=\"$found_colon\"/>\n      </xsl:when>\n      <xsl:when test=\"starts-with($line, '&#xA;')\">\n        <xsl:value-of select=\"$found_colon\"/>\n      </xsl:when>\n      <xsl:when test=\"starts-with($line, ' ')\">\n        <xsl:call-template name=\"ends_with_colon\">\n          <xsl:with-param name=\"line\" select=\"substring($line, 2)\"/>\n          <xsl:with-param name=\"found_colon\" select=\"$found_colon\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:when test=\"starts-with($line, ':')\">\n        <xsl:variable name=\"rest_is_comment\">\n          <xsl:call-template name=\"is_blank_or_comment\">\n            <xsl:with-param name=\"line\" select=\"substring($line, 2)\"/>\n          </xsl:call-template>\n        </xsl:variable>\n        <xsl:choose>\n          <xsl:when test=\"$rest_is_comment = '1'\">\n            <xsl:value-of select=\"1\"/>\n          </xsl:when>\n          <xsl:otherwise>\n            <xsl:call-template name=\"ends_with_colon\">\n              <xsl:with-param name=\"line\" select=\"substring($line, 2)\"/>\n              <xsl:with-param name=\"found_colon\" select=\"0\"/>\n            </xsl:call-template>\n          </xsl:otherwise>\n        </xsl:choose>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:call-template name=\"ends_with_colon\">\n          <xsl:with-param name=\"line\" select=\"substring($line, 2)\"/>\n          <xsl:with-param name=\"found_colon\" select=\"0\"/>\n        </xsl:call-template>\n      </xsl:otherwise>\n    </xsl:choose>\n  </xsl:template>\n\n  <!-- Prints one line of python code with proper indent and calls itself\n       recursively for the rest of the text.\n       This template uses \"a\", \"b\", \"c\" and \"d\" to refer to four key column\n       numbers. They are:\n       - a: the indentation common to all lines in a code snippet. This is\n            stripped out to allow for cleaner code in the xml.\n       - b: the indentation of the most out-dented line of code. This is\n            different from \"a\" when code is labelled with \"Yes:\" or \"No:\"\n       - c: the indentation of the current python block, in other words, the\n            indentation of the first line of this block, which is the\n            indentation of the last line we saw that ended with a colon.\n       - d: the \"total\" indentation of the line, ignoring possible \"Yes:\" or\n            \"No:\" text on the line.\n\n       For example, for the last line of the following code snippet, the\n       positions of a, b, c and d are indicated below:\n           Yes: def Foo():\n                  if bar():\n                    a += 1\n                    baz()\n           a    b c d\n\n       The algorithm is:\n       1) Split the text into first line and the rest. Note that the\n          substring-before function is supposed to handle the case where the\n          character is not present in the string but does not so we\n          automatically ignore the last line of the snippet which is always\n          empty (the closing snippet tag). This is consistent with the\n          behavior or print_without_leading_chars.\n       2) If the current is empty (only whitespace), print newline and call\n          itself recursively on the rest of the text with the rest of the\n          parameters unchanged.\n       3) Otherwise, measure \"d\"\n       4) Measure \"c\" by taking:\n          - the value of \"d\" if the previous line ended with a colon or the\n            current line is outdented compare to the previous line\n          - the indent of the previous line otherwise\n       5) Print line[a:c] (Note that we ignore line[0:a])\n       6) Print line[b:c] in an external span (in order to double the block\n          indent in external code).\n       7) Print line[c:<end>] with function names processed to produce both \n          internal and external names.\n       8) If there are more lines, recurse.\n  -->\n  <xsl:template name=\"print_python_line_recursively\">\n    <xsl:param name=\"text\"/>\n    <xsl:param name=\"a\"/>\n    <xsl:param name=\"b\"/>\n    <xsl:param name=\"previous_indent\"/>\n    <xsl:param name=\"previous_ends_with_colon\"/>\n    <xsl:param name=\"is_first_line\"/>\n    <xsl:variable name=\"line\" select=\"substring-before($text, '&#xA;')\"/>\n    <xsl:variable name=\"rest\" select=\"substring-after($text, '&#xA;')\"/>\n    <xsl:choose>\n      <xsl:when test=\"substring($line, $b) = '' and not($rest = '')\">\n        <xsl:if test=\"not($is_first_line = '1')\">\n          <xsl:text>&#xA;</xsl:text>\n        </xsl:if>\n        <xsl:call-template name=\"print_python_line_recursively\">\n          <xsl:with-param name=\"text\" select=\"$rest\"/>\n          <xsl:with-param name=\"a\" select=\"$a\"/>\n          <xsl:with-param name=\"b\" select=\"$b\"/>\n          <xsl:with-param name=\"previous_indent\" select=\"$previous_indent\"/>\n          <xsl:with-param name=\"previous_ends_with_colon\"\n                          select=\"$previous_ends_with_colon\"/>\n          <xsl:with-param name=\"is_first_line\" select=\"0\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:variable name=\"indent_after_b\">\n          <xsl:call-template name=\"num_leading_spaces_one_line\">\n            <xsl:with-param name=\"text\" select=\"substring($line, $b + 1)\"/>\n            <xsl:with-param name=\"current_count\" select=\"0\"/>\n          </xsl:call-template>\n        </xsl:variable>\n        <xsl:variable name=\"d\" select=\"$b + $indent_after_b\"/>\n        <xsl:variable name=\"c\">\n           <xsl:choose>\n             <xsl:when test=\"$previous_ends_with_colon = '1' or\n                             $previous_indent > $d\">\n               <xsl:value-of select=\"$d\"/>\n             </xsl:when>\n             <xsl:otherwise>\n               <xsl:value-of select=\"$previous_indent\"/>\n             </xsl:otherwise>\n           </xsl:choose>\n        </xsl:variable>\n\n        <xsl:value-of select=\"substring($line, $a + 1, $c - $a)\"/>\n        <span class=\"external\">\n           <xsl:value-of select=\"substring($line, $b + 1, $c - $b)\"/>\n        </span>\n        <xsl:call-template name=\"munge_function_names_in_text\">\n          <xsl:with-param name=\"stripped_line\"\n             select=\"substring($line, $c + 1)\"/>\n        </xsl:call-template>\n        <xsl:if test=\"not(substring($rest, $a) = '')\">\n          <xsl:text>&#xA;</xsl:text>\n          <xsl:call-template name=\"print_python_line_recursively\">\n            <xsl:with-param name=\"text\" select=\"$rest\"/>\n            <xsl:with-param name=\"a\" select=\"$a\"/>\n            <xsl:with-param name=\"b\" select=\"$b\"/>\n            <xsl:with-param name=\"previous_indent\" select=\"$c\"/>\n            <xsl:with-param name=\"previous_ends_with_colon\">\n              <xsl:call-template name=\"ends_with_colon\">\n                <xsl:with-param name=\"line\" select=\"$line\"/>\n                <xsl:with-param name=\"found_colon\" select=\"0\"/>\n              </xsl:call-template>\n            </xsl:with-param>\n            <xsl:with-param name=\"is_first_line\" select=\"0\"/>\n          </xsl:call-template>\n        </xsl:if>\n      </xsl:otherwise>\n    </xsl:choose>\n  </xsl:template>\n\n  <!-- Print python code with internal and external styles.\n       In order to conform with PEP-8 externally, we identify 2-space indents\n       and an external-only 4-space indent.\n       Function names that are marked with $$FunctionName/$$ have an external\n       lower_with_underscore version added. -->\n  <xsl:template name=\"print_python_code\">\n    <xsl:param name=\"text\"/>\n\n    <xsl:variable name=\"a\">\n       <xsl:call-template name=\"num_leading_spaces\">\n         <xsl:with-param name=\"text\" select=\".\"/>\n         <xsl:with-param name=\"max_so_far\" select=\"1000\"/>\n       </xsl:call-template>\n    </xsl:variable>\n\n    <xsl:variable name=\"b\">\n      <xsl:call-template name=\"code_start_index\">\n        <xsl:with-param name=\"text\" select=\"$text\"/>\n        <xsl:with-param name=\"current_count\" select=\"0\"/>\n      </xsl:call-template>\n    </xsl:variable>\n\n    <xsl:call-template name=\"print_python_line_recursively\">\n      <xsl:with-param name=\"text\" select=\"$text\"/>\n      <xsl:with-param name=\"a\" select=\"$a\"/>\n      <xsl:with-param name=\"b\" select=\"$b\"/>\n      <xsl:with-param name=\"previous_indent\" select=\"$b\"/>\n      <xsl:with-param name=\"previous_ends_with_colon\" select=\"0\"/>\n      <xsl:with-param name=\"is_first_line\" select=\"1\"/> \n    </xsl:call-template>\n  </xsl:template>\n\n  <!-- Given a block of text, each line terminated by \\n, and a number n,\n       emits the text with the first n characters of each line\n       deleted.  If strip==1, then we omit blank lines at the beginning\n       and end of the text (but not the middle!) -->\n  <!-- TODO(csilvers): deal well with leading tabs (treat as 8 spaces?) -->\n  <xsl:template name=\"print_without_leading_chars\">\n    <xsl:param name=\"text\"/>\n    <xsl:param name=\"trim_count\"/>\n    <xsl:param name=\"strip\"/>\n    <xsl:param name=\"is_firstline\"/>\n    <!-- TODO(csilvers): deal with case text doesn't end in a newline -->\n    <xsl:variable name=\"line\" select=\"substring-before($text, '&#xA;')\"/>\n    <xsl:variable name=\"rest\" select=\"substring-after($text, '&#xA;')\"/>\n    <xsl:variable name=\"stripped_line\" select=\"substring($line, $trim_count+1)\"/>\n    <xsl:choose>\n      <!-- $line (or $rest) is considered empty if we'd trim the entire line -->\n      <xsl:when test=\"($strip = '1') and ($is_firstline = '1') and\n                      (string-length($line) &lt;= $trim_count)\">\n      </xsl:when>\n      <xsl:when test=\"($strip = '1') and\n                      (string-length($rest) &lt;= $trim_count)\">\n        <xsl:value-of select=\"$stripped_line\"/>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:value-of select=\"$stripped_line\"/>\n        <xsl:text>&#xA;</xsl:text>\n      </xsl:otherwise>\n    </xsl:choose>\n    <xsl:if test=\"not($rest='')\">\n      <xsl:call-template name=\"print_without_leading_chars\">\n        <xsl:with-param name=\"text\" select=\"$rest\"/>\n        <xsl:with-param name=\"trim_count\" select=\"$trim_count\"/>\n        <xsl:with-param name=\"strip\" select=\"$strip\"/>\n        <xsl:with-param name=\"is_firstline\" select=\"0\"/>\n      </xsl:call-template>\n    </xsl:if>\n  </xsl:template>\n\n  <!-- Given a line of code, find function names that are marked with $$ /$$ and\n       print out the line with the internal and external versions of the\n       function names.-->\n  <xsl:template name=\"munge_function_names_in_text\">\n    <xsl:param name=\"stripped_line\"/>\n    <xsl:choose>\n      <xsl:when test=\"contains($stripped_line, '$$')\">\n        <xsl:value-of select=\"substring-before($stripped_line, '$$')\"/>\n        <xsl:call-template name=\"print_function_name\">\n          <xsl:with-param name=\"text\" select=\"substring-after(substring-before($stripped_line, '/$$'), '$$')\"/>\n        </xsl:call-template>\n        <xsl:call-template name=\"munge_function_names_in_text\">\n          <xsl:with-param name=\"stripped_line\" select=\"substring-after($stripped_line, '/$$')\"/>\n        </xsl:call-template>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:value-of select=\"$stripped_line\"/>\n     </xsl:otherwise>\n   </xsl:choose>\n  </xsl:template>\n\n  <!-- Given a function name, print out both the internal and external version\n       of the function name in their respective spans.-->\n  <xsl:template name=\"print_function_name\">\n    <xsl:param name=\"text\"/>\n      <xsl:call-template name=\"convert_camel_case_to_lowercase_with_under\">\n        <xsl:with-param name=\"text\" select=\"$text\"/>\n      </xsl:call-template>\n  </xsl:template>\n\n  <!-- Given a single word of text convert it from CamelCase to\n       lower_with_under.\n       This means replacing each uppercase character with _ followed by the\n       lowercase version except for the first character which is replaced \n       without adding the _.-->\n  <xsl:template name=\"convert_camel_case_to_lowercase_with_under\">\n    <xsl:param name=\"text\"/>\n    <xsl:param name=\"is_recursive_call\"/>\n    <xsl:variable name=\"first_char\" select=\"substring($text, 1, 1)\"/>\n    <xsl:variable name=\"rest\" select=\"substring($text, 2)\"/>\n    <xsl:choose>\n      <xsl:when test=\"contains('ABCDEFGHIJKLMNOPQRSTUVWXYZ', $first_char)\">\n        <xsl:if test=\"$is_recursive_call='1'\">\n           <xsl:text>_</xsl:text>\n        </xsl:if>\n        <xsl:value-of select=\"translate($first_char, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')\"/>\n      </xsl:when>\n      <xsl:otherwise>\n        <xsl:value-of select=\"$first_char\" />\n      </xsl:otherwise>\n    </xsl:choose>\n    <xsl:if test=\"not($rest='')\">\n      <xsl:call-template name=\"convert_camel_case_to_lowercase_with_under\">\n        <xsl:with-param name=\"text\" select=\"$rest\"/>\n        <xsl:with-param name=\"is_recursive_call\" select=\"1\"/>\n      </xsl:call-template>\n    </xsl:if>\n  </xsl:template>\n</xsl:stylesheet>\n\n"
  },
  {
    "path": "tsguide.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Google TypeScript Style Guide</title>\n<link rel=\"stylesheet\" href=\"javaguide.css\">\n<script src=\"include/styleguide.js\"></script>\n<link rel=\"shortcut icon\" href=\"/styleguide/favicon.ico\">\n<script src=\"include/jsguide.js\"></script>\n</head>\n<body onload=\"initStyleGuide();\">\n<div id=\"content\">\n<h1>Google TypeScript Style Guide</h1>\n\n\n<section>\n\n<p>This guide is based on the internal Google TypeScript style guide, but it has\nbeen slightly adjusted to remove Google-internal sections. Google's internal\nenvironment has different constraints on TypeScript than you might find outside\nof Google. The advice here is specifically useful for people authoring code they\nintend to import into Google, but otherwise may not apply in your external\nenvironment.</p>\n\n<p>There is no automatic deployment process for this version as it's pushed\non-demand by volunteers.</p>\n\n</section> \n\n<h2 id=\"introduction\" class=\"numbered\">Introduction</h2>\n\n \n\n<h3 id=\"terminology-notes\" class=\"numbered\">Terminology notes</h3>\n\n<p>This Style Guide uses <a href=\"https://tools.ietf.org/html/rfc2119\">RFC 2119</a>\nterminology when using the phrases <em>must</em>, <em>must not</em>, <em>should</em>, <em>should not</em>,\nand <em>may</em>. The terms <em>prefer</em> and <em>avoid</em> correspond to <em>should</em> and <em>should\nnot</em>, respectively. Imperative and declarative statements are prescriptive and\ncorrespond to <em>must</em>.</p>\n\n<h3 id=\"guide-notes\" class=\"numbered\">Guide notes</h3>\n\n<p>All examples given are <strong>non-normative</strong> and serve only to illustrate the\nnormative language of the style guide. That is, while the examples are in Google\nStyle, they may not illustrate the <em>only</em> stylish way to represent the code.\nOptional formatting choices made in examples must not be enforced as rules.</p>\n\n \n\n<h2 id=\"source-file-basics\" class=\"numbered\">Source file basics</h2>\n\n \n\n \n\n<p><a id=\"file-encoding\"></a></p>\n\n<h3 id=\"file-encoding-utf-8\" class=\"numbered\">File encoding: UTF-8</h3>\n\n<p>Source files are encoded in <strong>UTF-8</strong>.</p>\n\n<p><a id=\"special-characters\"></a></p>\n\n<h4 id=\"whitespace-characters\" class=\"numbered\">Whitespace characters</h4>\n\n<p>Aside from the line terminator sequence, the ASCII horizontal space character\n(0x20) is the only whitespace character that appears anywhere in a source file.\nThis implies that all other whitespace characters in string literals are\nescaped.</p>\n\n<h4 id=\"special-escape-sequences\" class=\"numbered\">Special escape sequences</h4>\n\n<p>For any character that has a special escape sequence (<code>\\'</code>, <code>\\\"</code>, <code>\\\\</code>, <code>\\b</code>,\n<code>\\f</code>, <code>\\n</code>, <code>\\r</code>, <code>\\t</code>, <code>\\v</code>), that sequence is used rather than the\ncorresponding numeric escape (e.g <code>\\x0a</code>, <code>\\u000a</code>, or <code>\\u{a}</code>). Legacy octal\nescapes are never used.</p>\n\n<h4 id=\"non-ascii-characters\" class=\"numbered\">Non-ASCII characters</h4>\n\n<p>For the remaining non-ASCII characters, use the actual Unicode character (e.g.\n<code>∞</code>). For non-printable characters, the equivalent hex or Unicode escapes (e.g.\n<code>\\u221e</code>) can be used along with an explanatory comment.</p>\n\n<pre><code class=\"language-ts good\">// Perfectly clear, even without a comment.\nconst units = 'μs';\n\n// Use escapes for non-printable characters.\nconst output = '\\ufeff' + content;  // byte order mark\n</code></pre>\n\n<pre><code class=\"language-ts bad\">// Hard to read and prone to mistakes, even with the comment.\nconst units = '\\u03bcs'; // Greek letter mu, 's'\n\n// The reader has no idea what this is.\nconst output = '\\ufeff' + content;\n</code></pre>\n\n \n\n \n\n \n\n \n\n \n\n \n\n<p><a id=\"modules\"></a>\n<a id=\"source-organization\"></a></p>\n\n<h2 id=\"source-file-structure\" class=\"numbered\">Source file structure</h2>\n\n<p>Files consist of the following, <strong>in order</strong>:</p>\n\n<ol>\n<li>Copyright information, if present</li>\n<li>JSDoc with <code>@fileoverview</code>, if present</li>\n<li>Imports, if present</li>\n<li>The file’s implementation</li>\n</ol>\n\n<p><strong>Exactly one blank line</strong> separates each section that is present.</p>\n\n \n\n<h3 id=\"file-copyright\" class=\"numbered\">Copyright information</h3>\n\n \n\n<p>If license or copyright information is necessary in a file, add it in a JSDoc at\nthe top of the file. </p>\n\n<p><a id=\"file-fileoverview\"></a>\n<a id=\"jsdoc-top-file-level-comments\"></a></p>\n\n<h3 id=\"fileoverview\" class=\"numbered\"><code>@fileoverview</code> JSDoc</h3>\n\n<p>A file may have a top-level <code>@fileoverview</code> JSDoc. If present, it may provide a\ndescription of the file's content, its uses, or information about its\ndependencies. Wrapped lines are not indented.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-ts good\">/**\n * @fileoverview Description of file. Lorem ipsum dolor sit amet, consectetur\n * adipiscing elit, sed do eiusmod tempor incididunt.\n */\n</code></pre>\n\n \n\n<h3 id=\"imports\" class=\"numbered\">Imports</h3>\n\n<p>There are four variants of import statements in ES6 and TypeScript:</p>\n\n \n\n<section>\n\n<table>\n<thead>\n<tr>\n<th>Import type</th>\n<th>Example</th>\n<th>Use for</th>\n</tr>\n</thead>\n\n<tbody>\n<tr>\n<td>module[<sup>module_import]</sup>\n</td>\n<td><code>import * as foo from\n'...';</code></td>\n<td>TypeScript imports\n</td>\n</tr>\n<tr>\n<td>named[<sup>destructuring_import]</sup>\n</td>\n<td><code>import {SomeThing}\nfrom '...';</code></td>\n<td>TypeScript imports\n</td>\n</tr>\n<tr>\n<td>default\n\n</td>\n<td><code>import SomeThing\nfrom '...';</code>\n</td>\n<td>Only for other\nexternal code that\nrequires them</td>\n</tr>\n<tr>\n<td>side-effect\n\n\n\n</td>\n<td><code>import '...';</code>\n\n\n\n</td>\n<td>Only to import\nlibraries for their\nside-effects on load\n(such as custom\nelements)</td>\n</tr>\n</tbody>\n</table>\n\n<pre><code class=\"language-ts good\">// Good: choose between two options as appropriate (see below).\nimport * as ng from '@angular/core';\nimport {Foo} from './foo';\n\n// Only when needed: default imports.\nimport Button from 'Button';\n\n// Sometimes needed to import libraries for their side effects:\nimport 'jasmine';\nimport '@polymer/paper-button';\n</code></pre>\n\n</section> \n\n<h4 id=\"import-paths\" class=\"numbered\">Import paths</h4>\n\n<p>TypeScript code <em>must</em> use paths to import other TypeScript code. Paths <em>may</em> be\nrelative, i.e. starting with <code>.</code> or <code>..</code>,\n or rooted at the base directory, e.g.\n<code>root/path/to/file</code>.</p>\n\n<p>Code <em>should</em> use relative imports (<code>./foo</code>) rather than absolute imports\n<code>path/to/foo</code> when referring to files within the same (logical) project as this\nallows to move the project around without introducing changes in these imports.</p>\n\n<p>Consider limiting the number of parent steps (<code>../../../</code>) as those can make\nmodule and path structures hard to understand.</p>\n\n<pre><code class=\"language-ts good\">import {Symbol1} from 'path/from/root';\nimport {Symbol2} from '../parent/file';\nimport {Symbol3} from './sibling';\n</code></pre>\n\n \n\n<p><a id=\"module-versus-destructuring-import\"></a></p>\n\n<h4 id=\"namespace-versus-named-imports\" class=\"numbered\">Namespace versus named imports</h4>\n\n<p>Both namespace and named imports can be used.</p>\n\n<p>Prefer named imports for symbols used frequently in a file or for symbols that\nhave clear names, for example Jasmine's <code>describe</code> and <code>it</code>. Named imports can\nbe aliased to clearer names as needed with <code>as</code>.</p>\n\n<p>Prefer namespace imports when using many different symbols from large APIs. A\nnamespace import, despite using the <code>*</code> character, is not comparable to a\n<q>wildcard</q> import as seen in other languages. Instead, namespace imports give a\nname to all the exports of a module, and each exported symbol from the module\nbecomes a property on the module name. Namespace imports can aid readability for\nexported symbols that have common names like <code>Model</code> or <code>Controller</code> without the\nneed to declare aliases.</p>\n\n<pre><code class=\"language-ts bad\">// Bad: overlong import statement of needlessly namespaced names.\nimport {Item as TableviewItem, Header as TableviewHeader, Row as TableviewRow,\n  Model as TableviewModel, Renderer as TableviewRenderer} from './tableview';\n\nlet item: TableviewItem|undefined;\n</code></pre>\n\n<pre><code class=\"language-ts good\">// Better: use the module for namespacing.\nimport * as tableview from './tableview';\n\nlet item: tableview.Item|undefined;\n</code></pre>\n\n<pre><code class=\"language-ts bad\">import * as testing from './testing';\n\n// Bad: The module name does not improve readability.\ntesting.describe('foo', () =&gt; {\n  testing.it('bar', () =&gt; {\n    testing.expect(null).toBeNull();\n    testing.expect(undefined).toBeUndefined();\n  });\n});\n</code></pre>\n\n<pre><code class=\"language-ts good\">// Better: give local names for these common functions.\nimport {describe, it, expect} from './testing';\n\ndescribe('foo', () =&gt; {\n  it('bar', () =&gt; {\n    expect(null).toBeNull();\n    expect(undefined).toBeUndefined();\n  });\n});\n</code></pre>\n\n<h5 id=\"jspb-import-by-path\" class=\"numbered\">Special case: Apps JSPB protos</h5>\n\n<p>Apps JSPB protos must use named imports, even when it leads to long import\nlines.</p>\n\n<p>This rule exists to aid in build performance and dead code elimination since\noften <code>.proto</code> files contain many <code>message</code>s that are not all needed together.\nBy leveraging destructured imports the build system can create finer grained\ndependencies on Apps JSPB messages while preserving the ergonomics of path based\nimports.</p>\n\n<pre><code class=\"language-ts good\">// Good: import the exact set of symbols you need from the proto file.\nimport {Foo, Bar} from './foo.proto';\n\nfunction copyFooBar(foo: Foo, bar: Bar) {...}\n</code></pre>\n\n \n\n<h4 id=\"renaming-imports\" class=\"numbered\">Renaming imports</h4>\n\n<p>Code <em>should</em> fix name collisions by using a namespace import or renaming the\nexports themselves. Code <em>may</em> rename imports (<code>import {SomeThing as\nSomeOtherThing}</code>) if needed.</p>\n\n<p>Three examples where renaming can be helpful:</p>\n\n<ol>\n<li>If it's necessary to avoid collisions with other imported symbols.</li>\n<li>If the imported symbol name is generated.</li>\n<li>If importing symbols whose names are unclear by themselves, renaming can\nimprove code clarity. For example, when using RxJS the <code>from</code> function might\nbe more readable when renamed to <code>observableFrom</code>.</li>\n</ol>\n\n \n\n \n\n \n\n<h3 id=\"exports\" class=\"numbered\">Exports</h3>\n\n<p>Use named exports in all code:</p>\n\n<pre><code class=\"language-ts good\">// Use named exports:\nexport class Foo { ... }\n</code></pre>\n\n<p>Do not use default exports. This ensures that all imports follow a uniform\npattern.</p>\n\n<pre><code class=\"language-ts bad\">// Do not use default exports:\nexport default class Foo { ... } // BAD!\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>Default exports provide no canonical name, which makes central maintenance\ndifficult with relatively little benefit to code owners, including potentially\ndecreased readability:</p>\n\n<pre><code class=\"language-ts bad\">import Foo from './bar';  // Legal.\nimport Bar from './bar';  // Also legal.\n</code></pre>\n\n<p>Named exports have the benefit of erroring when import statements try to import\nsomething that hasn't been declared. In <code>foo.ts</code>:</p>\n\n<pre><code class=\"language-ts bad\">const foo = 'blah';\nexport default foo;\n</code></pre>\n\n<p>And in <code>bar.ts</code>:</p>\n\n<pre><code class=\"language-ts bad\">import {fizz} from './foo';\n</code></pre>\n\n<p>Results in <code>error TS2614: Module '\"./foo\"' has no exported member 'fizz'.</code> While\n<code>bar.ts</code>:</p>\n\n<pre><code class=\"language-ts bad\">import fizz from './foo';\n</code></pre>\n\n<p>Results in <code>fizz === foo</code>, which is probably unexpected and difficult to debug.</p>\n\n<p>Additionally, default exports encourage people to put everything into one big\nobject to namespace it all together:</p>\n\n<pre><code class=\"language-ts bad\">export default class Foo {\n  static SOME_CONSTANT = ...\n  static someHelpfulFunction() { ... }\n  ...\n}\n</code></pre>\n\n<p>With the above pattern, we have file scope, which can be used as a namespace. We\nalso have a perhaps needless second scope (the class <code>Foo</code>) that can be\nambiguously used as both a type and a value in other files.</p>\n\n<p>Instead, prefer use of file scope for namespacing, as well as named exports:</p>\n\n<pre><code class=\"language-ts good\">export const SOME_CONSTANT = ...\nexport function someHelpfulFunction()\nexport class Foo {\n  // only class stuff here\n}\n</code></pre>\n\n</section> \n\n<h4 id=\"export-visibility\" class=\"numbered\">Export visibility</h4>\n\n<p>TypeScript does not support restricting the visibility for exported symbols.\nOnly export symbols that are used outside of the module. Generally minimize the\nexported API surface of modules.</p>\n\n \n\n<h4 id=\"mutable-exports\" class=\"numbered\">Mutable exports</h4>\n\n \n\n<p>Regardless of technical support, mutable exports can create hard to understand\nand debug code, in particular with re-exports across multiple modules. One way\nto paraphrase this style point is that <code>export let</code> is not allowed.</p>\n\n<section>\n\n<pre><code class=\"language-ts bad\">export let foo = 3;\n// In pure ES6, foo is mutable and importers will observe the value change after a second.\n// In TS, if foo is re-exported by a second file, importers will not see the value change.\nwindow.setTimeout(() =&gt; {\n  foo = 4;\n}, 1000 /* ms */);\n</code></pre>\n\n</section> \n\n<p>If one needs to support externally accessible and mutable bindings, they\n<em>should</em> instead use explicit getter functions.</p>\n\n<pre><code class=\"language-ts good\">let foo = 3;\nwindow.setTimeout(() =&gt; {\n  foo = 4;\n}, 1000 /* ms */);\n// Use an explicit getter to access the mutable export.\nexport function getFoo() { return foo; };\n</code></pre>\n\n<p>For the common pattern of conditionally exporting either of two values, first do\nthe conditional check, then the export. Make sure that all exports are final\nafter the module's body has executed.</p>\n\n<pre><code class=\"language-ts good\">function pickApi() {\n  if (useOtherApi()) return OtherApi;\n  return RegularApi;\n}\nexport const SomeApi = pickApi();\n</code></pre>\n\n<p><a id=\"static-containers\"></a></p>\n\n<h4 id=\"container-classes\" class=\"numbered\">Container classes</h4>\n\n<p>Do not create container classes with static methods or properties for the sake\nof namespacing.</p>\n\n<pre><code class=\"language-ts bad\">export class Container {\n  static FOO = 1;\n  static bar() { return 1; }\n}\n</code></pre>\n\n<p>Instead, export individual constants and functions:</p>\n\n<pre><code class=\"language-ts good\">export const FOO = 1;\nexport function bar() { return 1; }\n</code></pre>\n\n \n\n<h3 id=\"import-export-type\" class=\"numbered\">Import and export type</h3>\n\n<h4 id=\"import-type\" class=\"numbered\">Import type</h4>\n\n<p>You may use <code>import type {...}</code> when you use the imported symbol only as a type.\nUse regular imports for values:</p>\n\n<pre><code class=\"language-ts good\">import type {Foo} from './foo';\nimport {Bar} from './foo';\n\nimport {type Foo, Bar} from './foo';\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>The TypeScript compiler automatically handles the distinction and does not\ninsert runtime loads for type references. So why annotate type imports?</p>\n\n<p>The TypeScript compiler can run in 2 modes:</p>\n\n<ul>\n<li>In development mode, we typically want quick iteration loops. The compiler\ntranspiles to JavaScript without full type information. This is much faster,\nbut requires <code>import type</code> in certain cases.</li>\n<li>In production mode, we want correctness. The compiler type checks everything\nand ensures <code>import type</code> is used correctly.</li>\n</ul>\n\n<p>Note: If you need to force a runtime load for side effects, use <code>import '...';</code>.\nSee </p>\n\n</section> \n\n<h4 id=\"export-type\" class=\"numbered\">Export type</h4>\n\n<p>Use <code>export type</code> when re-exporting a type, e.g.:</p>\n\n<pre><code class=\"language-ts good\">export type {AnInterface} from './foo';\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p><code>export type</code> is useful to allow type re-exports in file-by-file transpilation.\nSee\n<a href=\"https://www.typescriptlang.org/tsconfig#exports-of-non-value-identifiers\"><code>isolatedModules</code> docs</a>.</p>\n\n<p><code>export type</code> might also seem useful to avoid ever exporting a value symbol for\nan API. However it does not give guarantees, either: downstream code might still\nimport an API through a different path. A better way to split &amp; guarantee type\nvs value usages of an API is to actually split the symbols into e.g.\n<code>UserService</code> and <code>AjaxUserService</code>. This is less error prone and also better\ncommunicates intent.</p>\n\n</section> \n\n<p><a id=\"namespaces-vs-modules\"></a></p>\n\n<h4 id=\"use-modules-not-namespaces\" class=\"numbered\">Use modules not namespaces</h4>\n\n<p>TypeScript supports two methods to organize code: <em>namespaces</em> and <em>modules</em>,\nbut namespaces are disallowed.  That\nis, your code <em>must</em> refer to code in other files using imports and exports of\nthe form <code>import {foo} from 'bar';</code></p>\n\n<p>Your code <em>must not</em> use the <code>namespace Foo { ... }</code> construct. <code>namespace</code>s\n<em>may</em> only be used when required to interface with external, third party code.\nTo semantically namespace your code, use separate files.</p>\n\n \n\n<p>Code <em>must not</em> use <code>require</code> (as in <code>import x = require('...');</code>) for imports.\nUse ES6 module syntax.</p>\n\n<pre><code class=\"language-ts bad\">// Bad: do not use namespaces:\nnamespace Rocket {\n  function launch() { ... }\n}\n\n// Bad: do not use &lt;reference&gt;\n/// &lt;reference path=\"...\"/&gt;\n\n// Bad: do not use require()\nimport x = require('mydep');\n</code></pre>\n\n \n\n<blockquote>\n<p>NB: TypeScript <code>namespace</code>s used to be called internal modules and used to use\nthe <code>module</code> keyword in the form <code>module Foo { ... }</code>. Don't use that either.\nAlways use ES6 imports.</p>\n</blockquote>\n\n<p><a id=\"language-rules\"></a></p>\n\n<h2 id=\"language-features\" class=\"numbered\">Language features</h2>\n\n<p>This section delineates which features may or may not be used, and any\nadditional constraints on their use.</p>\n\n<p>Language features which are not discussed in this style guide <em>may</em> be used with\nno recommendations of their usage.</p>\n\n<p><a id=\"features-local-variable-declarations\"></a></p>\n\n<h3 id=\"local-variable-declarations\" class=\"numbered\">Local variable declarations</h3>\n\n<p><a id=\"variables\"></a>\n<a id=\"features-use-const-and-let\"></a></p>\n\n<h4 id=\"use-const-and-let\" class=\"numbered\">Use const and let</h4>\n\n<p>Always use <code>const</code> or <code>let</code> to declare variables. Use <code>const</code> by default, unless\na variable needs to be reassigned. Never use <code>var</code>.</p>\n\n<pre><code class=\"language-ts good\">const foo = otherValue;  // Use if \"foo\" never changes.\nlet bar = someValue;     // Use if \"bar\" is ever assigned into later on.\n</code></pre>\n\n<p><code>const</code> and <code>let</code> are block scoped, like variables in most other languages.\n<code>var</code> in JavaScript is function scoped, which can cause difficult to understand\nbugs. Don't use it.</p>\n\n<pre><code class=\"language-ts bad\">var foo = someValue;     // Don't use - var scoping is complex and causes bugs.\n</code></pre>\n\n<p>Variables <em>must not</em> be used before their declaration.</p>\n\n<p><a id=\"features-one-variable-per-declaration\"></a></p>\n\n<h4 id=\"one-variable-per-declaration\" class=\"numbered\">One variable per declaration</h4>\n\n<p>Every local variable declaration declares only one variable: declarations such\nas <code class=\"badcode\">let a = 1, b = 2;</code> are not used.</p>\n\n<p><a id=\"features-array-literals\"></a></p>\n\n<h3 id=\"array-literals\" class=\"numbered\">Array literals</h3>\n\n<p><a id=\"features-arrays-ctor\"></a></p>\n\n<h4 id=\"array-constructor\" class=\"numbered\">Do not use the <code>Array</code> constructor</h4>\n\n<p><em>Do not</em> use the <code>Array()</code> constructor, with or without <code>new</code>. It has confusing\nand contradictory usage:</p>\n\n\n\n<pre><code class=\"language-ts bad\">const a = new Array(2); // [undefined, undefined]\nconst b = new Array(2, 3); // [2, 3];\n</code></pre>\n\n\n\n<p>Instead, always use bracket notation to initialize arrays, or <code>from</code> to\ninitialize an <code>Array</code> with a certain size:</p>\n\n<pre><code class=\"language-ts good\">const a = [2];\nconst b = [2, 3];\n\n// Equivalent to Array(2):\nconst c = [];\nc.length = 2;\n\n// [0, 0, 0, 0, 0]\nArray.from&lt;number&gt;({length: 5}).fill(0);\n</code></pre>\n\n \n\n<p><a id=\"features-arrays-non-numeric-properties\"></a></p>\n\n<h4 id=\"do-not-define-properties-on-arrays\" class=\"numbered\">Do not define properties on arrays</h4>\n\n<p>Do not define or use non-numeric properties on an array (other than <code>length</code>).\nUse a <code>Map</code> (or <code>Object</code>) instead.</p>\n\n<p><a id=\"features-arrays-spread-operator\"></a></p>\n\n<h4 id=\"array-spread-syntax\" class=\"numbered\">Using spread syntax</h4>\n\n<p>Using spread syntax <code>[...foo];</code> is a convenient shorthand for shallow-copying or\nconcatenating iterables.</p>\n\n<pre><code class=\"language-ts good\">const foo = [\n  1,\n];\n\nconst foo2 = [\n  ...foo,\n  6,\n  7,\n];\n\nconst foo3 = [\n  5,\n  ...foo,\n];\n\nfoo2[1] === 6;\nfoo3[1] === 1;\n</code></pre>\n\n<p>When using spread syntax, the value being spread <em>must</em> match what is being\ncreated. When creating an array, only spread iterables. Primitives (including\n<code>null</code> and <code>undefined</code>) <em>must not</em> be spread.</p>\n\n<pre><code class=\"language-ts bad\">const foo = [7];\nconst bar = [5, ...(shouldUseFoo &amp;&amp; foo)]; // might be undefined\n\n// Creates {0: 'a', 1: 'b', 2: 'c'} but has no length\nconst fooStrings = ['a', 'b', 'c'];\nconst ids = {...fooStrings};\n</code></pre>\n\n<pre><code class=\"language-ts good\">const foo = shouldUseFoo ? [7] : [];\nconst bar = [5, ...foo];\nconst fooStrings = ['a', 'b', 'c'];\nconst ids = [...fooStrings, 'd', 'e'];\n</code></pre>\n\n<p><a id=\"features-arrays-destructuring\"></a></p>\n\n<h4 id=\"array-destructuring\" class=\"numbered\">Array destructuring</h4>\n\n<p>Array literals may be used on the left-hand side of an assignment to perform\ndestructuring (such as when unpacking multiple values from a single array or\niterable). A final <q>rest</q> element may be included (with no space between the\n<code>...</code> and the variable name). Elements should be omitted if they are unused.</p>\n\n<pre><code class=\"language-ts good\">const [a, b, c, ...rest] = generateResults();\nlet [, b,, d] = someArray;\n</code></pre>\n\n<p>Destructuring may also be used for function parameters. Always specify <code>[]</code> as\nthe default value if a destructured array parameter is optional, and provide\ndefault values on the left hand side:</p>\n\n<pre><code class=\"language-ts good\">function destructured([a = 4, b = 2] = []) { … }\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-ts bad\">function badDestructuring([a, b] = [4, 2]) { … }\n</code></pre>\n\n<p>Tip: For (un)packing multiple values into a function’s parameter or return,\nprefer object destructuring to array destructuring when possible, as it allows\nnaming the individual elements and specifying a different type for each.</p>\n\n \n\n<p><a id=\"features-object-literals\"></a></p>\n\n<h3 id=\"object-literals\" class=\"numbered\">Object literals</h3>\n\n<p><a id=\"features-objects-ctor\"></a></p>\n\n<h4 id=\"object-constructor\" class=\"numbered\">Do not use the <code>Object</code> constructor</h4>\n\n<p>The <code>Object</code> constructor is disallowed. Use an object literal (<code>{}</code> or <code>{a: 0,\nb: 1, c: 2}</code>) instead.</p>\n\n<h4 id=\"iterating-objects\" class=\"numbered\">Iterating objects</h4>\n\n<p>Iterating objects with <code>for (... in ...)</code> is error prone. It will include\nenumerable properties from the prototype chain.</p>\n\n<p>Do not use unfiltered <code>for (... in ...)</code> statements:</p>\n\n<pre><code class=\"language-ts bad\">for (const x in someObj) {\n  // x could come from some parent prototype!\n}\n</code></pre>\n\n<p>Either filter values explicitly with an <code>if</code> statement, or use <code>for (... of\nObject.keys(...))</code>.</p>\n\n<pre><code class=\"language-ts good\">for (const x in someObj) {\n  if (!someObj.hasOwnProperty(x)) continue;\n  // now x was definitely defined on someObj\n}\nfor (const x of Object.keys(someObj)) { // note: for _of_!\n  // now x was definitely defined on someObj\n}\nfor (const [key, value] of Object.entries(someObj)) { // note: for _of_!\n  // now key was definitely defined on someObj\n}\n</code></pre>\n\n<p><a id=\"using-the-spread-operator\"></a></p>\n\n<h4 id=\"object-spread-syntax\" class=\"numbered\">Using spread syntax</h4>\n\n<p>Using spread syntax <code>{...bar}</code> is a convenient shorthand for creating a shallow\ncopy of an object. When using spread syntax in object initialization, later\nvalues replace earlier values at the same key.</p>\n\n<pre><code class=\"language-ts good\">const foo = {\n  num: 1,\n};\n\nconst foo2 = {\n  ...foo,\n  num: 5,\n};\n\nconst foo3 = {\n  num: 5,\n  ...foo,\n}\n\nfoo2.num === 5;\nfoo3.num === 1;\n\n</code></pre>\n\n<p>When using spread syntax, the value being spread <em>must</em> match what is being\ncreated. That is, when creating an object, only objects may be spread; arrays\nand primitives (including <code>null</code> and <code>undefined</code>) <em>must not</em> be spread. Avoid\nspreading objects that have prototypes other than the Object prototype (e.g.\nclass definitions, class instances, functions) as the behavior is unintuitive\n(only enumerable non-prototype properties are shallow-copied).</p>\n\n<pre><code class=\"language-ts bad\">const foo = {num: 7};\nconst bar = {num: 5, ...(shouldUseFoo &amp;&amp; foo)}; // might be undefined\n\n// Creates {0: 'a', 1: 'b', 2: 'c'} but has no length\nconst fooStrings = ['a', 'b', 'c'];\nconst ids = {...fooStrings};\n</code></pre>\n\n<pre><code class=\"language-ts good\">const foo = shouldUseFoo ? {num: 7} : {};\nconst bar = {num: 5, ...foo};\n</code></pre>\n\n<p><a id=\"features-objects-computed-property-names\"></a></p>\n\n<h4 id=\"computed-property-names\" class=\"numbered\">Computed property names</h4>\n\n<p>Computed property names (e.g. <code>{['key' + foo()]: 42}</code>) are allowed, and are\nconsidered dict-style (quoted) keys (i.e., must not be mixed with non-quoted\nkeys) unless the computed property is a\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol\">symbol</a>\n(e.g. <code>[Symbol.iterator]</code>).</p>\n\n \n\n<p><a id=\"features-objects-destructuring\"></a></p>\n\n<h4 id=\"object-destructuring\" class=\"numbered\">Object destructuring</h4>\n\n<p>Object destructuring patterns may be used on the left-hand side of an assignment\nto perform destructuring and unpack multiple values from a single object.</p>\n\n<p>Destructured objects may also be used as function parameters, but should be kept\nas simple as possible: a single level of unquoted shorthand properties. Deeper\nlevels of nesting and computed properties may not be used in parameter\ndestructuring. Specify any default values in the left-hand-side of the\ndestructured parameter (<code>{str = 'some default'} = {}</code>, rather than\n<code class=\"badcode\">{str} = {str: 'some default'}</code>), and if a\ndestructured object is itself optional, it must default to <code>{}</code>.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-ts good\">interface Options {\n  /** The number of times to do something. */\n  num?: number;\n\n  /** A string to do stuff to. */\n  str?: string;\n}\n\nfunction destructured({num, str = 'default'}: Options = {}) {}\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-ts bad\">function nestedTooDeeply({x: {num, str}}: {x: Options}) {}\nfunction nontrivialDefault({num, str}: Options = {num: 42, str: 'default'}) {}\n</code></pre>\n\n \n\n \n\n<p><a id=\"formatting-class-literals\"></a>\n<a id=\"features-classes\"></a></p>\n\n<h3 id=\"classes\" class=\"numbered\">Classes</h3>\n\n<h4 id=\"class-declarations\" class=\"numbered\">Class declarations</h4>\n\n<p>Class declarations <em>must not</em> be terminated with semicolons:</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Foo {\n}; // Unnecessary semicolon\n</code></pre>\n\n<p>In contrast, statements that contain class expressions <em>must</em> be terminated with\na semicolon:</p>\n\n<pre><code class=\"language-ts good\">export const Baz = class extends Bar {\n  method(): number {\n    return this.x;\n  }\n}; // Semicolon here as this is a statement, not a declaration\n</code></pre>\n\n<pre><code class=\"language-ts bad\">exports const Baz = class extends Bar {\n  method(): number {\n    return this.x;\n  }\n}\n</code></pre>\n\n<p>It is neither encouraged nor discouraged to have blank lines separating class\ndeclaration braces from other class content:</p>\n\n<pre><code class=\"language-ts good\">// No spaces around braces - fine.\nclass Baz {\n  method(): number {\n    return this.x;\n  }\n}\n\n// A single space around both braces - also fine.\nclass Foo {\n\n  method(): number {\n    return this.x;\n  }\n\n}\n</code></pre>\n\n<h4 id=\"class-method-declarations\" class=\"numbered\">Class method declarations</h4>\n\n<p>Class method declarations <em>must not</em> use a semicolon to separate individual\nmethod declarations:</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n  doThing() {\n    console.log(\"A\");\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  doThing() {\n    console.log(\"A\");\n  }; // &lt;-- unnecessary\n}\n</code></pre>\n\n<p>Method declarations should be separated from surrounding code by a single blank\nline:</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n  doThing() {\n    console.log(\"A\");\n  }\n\n  getOtherThing(): number {\n    return 4;\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  doThing() {\n    console.log(\"A\");\n  }\n  getOtherThing(): number {\n    return 4;\n  }\n}\n</code></pre>\n\n<p><a id=\"features-classes-overriding-tostring\"></a></p>\n\n<h5 id=\"overriding-tostring\" class=\"numbered\">Overriding toString</h5>\n\n<p>The <code>toString</code> method may be overridden, but must always succeed and never have\nvisible side effects.</p>\n\n<p>Tip: Beware, in particular, of calling other methods from toString, since\nexceptional conditions could lead to infinite loops.</p>\n\n<p><a id=\"features-classes-static-methods\"></a></p>\n\n<h4 id=\"static-methods\" class=\"numbered\">Static methods</h4>\n\n<h5 id=\"avoid-private-static-methods\" class=\"numbered\">Avoid private static methods</h5>\n\n<p>Where it does not interfere with readability, prefer module-local functions over\nprivate static methods.</p>\n\n<h5 id=\"avoid-static-method-dynamic-dispatch\" class=\"numbered\">Do not rely on dynamic dispatch</h5>\n\n<p>Code <em>should not</em> rely on dynamic dispatch of static\nmethods. Static methods <em>should</em> only be called on the base class\nitself (which defines it directly). Static methods <em>should not</em> be called on\nvariables containing a dynamic instance that may be either the constructor or a\nsubclass constructor (and <em>must</em> be defined with <code>@nocollapse</code> if this is done),\nand <em>must not</em> be called directly on a subclass that doesn’t define the method\nitself.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-ts bad\">// Context for the examples below (this class is okay by itself)\nclass Base {\n  /** @nocollapse */ static foo() {}\n}\nclass Sub extends Base {}\n\n// Discouraged: don't call static methods dynamically\nfunction callFoo(cls: typeof Base) {\n  cls.foo();\n}\n\n// Disallowed: don't call static methods on subclasses that don't define it themselves\nSub.foo();\n\n// Disallowed: don't access this in static methods.\nclass MyClass {\n  static foo() {\n    return this.staticField;\n  }\n}\nMyClass.staticField = 1;\n</code></pre>\n\n<h5 id=\"static-this\" class=\"numbered\">Avoid static <code>this</code> references</h5>\n\n<p>Code <em>must not</em> use <code>this</code> in a static context.</p>\n\n<p>JavaScript allows accessing static fields through <code>this</code>. Different from other\nlanguages, static fields are also inherited.</p>\n\n<pre><code class=\"bad\">class ShoeStore {\n  static storage: Storage = ...;\n\n  static isAvailable(s: Shoe) {\n    // Bad: do not use `this` in a static method.\n    return this.storage.has(s.id);\n  }\n}\n\nclass EmptyShoeStore extends ShoeStore {\n  static storage: Storage = EMPTY_STORE;  // overrides storage from ShoeStore\n}\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>This code is generally surprising: authors might not expect that static fields\ncan be accessed through the this pointer, and might be surprised to find that\nthey can be overridden - this feature is not commonly used.</p>\n\n<p>This code also encourages an anti-pattern of having substantial static state,\nwhich causes problems with testability.</p>\n\n</section> \n\n<p><a id=\"disallowed-features-omitting-parents-with-new\"></a>\n<a id=\"features-classes-constructors\"></a></p>\n\n<h4 id=\"constructors\" class=\"numbered\">Constructors</h4>\n\n<p>Constructor calls <em>must</em> use parentheses, even when no arguments are passed:</p>\n\n<pre><code class=\"language-ts bad\">const x = new Foo;\n</code></pre>\n\n<pre><code class=\"language-ts good\">const x = new Foo();\n</code></pre>\n\n<p>Omitting parentheses can lead to subtle mistakes. These two lines are not\nequivalent:</p>\n\n<pre><code class=\"language-js good\">new Foo().Bar();\nnew Foo.Bar();\n</code></pre>\n\n<p>It is unnecessary to provide an empty constructor or one that simply delegates\ninto its parent class because ES2015 provides a default class constructor if one\nis not specified. However constructors with parameter properties, visibility\nmodifiers or parameter decorators <em>should not</em> be omitted even if the body of\nthe constructor is empty.</p>\n\n<pre><code class=\"language-ts bad\">class UnnecessaryConstructor {\n  constructor() {}\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class UnnecessaryConstructorOverride extends Base {\n    constructor(value: number) {\n      super(value);\n    }\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">class DefaultConstructor {\n}\n\nclass ParameterProperties {\n  constructor(private myService) {}\n}\n\nclass ParameterDecorators {\n  constructor(@SideEffectDecorator myService) {}\n}\n\nclass NoInstantiation {\n  private constructor() {}\n}\n</code></pre>\n\n<p>The constructor should be separated from surrounding code both above and below\nby a single blank line:</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n  myField = 10;\n\n  constructor(private readonly ctorParam) {}\n\n  doThing() {\n    console.log(ctorParam.getThing() + myField);\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  myField = 10;\n  constructor(private readonly ctorParam) {}\n  doThing() {\n    console.log(ctorParam.getThing() + myField);\n  }\n}\n</code></pre>\n\n<h4 id=\"class-members\" class=\"numbered\">Class members</h4>\n\n<h5 id=\"private-fields\" class=\"numbered\">No #private fields</h5>\n\n<p>Do not use private fields (also known as private identifiers):</p>\n\n<pre><code class=\"language-ts bad\">class Clazz {\n  #ident = 1;\n}\n</code></pre>\n\n<p>Instead, use TypeScript's visibility annotations:</p>\n\n<pre><code class=\"language-ts good\">class Clazz {\n  private ident = 1;\n}\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p> Private identifiers cause substantial emit size and\nperformance regressions when down-leveled by TypeScript, and are unsupported\nbefore ES2015. They can only be downleveled to ES2015, not lower. At the same\ntime, they do not offer substantial benefits when static type checking is used\nto enforce visibility.</p>\n\n</section> \n\n<h5 id=\"use-readonly\" class=\"numbered\">Use readonly</h5>\n\n<p>Mark properties that are never reassigned outside of the constructor with the\n<code>readonly</code> modifier (these need not be deeply immutable).</p>\n\n<h5 id=\"parameter-properties\" class=\"numbered\">Parameter properties</h5>\n\n<p>Rather than plumbing an obvious initializer through to a class member, use a\nTypeScript\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties\">parameter property</a>.</p>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  private readonly barService: BarService;\n\n  constructor(barService: BarService) {\n    this.barService = barService;\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">class Foo {\n  constructor(private readonly barService: BarService) {}\n}\n</code></pre>\n\n<p>If the parameter property needs documentation,\n<a href=\"#parameter-property-comments\">use an <code>@param</code> JSDoc tag</a>.</p>\n\n<h5 id=\"field-initializers\" class=\"numbered\">Field initializers</h5>\n\n<p>If a class member is not a parameter, initialize it where it's declared, which\nsometimes lets you drop the constructor entirely.</p>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  private readonly userList: string[];\n\n  constructor() {\n    this.userList = [];\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">class Foo {\n  private readonly userList: string[] = [];\n}\n</code></pre>\n\n<p>Tip: Properties should never be added to or removed from an instance after the\nconstructor is finished, since it significantly hinders VMs’ ability to optimize\nclasses' <q>shape</q>. Optional fields that may be filled in later should be\nexplicitly initialized to <code>undefined</code> to prevent later shape changes.</p>\n\n<h5 id=\"properties-used-outside-of-class-lexical-scope\" class=\"numbered\">Properties used outside of class lexical scope</h5>\n\n<p>Properties used from outside the lexical scope of their containing class, such\nas an Angular component's properties used from a template, <em>must not</em> use\n<code>private</code> visibility, as they are used outside of the lexical scope of their\ncontaining class.</p>\n\n<p>Use either <code>protected</code> or <code>public</code> as appropriate to the property in question.\nAngular and AngularJS template properties should use <code>protected</code>, but Polymer\nshould use <code>public</code>.</p>\n\n<p>TypeScript code <em>must not</em> use <code>obj['foo']</code> to bypass the visibility of a\nproperty.</p>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>When a property is <code>private</code>, you are declaring to both automated systems and\nhumans that the property accesses are scoped to the methods of the declaring\nclass, and they will rely on that. For example, a check for unused code will\nflag a private property that appears to be unused, even if some other file\nmanages to bypass the visibility restriction.</p>\n\n<p>Though it might appear that <code>obj['foo']</code> can bypass visibility in the TypeScript\ncompiler, this pattern can be broken by rearranging the build rules, and also\nviolates <a href=\"#optimization-compatibility\">optimization compatibility</a>.</p>\n\n</section> \n\n<p><a id=\"features-classes-getters-and-setters\"></a></p>\n\n<h5 id=\"classes-getters-and-setters\" class=\"numbered\">Getters and setters</h5>\n\n \n\n<p>Getters and setters, also known as accessors, for class members <em>may</em> be used.\nThe getter method <em>must</em> be a\n<a href=\"https://en.wikipedia.org/wiki/Pure_function\">pure function</a> (i.e., result is\nconsistent and has no side effects: getters <em>must not</em> change observable state).\nThey are also useful as a means of restricting the visibility of internal or\nverbose implementation details (shown below).</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n  constructor(private readonly someService: SomeService) {}\n\n  get someMember(): string {\n    return this.someService.someVariable;\n  }\n\n  set someMember(newValue: string) {\n    this.someService.someVariable = newValue;\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  nextId = 0;\n  get next() {\n    return this.nextId++; // Bad: getter changes observable state\n  }\n}\n</code></pre>\n\n<p>If an accessor is used to hide a class property, the hidden property <em>may</em> be\nprefixed or suffixed with any whole word, like <code>internal</code> or <code>wrapped</code>. When\nusing these private properties, access the value through the accessor whenever\npossible. At least one accessor for a property <em>must</em> be non-trivial: do not\ndefine <q>pass-through</q> accessors only for the purpose of hiding a property.\nInstead, make the property public (or consider making it <code>readonly</code> rather than\njust defining a getter with no setter).</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n  private wrappedBar = '';\n  get bar() {\n    return this.wrappedBar || 'bar';\n  }\n\n  set bar(wrapped: string) {\n    this.wrappedBar = wrapped.trim();\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Bar {\n  private barInternal = '';\n  // Neither of these accessors have logic, so just make bar public.\n  get bar() {\n    return this.barInternal;\n  }\n\n  set bar(value: string) {\n    this.barInternal = value;\n  }\n}\n</code></pre>\n\n<p>Getters and setters <em>must not</em> be defined using <code>Object.defineProperty</code>, since\nthis interferes with property renaming.</p>\n\n<p><a id=\"features-classes-computed-properties\"></a></p>\n\n<h5 id=\"class-computed-properties\" class=\"numbered\">Computed properties</h5>\n\n<p>Computed properties may only be used in classes when the property is a symbol.\nDict-style properties (that is, quoted or computed non-symbol keys) are not\nallowed (see\n<a href=\"#features-objects-mixing-keys\">rationale for not mixing key types</a>. A\n<code>[Symbol.iterator]</code> method should be defined for any classes that are logically\niterable. Beyond this, <code>Symbol</code> should be used sparingly.</p>\n\n<p>Tip: be careful of using any other built-in symbols (e.g.\n<code>Symbol.isConcatSpreadable</code>) as they are not polyfilled by the compiler and will\ntherefore not work in older browsers.</p>\n\n \n\n<h4 id=\"visibility\" class=\"numbered\">Visibility</h4>\n\n<p>Restricting visibility of properties, methods, and entire types helps with\nkeeping code decoupled.</p>\n\n<ul>\n<li>Limit symbol visibility as much as possible.</li>\n<li>Consider converting private methods to non-exported functions within the\nsame file but outside of any class, and moving private properties into a\nseparate, non-exported class.</li>\n<li>TypeScript symbols are public by default. Never use the <code>public</code> modifier\nexcept when declaring non-readonly public parameter properties (in\nconstructors).</li>\n</ul>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  public bar = new Bar();  // BAD: public modifier not needed\n\n  constructor(public readonly baz: Baz) {}  // BAD: readonly implies it's a property which defaults to public\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">class Foo {\n  bar = new Bar();  // GOOD: public modifier not needed\n\n  constructor(public baz: Baz) {}  // public modifier allowed\n}\n</code></pre>\n\n<p>See also <a href=\"#export-visibility\">export visibility</a>.</p>\n\n<h4 id=\"disallowed-class-patterns\" class=\"numbered\">Disallowed class patterns</h4>\n\n<p><a id=\"features-classes-prototypes\"></a></p>\n\n<h5 id=\"class-prototypes\" class=\"numbered\">Do not manipulate <code>prototype</code>s directly</h5>\n\n<p>The <code>class</code> keyword allows clearer and more readable class definitions than\ndefining <code>prototype</code> properties. Ordinary implementation code has no business\nmanipulating these objects. Mixins and modifying the prototypes of builtin\nobjects are explicitly forbidden.</p>\n\n<p><strong>Exception</strong>: Framework code (such as Polymer, or Angular) may need to use <code>prototype</code>s, and should not resort\nto even-worse workarounds to avoid doing so.</p>\n\n \n\n \n\n<p><a id=\"features-functions\"></a></p>\n\n<h3 id=\"functions\" class=\"numbered\">Functions</h3>\n\n<h4 id=\"terminology\" class=\"numbered\">Terminology</h4>\n\n<p>There are many different types of functions, with subtle distinctions between\nthem. This guide uses the following terminology, which aligns with\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions\">MDN</a>:</p>\n\n<ul>\n<li><q>function declaration</q>: a declaration (i.e. not an expression) using the\n<code>function</code> keyword</li>\n<li><q>function expression</q>: an expression, typically used in an assignment or\npassed as a parameter, using the <code>function</code> keyword</li>\n<li><q>arrow function</q>: an expression using the <code>=&gt;</code> syntax</li>\n<li><q>block body</q>: right hand side of an arrow function with braces</li>\n<li><q>concise body</q>: right hand side of an arrow function without braces</li>\n</ul>\n\n<p>Methods and classes/constructors are not covered in this section.</p>\n\n<h4 id=\"function-declarations\" class=\"numbered\">Prefer function declarations for named functions</h4>\n\n<p>Prefer function declarations over arrow functions or function expressions when\ndefining named functions.</p>\n\n<pre><code class=\"language-.ts good\">function foo() {\n  return 42;\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">const foo = () =&gt; 42;\n</code></pre>\n\n<p>Arrow functions <em>may</em> be used, for example, when an explicit type annotation is\nrequired.</p>\n\n<pre><code class=\"language-ts good\">interface SearchFunction {\n  (source: string, subString: string): boolean;\n}\n\nconst fooSearch: SearchFunction = (source, subString) =&gt; { ... };\n</code></pre>\n\n \n\n \n\n<p><a id=\"features-functions-nested-functions\"></a></p>\n\n<h4 id=\"nested-functions\" class=\"numbered\">Nested functions</h4>\n\n<p>Functions nested within other methods or functions <em>may</em> use function\ndeclarations or arrow functions, as appropriate. In method bodies in particular,\narrow functions are preferred because they have access to the outer <code>this</code>.</p>\n\n<p><a id=\"use-arrow-functions-in-expressions\"></a></p>\n\n<h4 id=\"function-expressions\" class=\"numbered\">Do not use function expressions</h4>\n\n<p>Do not use function expressions. Use arrow functions instead.</p>\n\n<pre><code class=\"language-ts good\">bar(() =&gt; { this.doSomething(); })\n</code></pre>\n\n<pre><code class=\"language-ts bad\">bar(function() { ... })\n</code></pre>\n\n<p><strong>Exception:</strong> Function expressions <em>may</em> be used <em>only if</em> code has to\ndynamically rebind <code>this</code> (but this is <a href=\"#rebinding-this\">discouraged</a>), or for\ngenerator functions (which do not have an arrow syntax).</p>\n\n<p><a id=\"features-functions-arrow-functions\"></a>\n<a id=\"expression-bodies-vs-block-bodies\"></a></p>\n\n<h4 id=\"arrow-function-bodies\" class=\"numbered\">Arrow function bodies</h4>\n\n<p>Use arrow functions with concise bodies (i.e. expressions) or block bodies as\nappropriate.</p>\n\n<pre><code class=\"language-ts good\">// Top level functions use function declarations.\nfunction someFunction() {\n  // Block bodies are fine:\n  const receipts = books.map((b: Book) =&gt; {\n    const receipt = payMoney(b.price);\n    recordTransaction(receipt);\n    return receipt;\n  });\n\n  // Concise bodies are fine, too, if the return value is used:\n  const longThings = myValues.filter(v =&gt; v.length &gt; 1000).map(v =&gt; String(v));\n\n  function payMoney(amount: number) {\n    // function declarations are fine, but must not access `this`.\n  }\n\n  // Nested arrow functions may be assigned to a const.\n  const computeTax = (amount: number) =&gt; amount * 0.12;\n}\n</code></pre>\n\n<p>Only use a concise body if the return value of the function is actually used.\nThe block body makes sure the return type is <code>void</code> then and prevents potential\nside effects.</p>\n\n<pre><code class=\"language-ts bad\">// BAD: use a block body if the return value of the function is not used.\nmyPromise.then(v =&gt; console.log(v));\n// BAD: this typechecks, but the return value still leaks.\nlet f: () =&gt; void;\nf = () =&gt; 1;\n</code></pre>\n\n<pre><code class=\"language-ts good\">// GOOD: return value is unused, use a block body.\nmyPromise.then(v =&gt; {\n  console.log(v);\n});\n// GOOD: code may use blocks for readability.\nconst transformed = [1, 2, 3].map(v =&gt; {\n  const intermediate = someComplicatedExpr(v);\n  const more = acrossManyLines(intermediate);\n  return worthWrapping(more);\n});\n// GOOD: explicit `void` ensures no leaked return value\nmyPromise.then(v =&gt; void console.log(v));\n</code></pre>\n\n<p>Tip: The <code>void</code> operator can be used to ensure an arrow function with an\nexpression body returns <code>undefined</code> when the result is unused.</p>\n\n<h4 id=\"rebinding-this\" class=\"numbered\">Rebinding <code>this</code></h4>\n\n<p>Function expressions and function declarations <em>must not</em> use <code>this</code> unless they\nspecifically exist to rebind the <code>this</code> pointer. Rebinding <code>this</code> can in most\ncases be avoided by using arrow functions or explicit parameters.</p>\n\n<pre><code class=\"language-ts bad\">function clickHandler() {\n  // Bad: what's `this` in this context?\n  this.textContent = 'Hello';\n}\n// Bad: the `this` pointer reference is implicitly set to document.body.\ndocument.body.onclick = clickHandler;\n</code></pre>\n\n<pre><code class=\"language-ts good\">// Good: explicitly reference the object from an arrow function.\ndocument.body.onclick = () =&gt; { document.body.textContent = 'hello'; };\n// Alternatively: take an explicit parameter\nconst setTextFn = (e: HTMLElement) =&gt; { e.textContent = 'hello'; };\ndocument.body.onclick = setTextFn.bind(null, document.body);\n</code></pre>\n\n<p>Prefer arrow functions over other approaches to binding <code>this</code>, such as\n<code>f.bind(this)</code>, <code>goog.bind(f, this)</code>, or <code>const self = this</code>.</p>\n\n<h4 id=\"functions-as-callbacks\" class=\"numbered\">Prefer passing arrow functions as callbacks</h4>\n\n<p>Callbacks can be invoked with unexpected arguments that can pass a type check\nbut still result in logical errors.</p>\n\n<p>Avoid passing a named callback to a higher-order function, unless you are sure\nof the stability of both functions' call signatures. Beware, in particular, of\nless-commonly-used optional parameters.</p>\n\n<pre><code class=\"language-ts bad\">// BAD: Arguments are not explicitly passed, leading to unintended behavior\n// when the optional `radix` argument gets the array indices 0, 1, and 2.\nconst numbers = ['11', '5', '10'].map(parseInt);\n// &gt; [11, NaN, 2];\n</code></pre>\n\n<p>Instead, prefer passing an arrow-function that explicitly forwards parameters to\nthe named callback.</p>\n\n<pre><code class=\"language-ts good\">// GOOD: Arguments are explicitly passed to the callback\nconst numbers = ['11', '5', '3'].map((n) =&gt; parseInt(n));\n// &gt; [11, 5, 3]\n\n// GOOD: Function is locally defined and is designed to be used as a callback\nfunction dayFilter(element: string|null|undefined) {\n  return element != null &amp;&amp; element.endsWith('day');\n}\n\nconst days = ['tuesday', undefined, 'juice', 'wednesday'].filter(dayFilter);\n</code></pre>\n\n<h4 id=\"arrow-functions-as-properties\" class=\"numbered\">Arrow functions as properties</h4>\n\n<p>Classes usually <em>should not</em> contain properties initialized to arrow functions.\nArrow function properties require the calling function to understand that the\ncallee's <code>this</code> is already bound, which increases confusion about what <code>this</code>\nis, and call sites and references using such handlers look broken (i.e. require\nnon-local knowledge to determine that they are correct). Code <em>should</em> always\nuse arrow functions to call instance methods (<code>const handler = (x) =&gt; {\nthis.listener(x); };</code>), and <em>should not</em> obtain or pass references to instance\nmethods (<del><code>const handler = this.listener; handler(x);</code></del>).</p>\n\n<blockquote>\n<p>Note: in some specific situations, e.g. when binding functions in a template,\narrow functions as properties are useful and create much more readable code.\nUse judgement with this rule. Also, see the\n<a href=\"#event-handlers\"><code>Event Handlers</code></a> section below.</p>\n</blockquote>\n\n<pre><code class=\"language-ts bad\">class DelayHandler {\n  constructor() {\n    // Problem: `this` is not preserved in the callback. `this` in the callback\n    // will not be an instance of DelayHandler.\n    setTimeout(this.patienceTracker, 5000);\n  }\n  private patienceTracker() {\n    this.waitedPatiently = true;\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">// Arrow functions usually should not be properties.\nclass DelayHandler {\n  constructor() {\n    // Bad: this code looks like it forgot to bind `this`.\n    setTimeout(this.patienceTracker, 5000);\n  }\n  private patienceTracker = () =&gt; {\n    this.waitedPatiently = true;\n  }\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">// Explicitly manage `this` at call time.\nclass DelayHandler {\n  constructor() {\n    // Use anonymous functions if possible.\n    setTimeout(() =&gt; {\n      this.patienceTracker();\n    }, 5000);\n  }\n  private patienceTracker() {\n    this.waitedPatiently = true;\n  }\n}\n</code></pre>\n\n<h4 id=\"event-handlers\" class=\"numbered\">Event handlers</h4>\n\n<p>Event handlers <em>may</em> use arrow functions when there is no need to uninstall the\nhandler (for example, if the event is emitted by the class itself). If the\nhandler requires uninstallation, arrow function properties are the right\napproach, because they automatically capture <code>this</code> and provide a stable\nreference to uninstall.</p>\n\n<pre><code class=\"language-ts good\">// Event handlers may be anonymous functions or arrow function properties.\nclass Component {\n  onAttached() {\n    // The event is emitted by this class, no need to uninstall.\n    this.addEventListener('click', () =&gt; {\n      this.listener();\n    });\n    // this.listener is a stable reference, we can uninstall it later.\n    window.addEventListener('onbeforeunload', this.listener);\n  }\n  onDetached() {\n    // The event is emitted by window. If we don't uninstall, this.listener will\n    // keep a reference to `this` because it's bound, causing a memory leak.\n    window.removeEventListener('onbeforeunload', this.listener);\n  }\n  // An arrow function stored in a property is bound to `this` automatically.\n  private listener = () =&gt; {\n    confirm('Do you want to exit the page?');\n  }\n}\n</code></pre>\n\n<p>Do not use <code>bind</code> in the expression that installs an event handler, because it\ncreates a temporary reference that can't be uninstalled.</p>\n\n<pre><code class=\"language-ts bad\">// Binding listeners creates a temporary reference that prevents uninstalling.\nclass Component {\n  onAttached() {\n    // This creates a temporary reference that we won't be able to uninstall\n    window.addEventListener('onbeforeunload', this.listener.bind(this));\n  }\n  onDetached() {\n    // This bind creates a different reference, so this line does nothing.\n    window.removeEventListener('onbeforeunload', this.listener.bind(this));\n  }\n  private listener() {\n    confirm('Do you want to exit the page?');\n  }\n}\n</code></pre>\n\n<p><a id=\"features-functions-default-parameters\"></a></p>\n\n<h4 id=\"parameter-initializers\" class=\"numbered\">Parameter initializers</h4>\n\n<p>Optional function parameters <em>may</em> be given a default initializer to use when\nthe argument is omitted. Initializers <em>must not</em> have any observable side\neffects. Initializers <em>should</em> be kept as simple as possible.</p>\n\n<pre><code class=\"language-ts good\">function process(name: string, extraContext: string[] = []) {}\nfunction activate(index = 0) {}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">// BAD: side effect of incrementing the counter\nlet globalCounter = 0;\nfunction newId(index = globalCounter++) {}\n\n// BAD: exposes shared mutable state, which can introduce unintended coupling\n// between function calls\nclass Foo {\n  private readonly defaultPaths: string[];\n  frobnicate(paths = defaultPaths) {}\n}\n</code></pre>\n\n<p>Use default parameters sparingly. Prefer\n<a href=\"#features-objects-destructuring\">destructuring</a> to create readable APIs when\nthere are more than a small handful of optional parameters that do not have a\nnatural order.</p>\n\n \n\n<p><a id=\"features-functions-rest-parameters\"></a>\n<a id=\"features-functions-spread-operator\"></a></p>\n\n<h4 id=\"rest-and-spread\" class=\"numbered\">Prefer rest and spread when appropriate</h4>\n\n<p>Use a <em>rest</em> parameter instead of accessing <code>arguments</code>. Never name a local\nvariable or parameter <code>arguments</code>, which confusingly shadows the built-in name.</p>\n\n<pre><code class=\"language-ts good\">function variadic(array: string[], ...numbers: number[]) {}\n</code></pre>\n\n \n\n<p>Use function spread syntax instead of <code>Function.prototype.apply</code>.</p>\n\n<p><a id=\"features-functions-generators\"></a></p>\n\n<h4 id=\"formatting-functions\" class=\"numbered\">Formatting functions</h4>\n\n<p>Blank lines at the start or end of the function body are not allowed.</p>\n\n<p>A single blank line <em>may</em> be used within function bodies sparingly to create\n<em>logical groupings</em> of statements.</p>\n\n<p>Generators should attach the <code>*</code> to the <code>function</code> and <code>yield</code> keywords, as in\n<code>function* foo()</code> and <code>yield* iter</code>, rather than <del><code>function *foo()</code></del> or\n<del><code>yield *iter</code></del>.</p>\n\n<p>Parentheses around the left-hand side of a single-argument arrow function are\nrecommended but not required.</p>\n\n<p>Do not put a space after the <code>...</code> in rest or spread syntax.</p>\n\n<pre><code class=\"language-ts good\">function myFunction(...elements: number[]) {}\nmyFunction(...array, ...iterable, ...generator());\n</code></pre>\n\n<h3 id=\"features-this\" class=\"numbered\">this</h3>\n\n<p>Only use <code>this</code> in class constructors and methods, functions that have an\nexplicit <code>this</code> type declared (e.g. <code>function func(this: ThisType, ...)</code>), or in\narrow functions defined in a scope where <code>this</code> may be used.</p>\n\n<p>Never use <code>this</code> to refer to the global object, the context of an <code>eval</code>, the\ntarget of an event, or unnecessarily <code>call()</code>ed or <code>apply()</code>ed functions.</p>\n\n<pre><code class=\"language-ts bad\">this.alert('Hello');\n</code></pre>\n\n<h3 id=\"interfaces\" class=\"numbered\">Interfaces</h3>\n\n \n\n \n\n<h3 id=\"primitive-literals\" class=\"numbered\">Primitive literals</h3>\n\n<p><a id=\"features-string-literals\"></a></p>\n\n<h4 id=\"string-literals\" class=\"numbered\">String literals</h4>\n\n<p><a id=\"features-strings-use-single-quotes\"></a></p>\n\n<h5 id=\"use-single-quotes\" class=\"numbered\">Use single quotes</h5>\n\n<p>Ordinary string literals are delimited with single quotes (<code>'</code>), rather than\ndouble quotes (<code>\"</code>).</p>\n\n<p>Tip: if a string contains a single quote character, consider using a template\nstring to avoid having to escape the quote.</p>\n\n<p><a id=\"syntax-no-line-continuations\"></a>\n<a id=\"features-strings-no-line-continuations\"></a></p>\n\n<h5 id=\"no-line-continuations\" class=\"numbered\">No line continuations</h5>\n\n<p>Do not use <em>line continuations</em> (that is, ending a line inside a string literal\nwith a backslash) in either ordinary or template string literals. Even though\nES5 allows this, it can lead to tricky errors if any trailing whitespace comes\nafter the slash, and is less obvious to readers.</p>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-ts bad\">const LONG_STRING = 'This is a very very very very very very very long string. \\\n    It inadvertently contains long stretches of spaces due to how the \\\n    continued lines are indented.';\n</code></pre>\n\n<p>Instead, write</p>\n\n<pre><code class=\"language-ts good\">const LONG_STRING = 'This is a very very very very very very long string. ' +\n    'It does not contain long stretches of spaces because it uses ' +\n    'concatenated strings.';\nconst SINGLE_STRING =\n    'http://it.is.also/acceptable_to_use_a_single_long_string_when_breaking_would_hinder_search_discoverability';\n</code></pre>\n\n<p><a id=\"features-strings-template-strings\"></a></p>\n\n<h5 id=\"template-literals\" class=\"numbered\">Template literals</h5>\n\n<p>Use template literals (delimited with <code>`</code>) over complex string\nconcatenation, particularly if multiple string literals are involved. Template\nliterals may span multiple lines.</p>\n\n<p>If a template literal spans multiple lines, it does not need to follow the\nindentation of the enclosing block, though it may if the added whitespace does\nnot matter.</p>\n\n<p>Example:</p>\n\n<pre><code class=\"language-ts good\">function arithmetic(a: number, b: number) {\n  return `Here is a table of arithmetic operations:\n${a} + ${b} = ${a + b}\n${a} - ${b} = ${a - b}\n${a} * ${b} = ${a * b}\n${a} / ${b} = ${a / b}`;\n}\n</code></pre>\n\n<p><a id=\"features-number-literals\"></a></p>\n\n<h4 id=\"number-literals\" class=\"numbered\">Number literals</h4>\n\n<p>Numbers may be specified in decimal, hex, octal, or binary. Use exactly <code>0x</code>,\n<code>0o</code>, and <code>0b</code> prefixes, with lowercase letters, for hex, octal, and binary,\nrespectively. Never include a leading zero unless it is immediately followed by\n<code>x</code>, <code>o</code>, or <code>b</code>.</p>\n\n<h4 id=\"type-coercion\" class=\"numbered\">Type coercion</h4>\n\n<p>TypeScript code <em>may</em> use the <code>String()</code> and <code>Boolean()</code> (note: no <code>new</code>!)\nfunctions, string template literals, or <code>!!</code> to coerce types.</p>\n\n<pre><code class=\"language-ts good\">const bool = Boolean(false);\nconst str = String(aNumber);\nconst bool2 = !!str;\nconst str2 = `result: ${bool2}`;\n</code></pre>\n\n<p>Values of enum types (including unions of enum types and other types) <em>must not</em>\nbe converted to booleans with <code>Boolean()</code> or <code>!!</code>, and must instead be compared\nexplicitly with comparison operators.</p>\n\n<pre><code class=\"language-ts bad\">enum SupportLevel {\n  NONE,\n  BASIC,\n  ADVANCED,\n}\n\nconst level: SupportLevel = ...;\nlet enabled = Boolean(level);\n\nconst maybeLevel: SupportLevel|undefined = ...;\nenabled = !!maybeLevel;\n</code></pre>\n\n<pre><code class=\"language-ts good\">enum SupportLevel {\n  NONE,\n  BASIC,\n  ADVANCED,\n}\n\nconst level: SupportLevel = ...;\nlet enabled = level !== SupportLevel.NONE;\n\nconst maybeLevel: SupportLevel|undefined = ...;\nenabled = level !== undefined &amp;&amp; level !== SupportLevel.NONE;\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>For most purposes, it doesn't matter what number or string value an enum name is\nmapped to at runtime, because values of enum types are referred to by name in\nsource code. Consequently, engineers are accustomed to not thinking about this,\nand so situations where it <em>does</em> matter are undesirable because they will be\nsurprising. Such is the case with conversion of enums to booleans; in\nparticular, by default, the first declared enum value is falsy (because it is 0)\nwhile the others are truthy, which is likely to be unexpected. Readers of code\nthat uses an enum value may not even know whether it's the first declared value\nor not.</p>\n\n</section> \n\n<p>Using string concatenation to cast to string is discouraged, as we check that\noperands to the plus operator are of matching types.</p>\n\n<p>Code <em>must</em> use <code>Number()</code> to parse numeric values, and <em>must</em> check its return\nfor <code>NaN</code> values explicitly, unless failing to parse is impossible from context.</p>\n\n<p>Note: <code>Number('')</code>, <code>Number(' ')</code>, and <code>Number('\\t')</code> would return <code>0</code> instead\nof <code>NaN</code>. <code>Number('Infinity')</code> and <code>Number('-Infinity')</code> would return <code>Infinity</code>\nand <code>-Infinity</code> respectively. Additionally, exponential notation such as\n<code>Number('1e+309')</code> and <code>Number('-1e+309')</code> can overflow into <code>Infinity</code>. These\ncases may require special handling.</p>\n\n<pre><code class=\"language-ts good\">const aNumber = Number('123');\nif (!isFinite(aNumber)) throw new Error(...);\n</code></pre>\n\n \n\n<p>Code <em>must not</em> use unary plus (<code>+</code>) to coerce strings to numbers. Parsing\nnumbers can fail, has surprising corner cases, and can be a code smell (parsing\nat the wrong layer). A unary plus is too easy to miss in code reviews given\nthis.</p>\n\n<pre><code class=\"language-ts bad\">const x = +y;\n</code></pre>\n\n<p>Code also <em>must not</em> use <code>parseInt</code> or <code>parseFloat</code> to parse numbers, except for\nnon-base-10 strings (see below). Both of those functions ignore trailing\ncharacters in the string, which can shadow error conditions (e.g. parsing <code>12\ndwarves</code> as <code>12</code>).</p>\n\n<pre><code class=\"language-ts bad\">const n = parseInt(someString, 10);  // Error prone,\nconst f = parseFloat(someString);    // regardless of passing a radix.\n</code></pre>\n\n<p>Code that requires parsing with a radix <em>must</em> check that its input contains\nonly appropriate digits for that radix before calling into <code>parseInt</code>;</p>\n\n<pre><code class=\"language-ts good\">if (!/^[a-fA-F0-9]+$/.test(someString)) throw new Error(...);\n// Needed to parse hexadecimal.\n// tslint:disable-next-line:ban\nconst n = parseInt(someString, 16);  // Only allowed for radix != 10\n</code></pre>\n\n<p>Use <code>Number()</code> followed by <code>Math.floor</code> or <code>Math.trunc</code> (where available) to\nparse integer numbers:</p>\n\n<pre><code class=\"language-ts good\">let f = Number(someString);\nif (isNaN(f)) handleError();\nf = Math.floor(f);\n</code></pre>\n\n<p><a id=\"type-coercion-implicit\"></a></p>\n\n<h5 id=\"implicit-coercion\" class=\"numbered\">Implicit coercion</h5>\n\n<p>Do not use explicit boolean coercions in conditional clauses that have implicit\nboolean coercion. Those are the conditions in an <code>if</code>, <code>for</code> and <code>while</code>\nstatements.</p>\n\n<pre><code class=\"language-ts bad\">const foo: MyInterface|null = ...;\nif (!!foo) {...}\nwhile (!!foo) {...}\n</code></pre>\n\n<pre><code class=\"language-ts good\">const foo: MyInterface|null = ...;\nif (foo) {...}\nwhile (foo) {...}\n</code></pre>\n\n<p><a href=\"#type-coercion\">As with explicit conversions</a>, values of enum types (including\nunions of enum types and other types) <em>must not</em> be implicitly coerced to\nbooleans, and must instead be compared explicitly with comparison operators.</p>\n\n<pre><code class=\"language-ts bad\">enum SupportLevel {\n  NONE,\n  BASIC,\n  ADVANCED,\n}\n\nconst level: SupportLevel = ...;\nif (level) {...}\n\nconst maybeLevel: SupportLevel|undefined = ...;\nif (level) {...}\n</code></pre>\n\n<pre><code class=\"language-ts good\">enum SupportLevel {\n  NONE,\n  BASIC,\n  ADVANCED,\n}\n\nconst level: SupportLevel = ...;\nif (level !== SupportLevel.NONE) {...}\n\nconst maybeLevel: SupportLevel|undefined = ...;\nif (level !== undefined &amp;&amp; level !== SupportLevel.NONE) {...}\n</code></pre>\n\n<p>Other types of values may be either implicitly coerced to booleans or compared\nexplicitly with comparison operators:</p>\n\n<pre><code class=\"language-ts good\">// Explicitly comparing &gt; 0 is OK:\nif (arr.length &gt; 0) {...}\n// so is relying on boolean coercion:\nif (arr.length) {...}\n</code></pre>\n\n<p><a id=\"features-control-structures\"></a></p>\n\n<h3 id=\"control-structures\" class=\"numbered\">Control structures</h3>\n\n<p><a id=\"formatting-braces\"></a>\n<a id=\"formatting-braces-all\"></a></p>\n\n<h4 id=\"control-flow-statements-blocks\" class=\"numbered\">Control flow statements and blocks</h4>\n\n<p>Control flow statements (<code>if</code>, <code>else</code>, <code>for</code>, <code>do</code>, <code>while</code>, etc) always use\nbraced blocks for the containing code, even if the body contains only a single\nstatement. The first statement of a non-empty block must begin on its own line.</p>\n\n<pre><code class=\"language-ts good\">for (let i = 0; i &lt; x; i++) {\n  doSomethingWith(i);\n}\n\nif (x) {\n  doSomethingWithALongMethodNameThatForcesANewLine(x);\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">if (x)\n  doSomethingWithALongMethodNameThatForcesANewLine(x);\n\nfor (let i = 0; i &lt; x; i++) doSomethingWith(i);\n</code></pre>\n\n<p><strong>Exception:</strong> <code>if</code> statements fitting on one line <em>may</em> elide the block.</p>\n\n<pre><code class=\"language-ts good\">if (x) x.doFoo();\n</code></pre>\n\n<h5 id=\"assignment-in-control-statements\" class=\"numbered\">Assignment in control statements</h5>\n\n<p>Prefer to avoid assignment of variables inside control statements. Assignment\ncan be easily mistaken for equality checks inside control statements.</p>\n\n<pre><code class=\"language-ts bad\">if (x = someFunction()) {\n  // Assignment easily mistaken with equality check\n  // ...\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">x = someFunction();\nif (x) {\n  // ...\n}\n</code></pre>\n\n<p>In cases where assignment inside the control statement is preferred, enclose the\nassignment in additional parenthesis to indicate it is intentional.</p>\n\n<pre><code class=\"language-ts\">while ((x = someFunction())) {\n  // Double parenthesis shows assignment is intentional\n  // ...\n}\n\n</code></pre>\n\n<p><a id=\"features-for-loops\"></a></p>\n\n<h5 id=\"iterating-containers\" class=\"numbered\">Iterating containers</h5>\n\n<p>Prefer <code>for (... of someArr)</code> to iterate over arrays. <code>Array.prototype.forEach</code> and vanilla <code>for</code>\nloops are also allowed:</p>\n\n<pre><code class=\"language-ts good\">for (const x of someArr) {\n  // x is a value of someArr.\n}\n\nfor (let i = 0; i &lt; someArr.length; i++) {\n  // Explicitly count if the index is needed, otherwise use the for/of form.\n  const x = someArr[i];\n  // ...\n}\nfor (const [i, x] of someArr.entries()) {\n  // Alternative version of the above.\n}\n</code></pre>\n\n<p><code>for</code>-<code>in</code> loops may only be used on dict-style objects (see\n<a href=\"#optimization-compatibility-for-property-access\">below</a> for more info). Do not\nuse <code>for (... in ...)</code> to iterate over arrays as it will counterintuitively give\nthe array's indices (as strings!), not values:</p>\n\n<pre><code class=\"language-ts bad\">for (const x in someArray) {\n  // x is the index!\n}\n</code></pre>\n\n<p><code>Object.prototype.hasOwnProperty</code> should be used in <code>for</code>-<code>in</code> loops to exclude\nunwanted prototype properties. Prefer <code>for</code>-<code>of</code> with <code>Object.keys</code>,\n<code>Object.values</code>, or <code>Object.entries</code> over <code>for</code>-<code>in</code> when possible.</p>\n\n<pre><code class=\"language-ts good\">for (const key in obj) {\n  if (!obj.hasOwnProperty(key)) continue;\n  doWork(key, obj[key]);\n}\nfor (const key of Object.keys(obj)) {\n  doWork(key, obj[key]);\n}\nfor (const value of Object.values(obj)) {\n  doWorkValOnly(value);\n}\nfor (const [key, value] of Object.entries(obj)) {\n  doWork(key, value);\n}\n</code></pre>\n\n<p><a id=\"formatting-grouping-parentheses\"></a></p>\n\n<h4 id=\"grouping-parentheses\" class=\"numbered\">Grouping parentheses</h4>\n\n<p>Optional grouping parentheses are omitted only when the author and reviewer\nagree that there is no reasonable chance that the code will be misinterpreted\nwithout them, nor would they have made the code easier to read. It is <em>not</em>\nreasonable to assume that every reader has the entire operator precedence table\nmemorized.</p>\n\n<p>Do not use unnecessary parentheses around the entire expression following\n<code>delete</code>, <code>typeof</code>, <code>void</code>, <code>return</code>, <code>throw</code>, <code>case</code>, <code>in</code>, <code>of</code>, or <code>yield</code>.</p>\n\n \n\n<p><a id=\"exceptions\"></a>\n<a id=\"features-exceptions\"></a></p>\n\n<h4 id=\"exception-handling\" class=\"numbered\">Exception handling</h4>\n\n<p>Exceptions are an important part of the language and should be used whenever\nexceptional cases occur.</p>\n\n<p>Custom exceptions provide a great way to convey additional error information\nfrom functions. They should be defined and used wherever the native <code>Error</code> type\nis insufficient.</p>\n\n<p>Prefer throwing exceptions over ad-hoc error-handling approaches (such as\npassing an error container reference type, or returning an object with an error\nproperty).</p>\n\n<h5 id=\"instantiate-errors-using-new\" class=\"numbered\">Instantiate errors using <code>new</code></h5>\n\n<p>Always use <code>new Error()</code> when instantiating exceptions, instead of just calling\n<code>Error()</code>. Both forms create a new <code>Error</code> instance, but using <code>new</code> is more\nconsistent with how other objects are instantiated.</p>\n\n<pre><code class=\"language-ts good\">throw new Error('Foo is not a valid bar.');\n</code></pre>\n\n<pre><code class=\"language-ts bad\">throw Error('Foo is not a valid bar.');\n</code></pre>\n\n<h5 id=\"only-throw-errors\" class=\"numbered\">Only throw errors</h5>\n\n<p>JavaScript (and thus TypeScript) allow throwing or rejecting a Promise with\narbitrary values. However if the thrown or rejected value is not an <code>Error</code>, it\ndoes not populate stack trace information, making debugging hard. This treatment\nextends to <code>Promise</code> rejection values as <code>Promise.reject(obj)</code> is equivalent to\n<code>throw obj;</code> in async functions.</p>\n\n<pre><code class=\"language-ts bad\">// bad: does not get a stack trace.\nthrow 'oh noes!';\n// For promises\nnew Promise((resolve, reject) =&gt; void reject('oh noes!'));\nPromise.reject();\nPromise.reject('oh noes!');\n</code></pre>\n\n<p>Instead, only throw (subclasses of) <code>Error</code>:</p>\n\n<pre><code class=\"language-ts good\">// Throw only Errors\nthrow new Error('oh noes!');\n// ... or subtypes of Error.\nclass MyError extends Error {}\nthrow new MyError('my oh noes!');\n// For promises\nnew Promise((resolve) =&gt; resolve()); // No reject is OK.\nnew Promise((resolve, reject) =&gt; void reject(new Error('oh noes!')));\nPromise.reject(new Error('oh noes!'));\n</code></pre>\n\n<h5 id=\"catching-and-rethrowing\" class=\"numbered\">Catching and rethrowing</h5>\n\n<p>When catching errors, code <em>should</em> assume that all thrown errors are instances\nof <code>Error</code>.</p>\n\n \n\n<section>\n\n<pre><code class=\"language-ts good\">function assertIsError(e: unknown): asserts e is Error {\n  if (!(e instanceof Error)) throw new Error(\"e is not an Error\");\n}\n\ntry {\n  doSomething();\n} catch (e: unknown) {\n  // All thrown errors must be Error subtypes. Do not handle\n  // other possible values unless you know they are thrown.\n  assertIsError(e);\n  displayError(e.message);\n  // or rethrow:\n  throw e;\n}\n</code></pre>\n\n</section> \n\n<p>Exception handlers <em>must not</em> defensively handle non-<code>Error</code> types unless the\ncalled API is conclusively known to throw non-<code>Error</code>s in violation of the above\nrule. In that case, a comment should be included to specifically identify where\nthe non-<code>Error</code>s originate.</p>\n\n<pre><code class=\"language-ts good\">try {\n  badApiThrowingStrings();\n} catch (e: unknown) {\n  // Note: bad API throws strings instead of errors.\n  if (typeof e === 'string') { ... }\n}\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>Avoid\n<a href=\"https://en.wikipedia.org/wiki/Defensive_programming#Offensive_programming\">overly defensive programming</a>.\nRepeating the same defenses against a problem that will not exist in most code\nleads to boiler-plate code that is not useful.</p>\n\n</section> \n\n<p><a id=\"features-empty-catch-blocks\"></a></p>\n\n<h5 id=\"empty-catch-blocks\" class=\"numbered\">Empty catch blocks</h5>\n\n<p>It is very rarely correct to do nothing in response to a caught exception. When\nit truly is appropriate to take no action whatsoever in a catch block, the\nreason this is justified is explained in a comment.</p>\n\n<pre><code class=\"language-ts good\">  try {\n    return handleNumericResponse(response);\n  } catch (e: unknown) {\n    // Response is not numeric. Continue to handle as text.\n  }\n  return handleTextResponse(response);\n</code></pre>\n\n<p>Disallowed:</p>\n\n<pre><code class=\"language-ts bad\">  try {\n    shouldFail();\n    fail('expected an error');\n  } catch (expected: unknown) {\n  }\n</code></pre>\n\n<p>Tip: Unlike in some other languages, patterns like the above simply don’t work\nsince this will catch the error thrown by <code>fail</code>. Use <code>assertThrows()</code> instead.</p>\n\n<p><a id=\"features-switch-statements\"></a>\n<a id=\"features-switch-default-case\"></a></p>\n\n<h4 id=\"switch-statements\" class=\"numbered\">Switch statements</h4>\n\n<p>All <code>switch</code> statements <em>must</em> contain a <code>default</code> statement group, even if it\ncontains no code. The <code>default</code> statement group must be last.</p>\n\n<pre><code class=\"language-ts good\">switch (x) {\n  case Y:\n    doSomethingElse();\n    break;\n  default:\n    // nothing to do.\n}\n</code></pre>\n\n<p>Within a switch block, each statement group either terminates abruptly with a\n<code>break</code>, a <code>return</code> statement, or by throwing an exception. Non-empty statement\ngroups (<code>case ...</code>) <em>must not</em> fall through (enforced by the compiler):</p>\n\n<pre><code class=\"language-ts bad\">switch (x) {\n  case X:\n    doSomething();\n    // fall through - not allowed!\n  case Y:\n    // ...\n}\n</code></pre>\n\n<p>Empty statement groups are allowed to fall through:</p>\n\n<pre><code class=\"language-ts good\">switch (x) {\n  case X:\n  case Y:\n    doSomething();\n    break;\n  default: // nothing to do.\n}\n</code></pre>\n\n \n\n<p><a id=\"features-equality-checks\"></a>\n<a id=\"features-equality-checks-exceptions\"></a></p>\n\n<h4 id=\"equality-checks\" class=\"numbered\">Equality checks</h4>\n\n<p>Always use triple equals (<code>===</code>) and not equals (<code>!==</code>). The double equality\noperators cause error prone type coercions that are hard to understand and\nslower to implement for JavaScript Virtual Machines. See also the\n<a href=\"https://dorey.github.io/JavaScript-Equality-Table/\">JavaScript equality table</a>.</p>\n\n<pre><code class=\"language-ts bad\">if (foo == 'bar' || baz != bam) {\n  // Hard to understand behaviour due to type coercion.\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">if (foo === 'bar' || baz !== bam) {\n  // All good here.\n}\n</code></pre>\n\n<p><strong>Exception:</strong> Comparisons to the literal <code>null</code> value <em>may</em> use the <code>==</code> and\n<code>!=</code> operators to cover both <code>null</code> and <code>undefined</code> values.</p>\n\n<pre><code class=\"language-ts good\">if (foo == null) {\n  // Will trigger when foo is null or undefined.\n}\n</code></pre>\n\n<h4 id=\"type-and-non-nullability-assertions\" class=\"numbered\">Type and non-nullability assertions</h4>\n\n<p>Type assertions (<code>x as SomeType</code>) and non-nullability assertions (<code>y!</code>) are\nunsafe. Both only silence the TypeScript compiler, but do not insert any runtime\nchecks to match these assertions, so they can cause your program to crash at\nruntime.</p>\n\n<p>Because of this, you <em>should not</em> use type and non-nullability assertions\nwithout an obvious or explicit reason for doing so.</p>\n\n<p>Instead of the following:</p>\n\n<pre><code class=\"language-ts bad\">(x as Foo).foo();\n\ny!.bar();\n</code></pre>\n\n<p>When you want to assert a type or non-nullability the best answer is to\nexplicitly write a runtime check that performs that check.</p>\n\n<pre><code class=\"language-ts good\">// assuming Foo is a class.\nif (x instanceof Foo) {\n  x.foo();\n}\n\nif (y) {\n  y.bar();\n}\n</code></pre>\n\n<p>Sometimes due to some local property of your code you can be sure that the\nassertion form is safe. In those situations, you <em>should</em> add clarification to\nexplain why you are ok with the unsafe behavior:</p>\n\n<pre><code class=\"language-ts good\">// x is a Foo, because ...\n(x as Foo).foo();\n\n// y cannot be null, because ...\ny!.bar();\n</code></pre>\n\n<p>If the reasoning behind a type or non-nullability assertion is obvious, the\ncomments <em>may</em> not be necessary. For example, generated proto code is always\nnullable, but perhaps it is well-known in the context of the code that certain\nfields are always provided by the backend. Use your judgement.</p>\n\n<h5 id=\"type-assertions-syntax\" class=\"numbered\">Type assertion syntax</h5>\n\n<p>Type assertions <em>must</em> use the <code>as</code> syntax (as opposed to the angle brackets\nsyntax). This enforces parentheses around the assertion when accessing a member.</p>\n\n<pre><code class=\"language-ts bad\">const x = (&lt;Foo&gt;z).length;\nconst y = &lt;Foo&gt;z.length;\n</code></pre>\n\n<pre><code class=\"language-ts good\">// z must be Foo because ...\nconst x = (z as Foo).length;\n</code></pre>\n\n<h5 id=\"double-assertions\" class=\"numbered\">Double assertions</h5>\n\n<p>From the\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions\">TypeScript handbook</a>,\nTypeScript only allows type assertions which convert to a <em>more specific</em> or\n<em>less specific</em> version of a type. Adding a type assertion (<code>x as Foo</code>) which\ndoes not meet this criteria will give the error: <q>Conversion of type 'X' to type\n'Y' may be a mistake because neither type sufficiently overlaps with the other.</q></p>\n\n<p>If you are sure an assertion is safe, you can perform a <em>double assertion</em>. This\ninvolves casting through <code>unknown</code> since it is less specific than all types.</p>\n\n<pre><code class=\"language-ts good\">// x is a Foo here, because...\n(x as unknown as Foo).fooMethod();\n</code></pre>\n\n<p>Use <code>unknown</code> (instead of <code>any</code> or <code>{}</code>) as the intermediate type.</p>\n\n<h5 id=\"type-assertions-and-object-literals\" class=\"numbered\">Type assertions and object literals</h5>\n\n<p>Use type annotations (<code>: Foo</code>) instead of type assertions (<code>as Foo</code>) to specify\nthe type of an object literal. This allows detecting refactoring bugs when the\nfields of an interface change over time.</p>\n\n<pre><code class=\"language-ts bad\">interface Foo {\n  bar: number;\n  baz?: string;  // was \"bam\", but later renamed to \"baz\".\n}\n\nconst foo = {\n  bar: 123,\n  bam: 'abc',  // no error!\n} as Foo;\n\nfunction func() {\n  return {\n    bar: 123,\n    bam: 'abc',  // no error!\n  } as Foo;\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">interface Foo {\n  bar: number;\n  baz?: string;\n}\n\nconst foo: Foo = {\n  bar: 123,\n  bam: 'abc',  // complains about \"bam\" not being defined on Foo.\n};\n\nfunction func(): Foo {\n  return {\n    bar: 123,\n    bam: 'abc',   // complains about \"bam\" not being defined on Foo.\n  };\n}\n</code></pre>\n\n<h4 id=\"keep-try-blocks-focused\" class=\"numbered\">Keep try blocks focused</h4>\n\n<p>Limit the amount of code inside a try block, if this can be done without hurting\nreadability.</p>\n\n<pre><code class=\"language-ts bad\">try {\n  const result = methodThatMayThrow();\n  use(result);\n} catch (error: unknown) {\n  // ...\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">let result;\ntry {\n  result = methodThatMayThrow();\n} catch (error: unknown) {\n  // ...\n}\nuse(result);\n</code></pre>\n\n<p>Moving the non-throwable lines out of the try/catch block helps the reader learn\nwhich method throws exceptions. Some inline calls that do not throw exceptions\ncould stay inside because they might not be worth the extra complication of a\ntemporary variable.</p>\n\n<p><strong>Exception:</strong> There may be performance issues if try blocks are inside a loop.\nWidening try blocks to cover a whole loop is ok.</p>\n\n<h3 id=\"decorators\" class=\"numbered\">Decorators</h3>\n\n<p>Decorators are syntax with an <code>@</code> prefix, like <code>@MyDecorator</code>.</p>\n\n<p>Do not define new decorators. Only use the decorators defined by\nframeworks:</p>\n\n<ul>\n<li>Angular (e.g. <code>@Component</code>, <code>@NgModule</code>, etc.)</li>\n<li>Polymer (e.g. <code>@property</code>)</li>\n</ul>\n\n \n\n<section>\n\n<p>Why?</p>\n\n<p>We generally want to avoid decorators, because they were an experimental feature\nthat have since diverged from the TC39 proposal and have known bugs that won't\nbe fixed.</p>\n\n</section> \n\n<p>When using decorators, the decorator <em>must</em> immediately precede the symbol it\ndecorates, with no empty lines between:</p>\n\n<pre><code class=\"language-ts\">/** JSDoc comments go before decorators */\n@Component({...})  // Note: no empty line after the decorator.\nclass MyComp {\n  @Input() myField: string;  // Decorators on fields may be on the same line...\n\n  @Input()\n  myOtherField: string;  // ... or wrap.\n}\n</code></pre>\n\n<h3 id=\"disallowed-features\" class=\"numbered\">Disallowed features</h3>\n\n<p><a id=\"disallowed-features-wrapper-objects\"></a></p>\n\n<h4 id=\"primitive-types-wrapper-classes\" class=\"numbered\">Wrapper objects for primitive types</h4>\n\n<p>TypeScript code <em>must not</em> instantiate the wrapper classes for the primitive\ntypes <code>String</code>, <code>Boolean</code>, and <code>Number</code>. Wrapper classes have surprising\nbehavior, such as <code>new Boolean(false)</code> evaluating to <code>true</code>.</p>\n\n<pre><code class=\"language-ts bad\">const s = new String('hello');\nconst b = new Boolean(false);\nconst n = new Number(5);\n</code></pre>\n\n<p>The wrappers may be called as functions for coercing (which is preferred over\nusing <code>+</code> or concatenating the empty string) or creating symbols. See\n<a href=\"#type-coercion\">type coercion</a> for more information.</p>\n\n<p><a id=\"formatting-semicolons-are-required\"></a>\n<a id=\"disallowed-features-automatic-semicolon-insertion\"></a></p>\n\n<h4 id=\"automatic-semicolon-insertion\" class=\"numbered\">Automatic Semicolon Insertion</h4>\n\n<p>Do not rely on Automatic Semicolon Insertion (ASI). Explicitly end all\nstatements using a semicolon. This prevents bugs due to incorrect semicolon\ninsertions and ensures compatibility with tools with limited ASI support (e.g.\nclang-format).</p>\n\n<h4 id=\"enums\" class=\"numbered\">Const enums</h4>\n\n<p>Code <em>must not</em> use <code>const enum</code>; use plain <code>enum</code> instead.</p>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>TypeScript enums already cannot be mutated; <code>const enum</code> is a separate language\nfeature related to optimization that makes the enum invisible to\nJavaScript users of the module.</p>\n\n</section> \n\n<h4 id=\"debugger-statements\" class=\"numbered\">Debugger statements</h4>\n\n<p>Debugger statements <em>must not</em> be included in production code.</p>\n\n<pre><code class=\"language-ts bad\">function debugMe() {\n  debugger;\n}\n</code></pre>\n\n<p><a id=\"disallowed-features-with\"></a></p>\n\n<h4 id=\"diallowed-features-with\" class=\"numbered\"><code>with</code></h4>\n\n<p>Do not use the <code>with</code> keyword. It makes your code harder to understand and\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with\">has been banned in strict mode since ES5</a>.</p>\n\n<p><a id=\"disallowed-features-dynamic-code-evaluation\"></a></p>\n\n<h4 id=\"dynamic-code-evaluation\" class=\"numbered\">Dynamic code evaluation</h4>\n\n<p>Do not use <code>eval</code> or the <code>Function(...string)</code> constructor (except for code\nloaders). These features are potentially dangerous and simply do not work in\nenvironments using strict\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP\">Content Security Policies</a>.</p>\n\n<p><a id=\"disallowed-features-non-standard-features\"></a></p>\n\n<h4 id=\"non-standard-features\" class=\"numbered\">Non-standard features</h4>\n\n<p>Do not use non-standard ECMAScript or Web Platform features.</p>\n\n<p>This includes:</p>\n\n<ul>\n<li>Old features that have been marked deprecated or removed entirely from\nECMAScript / the Web Platform (see\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features\">MDN</a>)</li>\n<li>New ECMAScript features that are not yet standardized\n<ul>\n<li>Avoid using features that are in current TC39 working draft or currently\nin the <a href=\"https://tc39.es/process-document/\">proposal process</a></li>\n<li>Use only ECMAScript features defined in the current ECMA-262\nspecification</li>\n</ul></li>\n<li>Proposed but not-yet-complete web standards:\n<ul>\n<li>WHATWG proposals that have not completed the\n<a href=\"https://whatwg.org/faq#adding-new-features\">proposal process</a>.</li>\n</ul></li>\n<li>Non-standard language “extensions” (such as those provided by some external\ntranspilers)</li>\n</ul>\n\n<p>Projects targeting specific JavaScript runtimes, such as latest-Chrome-only,\nChrome extensions, Node.JS, Electron, can obviously use those APIs. Use caution\nwhen considering an API surface that is proprietary and only implemented in some\nbrowsers; consider whether there is a common library that can abstract this API\nsurface away for you.</p>\n\n<p><a id=\"disallowed-features-modifying-builtin-objects\"></a></p>\n\n<h4 id=\"modifying-builtin-objects\" class=\"numbered\">Modifying builtin objects</h4>\n\n<p>Never modify builtin types, either by adding methods to their constructors or to\ntheir prototypes. Avoid depending on libraries that do\nthis.</p>\n\n<p>Do not add symbols to the global object unless absolutely necessary (e.g.\nrequired by a third-party API).</p>\n\n<p><a id=\"syntax\"></a>\n<a id=\"naming-rules-common-to-all-identifiers\"></a></p>\n\n<h2 id=\"naming\" class=\"numbered\">Naming</h2>\n\n<h3 id=\"identifiers\" class=\"numbered\">Identifiers</h3>\n\n<p>Identifiers <em>must</em> use only ASCII letters, digits, underscores (for constants\nand structured test method names), and (rarely) the '$' sign.</p>\n\n<h4 id=\"naming-style\" class=\"numbered\">Naming style</h4>\n\n<p>TypeScript expresses information in types, so names <em>should not</em> be decorated\nwith information that is included in the type. (See also\n<a href=\"https://testing.googleblog.com/2017/10/code-health-identifiernamingpostforworl.html\">Testing Blog</a>\n for more about what\nnot to include.)</p>\n\n<p>Some concrete examples of this rule:</p>\n\n<ul>\n<li>Do not use trailing or leading underscores for private properties or\nmethods.</li>\n<li>Do not use the <code>opt_</code> prefix for optional parameters.\n<ul>\n<li>For accessors, see <a href=\"#getters-and-setters-accessors\">accessor rules</a>\nbelow.</li>\n</ul></li>\n<li>Do not mark interfaces specially (<del><code>IMyInterface</code></del> or\n<del><code>MyFooInterface</code></del>) unless it's idiomatic in its\nenvironment. When\nintroducing an interface for a class, give it a name that expresses why the\ninterface exists in the first place (e.g. <code>class TodoItem</code> and <code>interface\nTodoItemStorage</code> if the interface expresses the format used for\nstorage/serialization in JSON).</li>\n<li>Suffixing <code>Observable</code>s with <code>$</code> is a common external convention and can\nhelp resolve confusion regarding observable values vs concrete values.\nJudgement on whether this is a useful convention is left up to individual\nteams, but <em>should</em> be consistent within projects.</li>\n</ul>\n\n<p><a id=\"identifiers-abbreviations\"></a></p>\n\n<h4 id=\"descriptive-names\" class=\"numbered\">Descriptive names</h4>\n\n<p>Names <em>must</em> be descriptive and clear to a new reader. Do not use abbreviations\nthat are ambiguous or unfamiliar to readers outside your project, and do not\nabbreviate by deleting letters within a word.</p>\n\n<ul>\n<li><strong>Exception:</strong> Variables that are in scope for 10 lines or fewer, including\narguments that are <em>not</em> part of an exported API, <em>may</em> use short (e.g.\nsingle letter) variable names.</li>\n</ul>\n\n<pre><code class=\"language-ts good\">// Good identifiers:\nerrorCount          // No abbreviation.\ndnsConnectionIndex  // Most people know what \"DNS\" stands for.\nreferrerUrl         // Ditto for \"URL\".\ncustomerId          // \"Id\" is both ubiquitous and unlikely to be misunderstood.\n</code></pre>\n\n<pre><code class=\"language-ts bad\">// Disallowed identifiers:\nn                   // Meaningless.\nnErr                // Ambiguous abbreviation.\nnCompConns          // Ambiguous abbreviation.\nwgcConnections      // Only your group knows what this stands for.\npcReader            // Lots of things can be abbreviated \"pc\".\ncstmrId             // Deletes internal letters.\nkSecondsPerDay      // Do not use Hungarian notation.\ncustomerID          // Incorrect camelcase of \"ID\".\n</code></pre>\n\n<p><a id=\"naming-camel-case-defined\"></a></p>\n\n<h4 id=\"camel-case\" class=\"numbered\">Camel case</h4>\n\n<p>\nTreat abbreviations like acronyms in names as whole words, i.e. use\n<code>loadHttpUrl</code>, not <del><code>loadHTTPURL</code></del>, unless required by a platform name (e.g.\n<code>XMLHttpRequest</code>).</p>\n\n<h4 id=\"identifiers-dollar-sign\" class=\"numbered\">Dollar sign</h4>\n\n<p>Identifiers <em>should not</em> generally use <code>$</code>, except when required by naming\nconventions for third party frameworks. <a href=\"#naming-style\">See above</a> for more on\nusing <code>$</code> with <code>Observable</code> values.</p>\n\n<p><a id=\"naming-class-names\"></a>\n<a id=\"naming-method-names\"></a>\n<a id=\"naming-enum-names\"></a>\n<a id=\"naming-constant-names\"></a>\n<a id=\"naming-local-variable-names\"></a>\n<a id=\"naming-non-constant-field-names\"></a>\n<a id=\"naming-parameter-names\"></a></p>\n\n<h3 id=\"naming-rules-by-identifier-type\" class=\"numbered\">Rules by identifier type</h3>\n\n<p>Most identifier names should follow the casing in the table below, based on the\nidentifier's type.</p>\n\n<table>\n<thead>\n<tr>\n<th>Style</th>\n<th>Category</th>\n</tr>\n</thead>\n\n<tbody>\n<tr>\n<td><code>UpperCamelCase</code>\n\n</td>\n<td>class / interface / type / enum / decorator / type\nparameters / component functions in TSX / JSXElement type\nparameter</td>\n</tr>\n<tr>\n<td><code>lowerCamelCase</code>\n</td>\n<td>variable / parameter / function / method / property /\nmodule alias</td>\n</tr>\n<tr>\n<td><code>CONSTANT_CASE</code>\n</td>\n<td>global constant values, including enum values. See\n<a href=\"#identifiers-constants\">Constants</a> below.</td>\n</tr>\n<tr>\n<td><code>#ident</code></td>\n<td>private identifiers are never used.</td>\n</tr>\n</tbody>\n</table>\n\n<p><a id=\"naming-template-parameter-names\"></a></p>\n\n<h4 id=\"identifiers-type-parameters\" class=\"numbered\">Type parameters</h4>\n\n<p>Type parameters, like in <code>Array&lt;T&gt;</code>, <em>may</em> use a single upper case character\n(<code>T</code>) or <code>UpperCamelCase</code>.</p>\n\n \n\n<h4 id=\"identifiers-test-names\" class=\"numbered\">Test names</h4>\n\n<p>Test method names inxUnit-style test frameworks <em>may</em> be structured with <code>_</code> separators, e.g.\n<code>testX_whenY_doesZ()</code>.</p>\n\n<h4 id=\"identifiers-underscore-prefix-suffix\" class=\"numbered\"><code>_</code> prefix/suffix</h4>\n\n<p>Identifiers must not use <code>_</code> as a prefix or suffix.</p>\n\n<p>This also means that <code>_</code> <em>must not</em> be used as an identifier by itself (e.g. to\nindicate a parameter is unused).</p>\n\n<blockquote>\n<p>Tip: If you only need some of the elements from an array (or TypeScript\ntuple), you can insert extra commas in a destructuring statement to ignore\nin-between elements:</p>\n\n<pre><code class=\"language-ts\">const [a, , b] = [1, 5, 10];  // a &lt;- 1, b &lt;- 10\n</code></pre>\n</blockquote>\n\n \n\n<h4 id=\"identifiers-imports\" class=\"numbered\">Imports</h4>\n\n<p>Module namespace imports are <code>lowerCamelCase</code> while files are <code>snake_case</code>,\nwhich means that imports correctly will not match in casing style, such as</p>\n\n<pre><code class=\"language-ts good\">import * as fooBar from './foo_bar';\n</code></pre>\n\n<p>Some libraries might commonly use a namespace import prefix that violates this\nnaming scheme, but overbearingly common open source use makes the violating\nstyle more readable. The only libraries that currently fall under this exception\nare:</p>\n\n<ul>\n<li><a href=\"https://jquery.com/\">jquery</a>, using the <code>$</code> prefix</li>\n<li><a href=\"https://threejs.org/\">threejs</a>, using the <code>THREE</code> prefix</li>\n</ul>\n\n<h4 id=\"identifiers-constants\" class=\"numbered\">Constants</h4>\n\n<p><strong>Immutable</strong>: <code>CONSTANT_CASE</code> indicates that a value is <em>intended</em> to not be\nchanged, and <em>may</em> be used for values that can technically be modified (i.e.\nvalues that are not deeply frozen) to indicate to users that they must not be\nmodified.</p>\n\n<pre><code class=\"language-ts good\">const UNIT_SUFFIXES = {\n  'milliseconds': 'ms',\n  'seconds': 's',\n};\n// Even though per the rules of JavaScript UNIT_SUFFIXES is\n// mutable, the uppercase shows users to not modify it.\n</code></pre>\n\n<p>A constant can also be a <code>static readonly</code> property of a class.</p>\n\n<pre><code class=\"language-ts good\">class Foo {\n  private static readonly MY_SPECIAL_NUMBER = 5;\n\n  bar() {\n    return 2 * Foo.MY_SPECIAL_NUMBER;\n  }\n}\n</code></pre>\n\n<p><strong>Global</strong>: Only symbols declared on the module level, static fields of module\nlevel classes, and values of module level enums, <em>may</em> use <code>CONST_CASE</code>. If a\nvalue can be instantiated more than once over the lifetime of the program (e.g.\na local variable declared within a function, or a static field on a class nested\nin a function) then it <em>must</em> use <code>lowerCamelCase</code>.</p>\n\n<p>If a value is an arrow function that implements an interface, then it <em>may</em> be\ndeclared <code>lowerCamelCase</code>.</p>\n\n \n\n \n\n<p><a id=\"naming-local-aliases\"></a></p>\n\n<h4 id=\"aliases\" class=\"numbered\">Aliases</h4>\n\n<p>When creating a local-scope alias of an existing symbol, use the format of the\nexisting identifier. The local alias <em>must</em> match the existing naming and format\nof the source. For variables use <code>const</code> for your local aliases, and for class\nfields use the <code>readonly</code> attribute.</p>\n\n<blockquote>\n<p>Note: If you're creating an alias just to expose it to a template in your\nframework of choice, remember to also apply the proper\n<a href=\"#properties-used-outside-of-class-lexical-scope\">access modifiers</a>.</p>\n</blockquote>\n\n<pre><code class=\"language-ts good\">const {BrewStateEnum} = SomeType;\nconst CAPACITY = 5;\n\nclass Teapot {\n  readonly BrewStateEnum = BrewStateEnum;\n  readonly CAPACITY = CAPACITY;\n}\n</code></pre>\n\n<h2 id=\"type-system\" class=\"numbered\">Type system</h2>\n\n<h3 id=\"type-inference\" class=\"numbered\">Type inference</h3>\n\n<p>Code <em>may</em> rely on type inference as implemented by the TypeScript compiler for\nall type expressions (variables, fields, return types, etc).\n</p>\n\n<pre><code class=\"language-ts good\">const x = 15;  // Type inferred.\n</code></pre>\n\n<p>Leave out type annotations for trivially inferred types: variables or parameters\ninitialized to a <code>string</code>, <code>number</code>, <code>boolean</code>, <code>RegExp</code> literal or <code>new</code>\nexpression.</p>\n\n<pre><code class=\"language-ts bad\">const x: boolean = true;  // Bad: 'boolean' here does not aid readability\n</code></pre>\n\n<pre><code class=\"language-ts bad\">// Bad: 'Set' is trivially inferred from the initialization\nconst x: Set&lt;string&gt; = new Set();\n</code></pre>\n\n<p>Explicitly specifying types may be required to prevent generic type parameters\nfrom being inferred as <code>unknown</code>. For example, initializing generic types with\nno values (e.g. empty arrays, objects, <code>Map</code>s, or <code>Set</code>s).</p>\n\n<pre><code class=\"language-ts good\">const x = new Set&lt;string&gt;();\n</code></pre>\n\n<p>For more complex expressions, type annotations can help with readability of the\nprogram:</p>\n\n<pre><code class=\"language-ts bad\">// Hard to reason about the type of 'value' without an annotation.\nconst value = await rpc.getSomeValue().transform();\n</code></pre>\n\n<pre><code class=\"language-ts good\">// Can tell the type of 'value' at a glance.\nconst value: string[] = await rpc.getSomeValue().transform();\n</code></pre>\n\n<p>Whether an annotation is required is decided by the code reviewer.</p>\n\n \n\n<h4 id=\"return-types\" class=\"numbered\">Return types</h4>\n\n<p>Whether to include return type annotations for functions and methods is up to\nthe code author. Reviewers <em>may</em> ask for annotations to clarify complex return\ntypes that are hard to understand. Projects <em>may</em> have a local policy to always\nrequire return types, but this is not a general TypeScript style requirement.</p>\n\n<p>There are two benefits to explicitly typing out the implicit return values of\nfunctions and methods:</p>\n\n<ul>\n<li>More precise documentation to benefit readers of the code.</li>\n<li>Surface potential type errors faster in the future if there are code changes\nthat change the return type of the function.</li>\n</ul>\n\n<p><a id=\"null-vs-undefined\"></a></p>\n\n<h3 id=\"undefined-and-null\" class=\"numbered\">Undefined and null</h3>\n\n<p>TypeScript supports <code>undefined</code> and <code>null</code> types. Nullable types can be\nconstructed as a union type (<code>string|null</code>); similarly with <code>undefined</code>. There\nis no special syntax for unions of <code>undefined</code> and <code>null</code>.</p>\n\n \n\n<p>TypeScript code can use either <code>undefined</code> or <code>null</code> to denote absence of a\nvalue, there is no general guidance to prefer one over the other. Many\nJavaScript APIs use <code>undefined</code> (e.g. <code>Map.get</code>), while many DOM and Google APIs\nuse <code>null</code> (e.g. <code>Element.getAttribute</code>), so the appropriate absent value\ndepends on the context.</p>\n\n<h4 id=\"nullableundefined-type-aliases\" class=\"numbered\">Nullable/undefined type aliases</h4>\n\n<p>Type aliases <em>must not</em> include <code>|null</code> or <code>|undefined</code> in a union type.\nNullable aliases typically indicate that null values are being passed around\nthrough too many layers of an application, and this clouds the source of the\noriginal issue that resulted in <code>null</code>. They also make it unclear when specific\nvalues on a class or interface might be absent.</p>\n\n<p>Instead, code <em>must</em> only add <code>|null</code> or <code>|undefined</code> when the alias is actually\nused. Code <em>should</em> deal with null values close to where they arise, using the\nabove techniques.</p>\n\n<pre><code class=\"language-ts bad\">// Bad\ntype CoffeeResponse = Latte|Americano|undefined;\n\nclass CoffeeService {\n  getLatte(): CoffeeResponse { ... };\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">// Better\ntype CoffeeResponse = Latte|Americano;\n\nclass CoffeeService {\n  getLatte(): CoffeeResponse|undefined { ... };\n}\n</code></pre>\n\n<p><a id=\"optionals-vs-undefined-type\"></a></p>\n\n<h4 id=\"prefer-optional-over-undefined\" class=\"numbered\">Prefer optional over <code>|undefined</code></h4>\n\n<p>In addition, TypeScript supports a special construct for optional parameters and\nfields, using <code>?</code>:</p>\n\n<pre><code class=\"language-ts good\">interface CoffeeOrder {\n  sugarCubes: number;\n  milk?: Whole|LowFat|HalfHalf;\n}\n\nfunction pourCoffee(volume?: Milliliter) { ... }\n</code></pre>\n\n<p>Optional parameters implicitly include <code>|undefined</code> in their type. However, they\nare different in that they can be left out when constructing a value or calling\na method. For example, <code>{sugarCubes: 1}</code> is a valid <code>CoffeeOrder</code> because <code>milk</code>\nis optional.</p>\n\n<p>Use optional fields (on interfaces or classes) and parameters rather than a\n<code>|undefined</code> type.</p>\n\n<p>For classes preferably avoid this pattern altogether and initialize as many\nfields as possible.</p>\n\n<pre><code class=\"language-ts good\">class MyClass {\n  field = '';\n}\n</code></pre>\n\n<p><a id=\"structural-types-vs-nominal-types\"></a></p>\n\n<h3 id=\"use-structural-types\" class=\"numbered\">Use structural types</h3>\n\n<p>TypeScript's type system is structural, not nominal. That is, a value matches a\ntype if it has at least all the properties the type requires and the properties'\ntypes match, recursively.</p>\n\n<p>When providing a structural-based implementation, explicitly include the type at\nthe declaration of the symbol (this allows more precise type checking and error\nreporting).</p>\n\n<pre><code class=\"language-ts good\">const foo: Foo = {\n  a: 123,\n  b: 'abc',\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">const badFoo = {\n  a: 123,\n  b: 'abc',\n}\n</code></pre>\n\n<p>Use interfaces to define structural types, not classes</p>\n\n<pre><code class=\"language-ts good\">interface Foo {\n  a: number;\n  b: string;\n}\n\nconst foo: Foo = {\n  a: 123,\n  b: 'abc',\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">class Foo {\n  readonly a: number;\n  readonly b: number;\n}\n\nconst foo: Foo = {\n  a: 123,\n  b: 'abc',\n}\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>The <q>badFoo</q> object above relies on type inference. Additional fields could be\nadded to <q>badFoo</q> and the type is inferred based on the object itself.</p>\n\n<p>When passing a <q>badFoo</q> to a function that takes a <q>Foo</q>, the error will be at\nthe function call site, rather than at the object declaration site. This is also\nuseful when changing the surface of an interface across broad codebases.</p>\n\n<pre><code class=\"language-ts\">interface Animal {\n  sound: string;\n  name: string;\n}\n\nfunction makeSound(animal: Animal) {}\n\n/**\n * 'cat' has an inferred type of '{sound: string}'\n */\nconst cat = {\n  sound: 'meow',\n};\n\n/**\n * 'cat' does not meet the type contract required for the function, so the\n * TypeScript compiler errors here, which may be very far from where 'cat' is\n * defined.\n */\nmakeSound(cat);\n\n/**\n * Horse has a structural type and the type error shows here rather than the\n * function call.  'horse' does not meet the type contract of 'Animal'.\n */\nconst horse: Animal = {\n  sound: 'niegh',\n};\n\nconst dog: Animal = {\n  sound: 'bark',\n  name: 'MrPickles',\n};\n\nmakeSound(dog);\nmakeSound(horse);\n</code></pre>\n\n</section> \n\n<p><a id=\"interfaces-vs-type-aliases\"></a></p>\n\n<h3 id=\"prefer-interfaces\" class=\"numbered\">Prefer interfaces over type literal aliases</h3>\n\n<p>TypeScript supports\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases\">type aliases</a>\nfor naming a type expression. This can be used to name primitives, unions,\ntuples, and any other types.</p>\n\n<p>However, when declaring types for objects, use interfaces instead of a type\nalias for the object literal expression.</p>\n\n<pre><code class=\"language-ts good\">interface User {\n  firstName: string;\n  lastName: string;\n}\n</code></pre>\n\n<pre><code class=\"language-ts bad\">type User = {\n  firstName: string,\n  lastName: string,\n}\n</code></pre>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>These forms are nearly equivalent, so under the principle of just choosing one\nout of two forms to prevent variation, we should choose one. Additionally, there\nare also\n<a href=\"https://ncjamieson.com/prefer-interfaces/\">interesting technical reasons to prefer interface</a>.\nThat page quotes the TypeScript team lead: <q>Honestly, my take is that it should\nreally just be interfaces for anything that they can model. There is no benefit\nto type aliases when there are so many issues around display/perf.</q></p>\n\n</section> \n\n<h3 id=\"arrayt-type\" class=\"numbered\"><code>Array&lt;T&gt;</code> Type</h3>\n\n<p>For simple types (containing just alphanumeric characters and dot), use the\nsyntax sugar for arrays, <code>T[]</code> or <code>readonly T[]</code>, rather than the longer form\n<code>Array&lt;T&gt;</code> or <code>ReadonlyArray&lt;T&gt;</code>.</p>\n\n<p>For multi-dimensional non-<code>readonly</code> arrays of simple types, use the syntax\nsugar form (<code>T[][]</code>, <code>T[][][]</code>, and so on) rather than the longer form.</p>\n\n<p>For anything more complex, use the longer form <code>Array&lt;T&gt;</code>.</p>\n\n<p>These rules apply at each level of nesting, i.e. a simple <code>T[]</code> nested in a more\ncomplex type would still be spelled as <code>T[]</code>, using the syntax sugar.</p>\n\n<pre><code class=\"language-ts good\">let a: string[];\nlet b: readonly string[];\nlet c: ns.MyObj[];\nlet d: string[][];\nlet e: Array&lt;{n: number, s: string}&gt;;\nlet f: Array&lt;string|number&gt;;\nlet g: ReadonlyArray&lt;string|number&gt;;\nlet h: InjectionToken&lt;string[]&gt;;  // Use syntax sugar for nested types.\nlet i: ReadonlyArray&lt;string[]&gt;;\nlet j: Array&lt;readonly string[]&gt;;\n</code></pre>\n\n<pre><code class=\"language-ts bad\">let a: Array&lt;string&gt;;  // The syntax sugar is shorter.\nlet b: ReadonlyArray&lt;string&gt;;\nlet c: Array&lt;ns.MyObj&gt;;\nlet d: Array&lt;string[]&gt;;\nlet e: {n: number, s: string}[];  // The braces make it harder to read.\nlet f: (string|number)[];         // Likewise with parens.\nlet g: readonly (string | number)[];\nlet h: InjectionToken&lt;Array&lt;string&gt;&gt;;\nlet i: readonly string[][];\nlet j: (readonly string[])[];\n</code></pre>\n\n<h3 id=\"indexable-key-string-type\" class=\"numbered\">Indexable types / index signatures (<code>{[key: string]: T}</code>)</h3>\n\n<p>In JavaScript, it's common to use an object as an associative array (aka <q>map</q>,\n<q>hash</q>, or <q>dict</q>). Such objects can be typed using an\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures\">index signature</a>\n(<code>[k: string]: T</code>) in TypeScript:</p>\n\n<pre><code class=\"language-ts\">const fileSizes: {[fileName: string]: number} = {};\nfileSizes['readme.txt'] = 541;\n</code></pre>\n\n<p>In TypeScript, provide a meaningful label for the key. (The label only exists\nfor documentation; it's unused otherwise.)</p>\n\n<pre><code class=\"language-ts bad\">const users: {[key: string]: number} = ...;\n</code></pre>\n\n<pre><code class=\"language-ts good\">const users: {[userName: string]: number} = ...;\n</code></pre>\n\n<blockquote>\n<p>Rather than using one of these, consider using the ES6 <code>Map</code> and <code>Set</code> types\ninstead. JavaScript objects have\n<a href=\"http://2ality.com/2012/01/objects-as-maps.html\">surprising undesirable behaviors</a>\nand the ES6 types more explicitly convey your intent. Also, <code>Map</code>s can be\nkeyed by—and <code>Set</code>s can contain—types other than <code>string</code>.</p>\n</blockquote>\n\n<p>TypeScript's builtin <code>Record&lt;Keys, ValueType&gt;</code> type allows constructing types\nwith a defined set of keys. This is distinct from associative arrays in that the\nkeys are statically known. See advice on that\n<a href=\"#mapped-conditional-types\">below</a>.</p>\n\n<h3 id=\"mapped-conditional-types\" class=\"numbered\">Mapped and conditional types</h3>\n\n<p>TypeScript's\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/mapped-types.html\">mapped types</a>\nand\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/conditional-types.html\">conditional types</a>\nallow specifying new types based on other types. TypeScript's standard library\nincludes several type operators based on these (<code>Record</code>, <code>Partial</code>, <code>Readonly</code>\netc).</p>\n\n<p>These type system features allow succinctly specifying types and constructing\npowerful yet type safe abstractions. They come with a number of drawbacks\nthough:</p>\n\n<ul>\n<li>Compared to explicitly specifying properties and type relations (e.g. using\ninterfaces and extension, see below for an example), type operators require\nthe reader to mentally evaluate the type expression. This can make programs\nsubstantially harder to read, in particular combined with type inference and\nexpressions crossing file boundaries.</li>\n<li>Mapped &amp; conditional types' evaluation model, in particular when combined\nwith type inference, is underspecified, not always well understood, and\noften subject to change in TypeScript compiler versions. Code can\n<q>accidentally</q> compile or seem to give the right results. This increases\nfuture support cost of code using type operators.</li>\n<li>Mapped &amp; conditional types are most powerful when deriving types from\ncomplex and/or inferred types. On the flip side, this is also when they are\nmost prone to create hard to understand and maintain programs.</li>\n<li>Some language tooling does not work well with these type system features.\nE.g. your IDE's find references (and thus rename property refactoring) will\nnot find properties in a <code>Pick&lt;T, Keys&gt;</code> type, and Code Search won't\nhyperlink them.</li>\n<li>\n</ul>\n\n<p>The style recommendation is:</p>\n\n<ul>\n<li>Always use the simplest type construct that can possibly express your code.</li>\n<li>A little bit of repetition or verbosity is often much cheaper than the long\nterm cost of complex type expressions.</li>\n<li>Mapped &amp; conditional types may be used, subject to these considerations.</li>\n</ul>\n\n<p>For example, TypeScript's builtin <code>Pick&lt;T, Keys&gt;</code> type allows creating a new\ntype by subsetting another type <code>T</code>, but simple interface extension can often be\neasier to understand.</p>\n\n<pre><code class=\"language-ts\">interface User {\n  shoeSize: number;\n  favoriteIcecream: string;\n  favoriteChocolate: string;\n}\n\n// FoodPreferences has favoriteIcecream and favoriteChocolate, but not shoeSize.\ntype FoodPreferences = Pick&lt;User, 'favoriteIcecream'|'favoriteChocolate'&gt;;\n</code></pre>\n\n<p>This is equivalent to spelling out the properties on <code>FoodPreferences</code>:</p>\n\n<pre><code class=\"language-ts\">interface FoodPreferences {\n  favoriteIcecream: string;\n  favoriteChocolate: string;\n}\n</code></pre>\n\n<p>To reduce duplication, <code>User</code> could extend <code>FoodPreferences</code>, or (possibly\nbetter) nest a field for food preferences:</p>\n\n<pre><code class=\"language-ts good\">interface FoodPreferences { /* as above */ }\ninterface User extends FoodPreferences {\n  shoeSize: number;\n  // also includes the preferences.\n}\n</code></pre>\n\n<p>Using interfaces here makes the grouping of properties explicit, improves IDE\nsupport, allows better optimization, and arguably makes the code easier to\nunderstand.</p>\n\n<h3 id=\"any\" class=\"numbered\"><code>any</code> Type</h3>\n\n<p>TypeScript's <code>any</code> type is a super and subtype of all other types, and allows\ndereferencing all properties. As such, <code>any</code> is dangerous - it can mask severe\nprogramming errors, and its use undermines the value of having static types in\nthe first place.</p>\n\n \n\n<section>\n\n<p><strong>Consider <em>not</em> to use <code>any</code>.</strong> In circumstances where you want to use <code>any</code>,\nconsider one of:</p>\n\n</section> \n\n<ul>\n<li><a href=\"#any-specific\">Provide a more specific type</a></li>\n<li><a href=\"#any-unknown\">Use <code>unknown</code></a></li>\n<li><a href=\"#any-suppress\">Suppress the lint warning and document why</a></li>\n</ul>\n\n<h4 id=\"any-specific\" class=\"numbered\">Providing a more specific type</h4>\n\n<p>Use interfaces , an\ninline object type, or a type alias:</p>\n\n<pre><code class=\"language-ts good\">// Use declared interfaces to represent server-side JSON.\ndeclare interface MyUserJson {\n  name: string;\n  email: string;\n}\n\n// Use type aliases for types that are repetitive to write.\ntype MyType = number|string;\n\n// Or use inline object types for complex returns.\nfunction getTwoThings(): {something: number, other: string} {\n  // ...\n  return {something, other};\n}\n\n// Use a generic type, where otherwise a library would say `any` to represent\n// they don't care what type the user is operating on (but note \"Return type\n// only generics\" below).\nfunction nicestElement&lt;T&gt;(items: T[]): T {\n  // Find the nicest element in items.\n  // Code can also put constraints on T, e.g. &lt;T extends HTMLElement&gt;.\n}\n</code></pre>\n\n<h4 id=\"any-unknown\" class=\"numbered\">Using <code>unknown</code> over <code>any</code></h4>\n\n<p>The <code>any</code> type allows assignment into any other type and dereferencing any\nproperty off it. Often this behaviour is not necessary or desirable, and code\njust needs to express that a type is unknown. Use the built-in type <code>unknown</code> in\nthat situation — it expresses the concept and is much safer as it does not allow\ndereferencing arbitrary properties.</p>\n\n<pre><code class=\"language-ts good\">// Can assign any value (including null or undefined) into this but cannot\n// use it without narrowing the type or casting.\nconst val: unknown = value;\n</code></pre>\n\n<pre><code class=\"language-ts bad\">const danger: any = value /* result of an arbitrary expression */;\ndanger.whoops();  // This access is completely unchecked!\n</code></pre>\n\n<section>\n\n<p>To safely use <code>unknown</code> values, narrow the type using a\n<a href=\"https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types\">type guard</a></p>\n\n</section> \n\n \n\n<h4 id=\"any-suppress\" class=\"numbered\">Suppressing <code>any</code> lint warnings</h4>\n\n<p>Sometimes using <code>any</code> is legitimate, for example in tests to construct a mock\nobject. In such cases, add a comment that suppresses the lint warning, and\ndocument why it is legitimate.</p>\n\n<pre><code class=\"language-ts good\">// This test only needs a partial implementation of BookService, and if\n// we overlooked something the test will fail in an obvious way.\n// This is an intentionally unsafe partial mock\n// tslint:disable-next-line:no-any\nconst mockBookService = ({get() { return mockBook; }} as any) as BookService;\n// Shopping cart is not used in this test\n// tslint:disable-next-line:no-any\nconst component = new MyComponent(mockBookService, /* unused ShoppingCart */ null as any);\n</code></pre>\n\n \n\n<h3 id=\"empty-interface-type\" class=\"numbered\"><code>{}</code> Type</h3>\n\n<p>The <code>{}</code> type, also known as an <em>empty interface</em> type, represents a interface\nwith no properties. An empty interface type has no specified properties and\ntherefore any non-nullish value is assignable to it.</p>\n\n<pre><code class=\"language-ts bad\">let player: {};\n\nplayer = {\n  health: 50,\n}; // Allowed.\n\nconsole.log(player.health) // Property 'health' does not exist on type '{}'.\n</code></pre>\n\n<pre><code class=\"language-ts bad\">function takeAnything(obj:{}) {\n\n}\n\ntakeAnything({});\ntakeAnything({ a: 1, b: 2 });\n</code></pre>\n\n<p>Google3 code <strong>should not</strong> use <code>{}</code> for most use cases. <code>{}</code> represents any\nnon-nullish primitive or object type, which is rarely appropriate. Prefer one of\nthe following more-descriptive types:</p>\n\n<ul>\n<li><code>unknown</code> can hold any value, including <code>null</code> or <code>undefined</code>, and is\ngenerally more appropriate for opaque values.</li>\n<li><code>Record&lt;string, T&gt;</code> is better for dictionary-like objects, and provides\nbetter type safety by being explicit about the type <code>T</code> of contained values\n(which may itself be <code>unknown</code>).</li>\n<li><code>object</code> excludes primitives as well, leaving only non-nullish functions and\nobjects, but without any other assumptions about what properties may be\navailable.</li>\n</ul>\n\n<h3 id=\"tuple-types\" class=\"numbered\">Tuple types</h3>\n\n<p>If you are tempted to create a Pair type, instead use a tuple type:</p>\n\n<pre><code class=\"language-ts bad\">interface Pair {\n  first: string;\n  second: string;\n}\nfunction splitInHalf(input: string): Pair {\n  ...\n  return {first: x, second: y};\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">function splitInHalf(input: string): [string, string] {\n  ...\n  return [x, y];\n}\n\n// Use it like:\nconst [leftHalf, rightHalf] = splitInHalf('my string');\n</code></pre>\n\n<p>However, often it's clearer to provide meaningful names for the properties.</p>\n\n<p>If declaring an <code>interface</code> is too heavyweight, you can use an inline object\nliteral type:</p>\n\n<pre><code class=\"language-ts good\">function splitHostPort(address: string): {host: string, port: number} {\n  ...\n}\n\n// Use it like:\nconst address = splitHostPort(userAddress);\nuse(address.port);\n\n// You can also get tuple-like behavior using destructuring:\nconst {host, port} = splitHostPort(userAddress);\n</code></pre>\n\n<h3 id=\"wrapper-types\" class=\"numbered\">Wrapper types</h3>\n\n<p>There are a few types related to JavaScript primitives that <em>should not</em> ever be\nused:</p>\n\n<ul>\n<li><code>String</code>, <code>Boolean</code>, and <code>Number</code> have slightly different meaning from the\ncorresponding primitive types <code>string</code>, <code>boolean</code>, and <code>number</code>. Always use\nthe lowercase version.</li>\n<li><code>Object</code> has similarities to both <code>{}</code> and <code>object</code>, but is slightly looser.\nUse <code>{}</code> for a type that include everything except <code>null</code> and <code>undefined</code>,\nor lowercase <code>object</code> to further exclude the other primitive types (the\nthree mentioned above, plus <code>symbol</code> and <code>bigint</code>).</li>\n</ul>\n\n<p>Further, never invoke the wrapper types as constructors (with <code>new</code>).</p>\n\n<h3 id=\"return-type-only-generics\" class=\"numbered\">Return type only generics</h3>\n\n<p>Avoid creating APIs that have return type only generics. When working with\nexisting APIs that have return type only generics always explicitly specify the\ngenerics.</p>\n\n \n\n<p><a id=\"appendices-style-related-tools\"></a></p>\n\n<h2 id=\"toolchain-requirements\" class=\"numbered\">Toolchain requirements</h2>\n\n<p>Google style requires using a number of tools in specific ways, outlined here.</p>\n\n<p><a id=\"clang-format\"></a>\n<a id=\"google-format\"></a>\n<a id=\"use-the-google3-formatter\"></a>\n<a id=\"source-code-formatting\"></a>\n<a id=\"appendices-clang-format\"></a>\n<a id=\"formatting\"></a>\n<a id=\"formatting-array-literals\"></a>\n<a id=\"formatting-block-indentation\"></a>\n<a id=\"formatting-column-limit\"></a>\n<a id=\"formatting-empty-blocks\"></a>\n<a id=\"formatting-function-expressions\"></a>\n<a id=\"formatting-nonempty-blocks\"></a>\n<a id=\"formatting-object-literals\"></a>\n<a id=\"formatting-one-statement-perline\"></a>\n<a id=\"formatting-statements\"></a>\n<a id=\"formatting-switch-statements\"></a>\n<a id=\"formatting-vertical-whitespace\"></a>\n<a id=\"formatting-whitespace\"></a></p>\n\n \n\n<h3 id=\"typescript-compiler\" class=\"numbered\">TypeScript compiler</h3>\n\n<p>All TypeScript files must pass type checking using the standard\n tool chain.</p>\n\n<h4 id=\"ts-ignore\" class=\"numbered\">@ts-ignore</h4>\n\n<p>Do not use <code>@ts-ignore</code> nor the variants <code>@ts-expect-error</code> or <code>@ts-nocheck</code>.</p>\n\n<section class=\"zippy\">\n\n<p>Why?</p>\n\n<p>They superficially seem to be an easy way to <q>fix</q> a compiler error, but in\npractice, a specific compiler error is often caused by a larger problem that can\nbe fixed more directly.</p>\n\n<p>For example, if you are using <code>@ts-ignore</code> to suppress a type error, then it's\nhard to predict what types the surrounding code will end up seeing. For many\ntype errors, the advice in <a href=\"#any\">how to best use <code>any</code></a> is useful.</p>\n\n</section> \n\n \n\n<p>You may use <code>@ts-expect-error</code> in unit tests, though you generally <em>should not</em>.\n<code>@ts-expect-error</code> suppresses all errors. It's easy to accidentally over-match\nand suppress more serious errors. Consider one of:</p>\n\n<ul>\n<li>When testing APIs that need to deal with unchecked values at runtime, add\ncasts to the expected type or to <code>any</code> and add an explanatory comment. This\nlimits error suppression to a single expression.</li>\n<li>Suppress the lint warning and document why, similar to\n<a href=\"#any-suppress\">suppressing <code>any</code> lint warnings</a>.</li>\n</ul>\n\n \n\n \n\n<h3 id=\"conformance\" class=\"numbered\">Conformance</h3>\n\n<p>Google TypeScript includes several <em>conformance frameworks</em>,\n\n<a href=\"https://tsetse.info\">tsetse</a> and\n<a href=\"https://github.com/google/tsec\">tsec</a>.</p>\n\n \n\n<p>These rules are commonly used to enforce critical restrictions (such as defining\nglobals, which could break the codebase) and security patterns (such as using\n<code>eval</code> or assigning to <code>innerHTML</code>), or more loosely to improve code quality.</p>\n\n<p>Google-style TypeScript must abide by any applicable global or framework-local\nconformance rules.</p>\n\n \n\n \n\n<p><a id=\"jsdoc\"></a>\n<a id=\"formatting-comments\"></a></p>\n\n<h2 id=\"comments-documentation\" class=\"numbered\">Comments and documentation</h2>\n\n \n\n<h4 id=\"jsdoc-vs-comments\" class=\"numbered\">JSDoc versus comments</h4>\n\n<p>There are two types of comments, JSDoc (<code>/** ... */</code>) and non-JSDoc ordinary\ncomments (<code>// ...</code> or <code>/* ... */</code>).</p>\n\n<ul>\n<li>Use <code>/** JSDoc */</code> comments for documentation, i.e. comments a user of the\ncode should read.</li>\n<li>Use <code>// line comments</code> for implementation comments, i.e. comments that only\nconcern the implementation of the code itself.</li>\n</ul>\n\n<p>JSDoc comments are understood by tools (such as editors and documentation\ngenerators), while ordinary comments are only for other humans.</p>\n\n<p><a id=\"formatting-block-comment-style\"></a></p>\n\n<h4 id=\"multi-line-comments\" class=\"numbered\">Multi-line comments</h4>\n\n<p>Multi-line comments are indented at the same level as the surrounding code. They\n<em>must</em> use multiple single-line comments (<code>//</code>-style), not block comment style\n(<code>/* */</code>).</p>\n\n<pre><code class=\"language-ts good\">// This is\n// fine\n</code></pre>\n\n<pre><code class=\"language-ts bad\">/*\n * This should\n * use multiple\n * single-line comments\n */\n\n/* This should use // */\n</code></pre>\n\n<p>Comments are not enclosed in boxes drawn with asterisks or other characters.</p>\n\n \n\n<h3 id=\"jsdoc-general-form\" class=\"numbered\">JSDoc general form</h3>\n\n<p>The basic formatting of JSDoc comments is as seen in this example:</p>\n\n<pre><code class=\"language-ts good\">/**\n * Multiple lines of JSDoc text are written here,\n * wrapped normally.\n * @param arg A number to do something to.\n */\nfunction doSomething(arg: number) { … }\n</code></pre>\n\n<p>or in this single-line example:</p>\n\n<pre><code class=\"language-ts good\">/** This short jsdoc describes the function. */\nfunction doSomething(arg: number) { … }\n</code></pre>\n\n<p>If a single-line comment overflows into multiple lines, it <em>must</em> use the\nmulti-line style with <code>/**</code> and <code>*/</code> on their own lines.</p>\n\n<p>Many tools extract metadata from JSDoc comments to perform code validation and\noptimization. As such, these comments <em>must</em> be well-formed.</p>\n\n<h3 id=\"jsdoc-markdown\" class=\"numbered\">Markdown</h3>\n\n<p>JSDoc is written in Markdown, though it <em>may</em> include HTML when necessary.</p>\n\n<p>This means that tooling parsing JSDoc will ignore plain text formatting, so if\nyou did this:</p>\n\n<pre><code class=\"language-ts bad\">/**\n * Computes weight based on three factors:\n *   items sent\n *   items received\n *   last timestamp\n */\n</code></pre>\n\n<p>it will be rendered like this:</p>\n\n<pre><code>Computes weight based on three factors: items sent items received last timestamp\n</code></pre>\n\n<p>Instead, write a Markdown list:</p>\n\n<pre><code class=\"language-ts good\">/**\n * Computes weight based on three factors:\n *\n * - items sent\n * - items received\n * - last timestamp\n */\n</code></pre>\n\n<h3 id=\"jsdoc-tags\" class=\"numbered\">JSDoc tags</h3>\n\n<p>Google style allows a subset of JSDoc tags.  Most tags must occupy their own line, with the tag at the beginning\nof the line.</p>\n\n<pre><code class=\"language-ts good\">/**\n * The \"param\" tag must occupy its own line and may not be combined.\n * @param left A description of the left param.\n * @param right A description of the right param.\n */\nfunction add(left: number, right: number) { ... }\n</code></pre>\n\n<pre><code class=\"language-ts bad\">/**\n * The \"param\" tag must occupy its own line and may not be combined.\n * @param left @param right\n */\nfunction add(left: number, right: number) { ... }\n</code></pre>\n\n \n\n<h3 id=\"jsdoc-line-wrapping\" class=\"numbered\">Line wrapping</h3>\n\n<p>Line-wrapped block tags are indented four spaces. Wrapped description text <em>may</em>\nbe lined up with the description on previous lines, but this horizontal\nalignment is discouraged.</p>\n\n<pre><code class=\"language-ts good\">/**\n * Illustrates line wrapping for long param/return descriptions.\n * @param foo This is a param with a particularly long description that just\n *     doesn't fit on one line.\n * @return This returns something that has a lengthy description too long to fit\n *     in one line.\n */\nexports.method = function(foo) {\n  return 5;\n};\n</code></pre>\n\n<p>Do not indent when wrapping a <code>@desc</code> or <code>@fileoverview</code> description.</p>\n\n<h3 id=\"document-all-top-level-exports-of-modules\" class=\"numbered\">Document all top-level exports of modules</h3>\n\n<p>Use <code>/** JSDoc */</code> comments to communicate information to the users of your\ncode. Avoid merely restating the property or parameter name. You <em>should</em> also\ndocument all properties and methods (exported/public or not) whose purpose is\nnot immediately obvious from their name, as judged by your reviewer.</p>\n\n<p><strong>Exception:</strong> Symbols that are only exported to be consumed by tooling, such as\n@NgModule classes, do not require comments.</p>\n\n<h3 id=\"jsdoc-class-comments\" class=\"numbered\">Class comments</h3>\n\n<p>JSDoc comments for classes should provide the reader with enough information to\nknow how and when to use the class, as well as any additional considerations\nnecessary to correctly use the class. Textual descriptions may be omitted on the\nconstructor.</p>\n\n \n\n<h3 id=\"method-and-function-comments\" class=\"numbered\">Method and function comments</h3>\n\n<p>Method, parameter, and return descriptions may be omitted if they are obvious\nfrom the rest of the method’s JSDoc or from the method name and type signature.</p>\n\n<p>Method descriptions begin with a verb phrase that describes what the method\ndoes. This phrase is not an imperative sentence, but instead is written in the\nthird person, as if there is an implied <q>This method ...</q> before it.</p>\n\n<h3 id=\"parameter-property-comments\" class=\"numbered\">Parameter property comments</h3>\n\n<p>A\n<a href=\"https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties\">parameter property</a>\nis a constructor parameter that is prefixed by one of the modifiers <code>private</code>,\n<code>protected</code>, <code>public</code>, or <code>readonly</code>. A parameter property declares both a\nparameter and an instance property, and implicitly assigns into it. For example,\n<code>constructor(private readonly foo: Foo)</code>, declares that the constructor takes a\nparameter <code>foo</code>, but also declares a private readonly property <code>foo</code>, and\nassigns the parameter into that property before executing the remainder of the\nconstructor.</p>\n\n<p>To document these fields, use JSDoc's <code>@param</code> annotation. Editors display the\ndescription on constructor calls and property accesses.</p>\n\n \n\n<pre><code class=\"language-ts good\">/** This class demonstrates how parameter properties are documented. */\nclass ParamProps {\n  /**\n   * @param percolator The percolator used for brewing.\n   * @param beans The beans to brew.\n   */\n  constructor(\n    private readonly percolator: Percolator,\n    private readonly beans: CoffeeBean[]) {}\n}\n</code></pre>\n\n<pre><code class=\"language-ts good\">/** This class demonstrates how ordinary fields are documented. */\nclass OrdinaryClass {\n  /** The bean that will be used in the next call to brew(). */\n  nextBean: CoffeeBean;\n\n  constructor(initialBean: CoffeeBean) {\n    this.nextBean = initialBean;\n  }\n}\n</code></pre>\n\n<p><a id=\"omit-comments-that-are-redundant-with-typescript\"></a>\n<a id=\"do-not-use-override\"></a></p>\n\n<h3 id=\"jsdoc-type-annotations\" class=\"numbered\">JSDoc type annotations</h3>\n\n<p>JSDoc type annotations are redundant in TypeScript source code. Do not declare\ntypes in <code>@param</code> or <code>@return</code> blocks, do not write <code>@implements</code>, <code>@enum</code>,\n<code>@private</code>, <code>@override</code> etc. on code that uses the <code>implements</code>, <code>enum</code>,\n<code>private</code>, <code>override</code> etc. keywords.</p>\n\n \n\n<h3 id=\"redundant-comments\" class=\"numbered\">Make comments that actually add information</h3>\n\n<p>For non-exported symbols, sometimes the name and type of the function or\nparameter is enough. Code will <em>usually</em> benefit from more documentation than\njust variable names though!</p>\n\n<ul>\n<li><p>Avoid comments that just restate the parameter name and type, e.g.</p>\n\n<pre><code class=\"language-ts bad\">/** @param fooBarService The Bar service for the Foo application. */\n</code></pre></li>\n<li><p>Because of this rule, <code>@param</code> and <code>@return</code> lines are only required when\nthey add information, and <em>may</em> otherwise be omitted.</p>\n\n<pre><code class=\"language-ts good\">/**\n * POSTs the request to start coffee brewing.\n * @param amountLitres The amount to brew. Must fit the pot size!\n */\nbrew(amountLitres: number, logger: Logger) {\n  // ...\n}\n</code></pre></li>\n</ul>\n\n<p><a id=\"formatting-param-name-comments\"></a></p>\n\n<h4 id=\"comments-when-calling-a-function\" class=\"numbered\">Comments when calling a function</h4>\n\n<p>“Parameter name” comments should be used whenever the method name and parameter\nvalue do not sufficiently convey the meaning of the parameter.</p>\n\n<p>Before adding these comments, consider refactoring the method to instead accept\nan interface and destructure it to greatly improve call-site\nreadability.</p>\n\n<p><q>Parameter name</q> comments go before the parameter value, and include the\nparameter name and a <code>=</code> suffix:</p>\n\n<pre><code class=\"language-ts good\">someFunction(obviousParam, /* shouldRender= */ true, /* name= */ 'hello');\n</code></pre>\n\n<p>Existing code may use a legacy parameter name comment style, which places these\ncomments ~after~ the parameter value and omits the <code>=</code>. Continuing to use this\nstyle within the file for consistency is acceptable.</p>\n\n<pre><code class=\"language-ts\">someFunction(obviousParam, true /* shouldRender */, 'hello' /* name */);\n</code></pre>\n\n<h3 id=\"place-documentation-prior-to-decorators\" class=\"numbered\">Place documentation prior to decorators</h3>\n\n<p>When a class, method, or property have both decorators like <code>@Component</code> and\nJsDoc, please make sure to write the JsDoc before the decorator.</p>\n\n<ul>\n<li><p>Do not write JsDoc between the Decorator and the decorated statement.</p>\n\n<pre><code class=\"language-ts bad\">@Component({\n  selector: 'foo',\n  template: 'bar',\n})\n/** Component that prints \"bar\". */\nexport class FooComponent {}\n</code></pre></li>\n<li><p>Write the JsDoc block before the Decorator.</p>\n\n<pre><code class=\"language-ts good\">/** Component that prints \"bar\". */\n@Component({\n  selector: 'foo',\n  template: 'bar',\n})\nexport class FooComponent {}\n</code></pre></li>\n</ul>\n\n \n\n<h2 id=\"policies\" class=\"numbered\">Policies</h2>\n\n<p><a id=\"policies-be-consistent\"></a>\n<a id=\"policies-newly-added-code-use-google-style\"></a></p>\n\n<h3 id=\"consistency\" class=\"numbered\">Consistency</h3>\n\n<p>For any style question that isn't settled definitively by this specification, do\nwhat the other code in the same file is already doing (<q>be consistent</q>). If that\ndoesn't resolve the question, consider emulating the other files in the same\ndirectory.</p>\n\n<p>Brand new files <em>must</em> use Google Style, regardless of the style choices of\nother files in the same package. When adding new code to a file that is not in\nGoogle Style, reformatting the existing code first is recommended, subject to\nthe advice <a href=\"#reformatting-existing-code\">below</a>. If this reformatting is not\ndone, then new code <em>should</em> be as consistent as possible with existing code in\nthe same file, but <em>must not</em> violate the style guide.</p>\n\n<p><a id=\"policies-code-not-in-google-style\"></a>\n<a id=\"policies-reformatting-existing-code\"></a></p>\n\n<h4 id=\"reformatting-existing-code\" class=\"numbered\">Reformatting existing code</h4>\n\n<p>You will occasionally encounter files in the codebase that are not in proper\nGoogle Style. These may have come from an acquisition, or may have been written\nbefore Google Style took a position on some issue, or may be in non-Google Style\nfor any other reason.</p>\n\n<p>When updating the style of existing code, follow these guidelines.</p>\n\n<ol>\n<li>It is not required to change all existing code to meet current style\nguidelines. Reformatting existing code is a trade-off between code churn and\nconsistency. Style rules evolve over time and these kinds of tweaks to\nmaintain compliance would create unnecessary churn. However, if significant\nchanges are being made to a file it is expected that the file will be in\nGoogle Style.</li>\n<li>Be careful not to allow opportunistic style fixes to muddle the focus of a\nCL. If you find yourself making a lot of style changes that aren’t critical\nto the central focus of a CL, promote those changes to a separate CL.</li>\n</ol>\n\n \n\n \n\n<p><a id=\"policies-deprecation\"></a></p>\n\n<h3 id=\"deprecation\" class=\"numbered\">Deprecation</h3>\n\n<p>Mark deprecated methods, classes or interfaces with an <code>@deprecated</code> JSDoc\nannotation. A deprecation comment must include simple, clear directions for\npeople to fix their call sites.</p>\n\n \n\n<p><a id=\"policies-generated-code-mostly-exempt\"></a></p>\n\n<h3 id=\"generated-code\" class=\"numbered\">Generated code: mostly exempt</h3>\n\n<p>Source code generated by the build process is not required to be in Google\nStyle. However, any generated identifiers that will be referenced from\nhand-written source code must follow the naming requirements. As a special\nexception, such identifiers are allowed to contain underscores, which may help\nto avoid conflicts with hand-written identifiers.</p>\n\n \n\n<p><a id=\"goals\"></a></p>\n\n<h4 id=\"style-guide-goals\" class=\"numbered\">Style guide goals</h4>\n\n<p>In general, engineers usually know best about what's needed in their code, so if\nthere are multiple options and the choice is situation dependent, we should let\ndecisions be made locally. So the default answer should be <q>leave it out</q>.</p>\n\n<p>The following points are the exceptions, which are the reasons we have some\nglobal rules. Evaluate your style guide proposal against the following:</p>\n\n<ol>\n<li><p><strong>Code should avoid patterns that are known to cause problems, especially\nfor users new to the language.</strong></p>\n\n</li>\n<li><p><strong>Code across\nprojects should be consistent across\nirrelevant variations.</strong></p>\n\n<p>When there are two options that are equivalent in a superficial way, we\nshould consider choosing one just so we don't divergently evolve for no\nreason and avoid pointless debates in code reviews.</p>\n\n<p>Examples:</p>\n\n<ul>\n<li>The capitalization style of names.</li>\n<li><code>x as T</code> syntax vs the equivalent <code>&lt;T&gt;x</code> syntax (disallowed).</li>\n<li><code>Array&lt;[number, number]&gt;</code> vs <code>[number, number][]</code>.</li>\n</ul></li>\n<li><p><strong>Code should be maintainable in the long term.</strong></p>\n\n<p>Code usually lives longer than the original author works on it, and the\nTypeScript team must keep all of Google working into the future.</p>\n\n<p>Examples:</p>\n\n<ul>\n<li>We use software to automate changes to code, so code is autoformatted so\nit's easy for software to meet whitespace rules.</li>\n<li>We require a single set of compiler flags, so a given TS library can be\nwritten assuming a specific set of flags, and users can always safely\nuse a shared library.</li>\n<li>Code must import the libraries it uses (<q>strict deps</q>) so that a\nrefactor in a dependency doesn't change the dependencies of its users.</li>\n<li>We ask users to write tests. Without tests we cannot have confidence\nthat changes that we make to the language,  don't break users.</li>\n</ul></li>\n<li><p><strong>Code reviewers should be focused on improving the quality of the code, not\nenforcing arbitrary rules.</strong></p>\n\n<p>If it's possible to implement your rule as an\n\nautomated check that is often a good sign.\nThis also supports principle 3.</p>\n\n<p>If it really just doesn't matter that much -- if it's an obscure corner of\nthe language or if it avoids a bug that is unlikely to occur -- it's\nprobably worth leaving out.</p></li>\n</ol>\n\n \n\n<p><a id=\"appendices-legacy-exceptions\"></a>\n<a id=\"appendices-legacy-exceptions-declareLegacyNamespace\"></a>\n<a id=\"appendices-legacy-exceptions-forward-declare\"></a>\n<a id=\"appendices-legacy-exceptions-function\"></a>\n<a id=\"appendices-legacy-exceptions-goog-provide\"></a>\n<a id=\"appendices-legacy-exceptions-goog-provide-summary\"></a>\n<a id=\"appendices-legacy-exceptions-goog-scope\"></a>\n<a id=\"appendices-legacy-exceptions-module-get\"></a>\n<a id=\"appendices-legacy-exceptions-overview\"></a>\n<a id=\"appendices-legacy-exceptions-var\"></a>\n<a id=\"appendices-legacy-exceptions-var-const\"></a>\n<a id=\"appendices-legacy-exceptions-var-declare\"></a>\n<a id=\"appendices-legacy-exceptions-var-scope\"></a>\n<a id=\"features-classes-old-style\"></a></p>\n\n<div class=\"footnotes\">\n<hr>\n<ol>\n\n<li id=\"fn1\">\n<p>Namespace imports are often called 'module imports' <a href=\"#fnref1\" rev=\"footnote\">↩</a></p>\n</li>\n\n<li id=\"fn2\">\n<p>named imports are sometimes called 'destructuring\nimports' because they use similar syntax to\ndestructuring assignments. <a href=\"#fnref2\" rev=\"footnote\">↩</a></p>\n</li>\n\n</ol>\n</div>\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "vimscriptfull.xml",
    "content": "<?xml version = '1.0'?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google Vimscript Guide\">\n  <p class=\"revision\">\n\n    Revision 1.1\n  </p>\n\n  \n  <address>\n    Nate Soares<br/>\n    Artemis Sparks<br/>\n    David Barnett<br/>\n  </address>\n\n  <OVERVIEW>\n    <CATEGORY title=\"Background\">\n      <p>\n        This is the in-depth vimscript guide. If you're just a casual user\n        looking to write a plugin, the\n        <a href=\"vimscriptguide.html\">abbreviated style guide</a> is for you.\n      </p>\n      <p>\n        This rather rotund guide dives into justifications and clarifications.\n        It provides an idealized set of rules that are rather too draconian to\n        push on casual scripters.\n      </p>\n      \n      <p>\n        It's for users who want to know why certain decisions were made in the\n        abbreviated guide and who want to learn a thing or two about using\n        vimscript safely.\n      </p>\n      <p>\n        Fair warning: Vimscript is a maddening abyss. When you gaze into it, it\n        gazes also into you. Proceed with caution.\n      </p>\n    </CATEGORY>\n  </OVERVIEW>\n\n  <CATEGORY title=\"Portability\">\n    <p>\n      Vim is highly configurable. Users can change many of the default\n      settings, including the case sensitivity, the regular expression rules,\n      the substitution rules, and more. In order for your vimscript to work\n      for all users, follow these guidelines:\n    </p>\n    <ul>\n      <li>\n        Always prefix regular expressions with one of <code>\\m</code>,\n        <code>\\v</code>, <code>\\M</code>, or <code>\\V</code> (prefer\n        tersity)\n        <ul>\n          <li>\n            Users can change the global \"magic level\" of regular expressions.\n            This changes how atoms are parsed in regular expressions,\n            including <code>.</code>, <code>*</code>, and <code>{</code>.\n          </li>\n          <li>\n            Even if your regular expression does not contain characters which\n            are affected by the <code>magic</code> setting you must prefix it\n            with one of the magic control atoms. This future-proofs your\n            regular expression against other devs modifying it and forgetting\n            to add the control atom.\n          </li>\n          <li>\n            If you have no opinion about what type of regular expression to\n            use, prefer the one which makes your regular expression most\n            concise.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Avoid using <code>:s[ubstitute]</code> in scripts.\n        <ul>\n          <li>\n            <code>:substitute</code> moves the cursor.\n          </li>\n          <li>\n            <code>:substitute</code> outputs an error message when the match\n            does not exist.\n          </li>\n          <li>\n            The meaning of the <code>g</code> flag depends upon the\n            <code>gdefault</code> setting. If you do use\n            <code>:substitute</code> you must save <code>gdefault</code>, set\n            it to <code>0</code> or <code>1</code>, perform the substitution,\n            and then restore it.\n          </li>\n          <li>\n            Script authors who want a safe way to replace text in the buffer\n            are encouraged to use <code>maktaba#buffer#Replace</code>.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Always use case-explicit operators for strings (<code>=~#</code> and\n        <code>=~?</code>, never <code>=~</code>).\n        <ul>\n          <li>\n            This also applies to <code>!~ == != &gt; &gt;= &lt;</code> and\n            <code>&lt;=</code>\n          </li>\n          <li>\n            This only applies for strings. <code>==</code> and\n            <code>&gt;=</code> are fine for numbers, but <code>==#</code> and\n            <code>&gt;=#</code> must be used for strings.\n          </li>\n          <li>\n            The behavior of <code>=~</code> and friends is dependent upon the\n            <code>ignorecase</code> setting.\n          </li>\n          <li>\n            You may break this rule when you explicitly want to obey the\n            user's <code>ignorecase</code> setting. Be prepared to justify\n            your reasoning.\n          </li>\n        </ul>\n      </li>\n      <li>\n        When using regular expressions as arguments to functions, prepend them\n        with <code>\\c</code> or <code>\\C</code>.\n        <ul>\n          <li>\n            This forces case to be either explicitly matched or ignored.\n          </li>\n          <li>\n            This is recommended, but not required, when comparing regexes with\n            operators that specify case sensitivity (<code>=~#</code>, etc.).\n          </li>\n          <li>\n            This rule applies when your regexes are matching syntax, external\n            APIs, external messages, and most other cases.\n          </li>\n          <li>\n            It does not apply when matching text in the buffer. When matching\n            text in the buffer you should honor the <code>ignorecase</code>\n            setting.\n          </li>\n          <li>\n            You may also ignore this rule any time that you explicitly want to\n            honor the <code>ignorecase</code> setting. Be prepared to justify\n            your reasoning.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Always use <code>normal!</code> instead of <code>normal</code>.\n        <ul>\n          <li>\n            If you forgo the <code>!</code> the command will use the user's\n            key mappings and you have literally no idea what your macro will\n            do.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Always use the <code>noremap</code> family of commands.\n        <ul>\n          <li>\n            Your plugins generally shouldn't introduce mappings, but if they\n            do, the <code>map</code> command respects the users existing\n            mappings and could do anything.\n          </li>\n        </ul>\n      </li>\n      <li>\n        When using <code>catch</code>, match the error code rather than the\n        error text.\n        <ul>\n          <li>\n            The error text may be locale-dependant.\n          </li>\n          <li>\n            See <code>:help error-messages</code>.\n          </li>\n        </ul>\n      </li>\n    </ul>\n    <p>\n      In general, guard all commands and functions against user settings.\n    </p>\n    \n  </CATEGORY>\n  <CATEGORY title=\"Language Guide\">\n    <ul>\n      \n      \n      <li>\n        Line continuations: <strong>Yes</strong>\n        <ul>\n          \n          <li>\n            Plugins that support vi compatibility mode must save and restore\n            compatibility options as described in the\n            <strong>Errata section</strong> so line continuations work properly.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Exceptions: <strong>Yes, with caution</strong>\n        <ul>\n          <li>\n            Always use an error code in thrown exception messages.\n          </li>\n          <li>\n            Prefer the <code>maktaba#error</code> codes found in\n            <code>maktaba</code>.\n          </li>\n          <li>\n            Fall back to the vim error codes. See\n            <code>:help error-messages</code>.\n          </li>\n          <li>\n            Generate custom error messages using\n            <code>maktaba#error#Message</code>.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Global Variables: <strong>As configuration only</strong>\n        <ul>\n          <li>\n            See the plugin guide.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Messaging: <strong>As little as possible.</strong>\n        <ul>\n          <li>\n            Loud scripts are annoying.\n          </li>\n          <li>\n            Message the user when an error has occurred.\n          </li>\n          <li>\n            Message the user when an operation which takes a long time has\n            begun work.\n          </li>\n          <li>\n            Avoid messaging otherwise.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Type checking:\n        <strong>Use strict and explicit checks where possible.</strong>\n        <ul>\n          <li>\n            Vimscript has unsafe, unintuitive behavior when dealing with some\n            types. For instance, <code>0 == 'foo'</code> evaluates to true.\n          </li>\n          <li>\n            Use strict comparison operators where possible. When comparing\n            against a string literal, use the <code>is#</code> operator.\n            Otherwise, prefer <code>maktaba#value#IsEqual</code> or check\n            <code>type()</code> explicitly.\n          </li>\n          <li>\n            Check variable types explicitly before using them. Use functions\n            from <code>maktaba#ensure</code>, or check\n            <code>maktaba#value</code> or <code>type()</code> and throw your own\n            errors.\n          </li>\n          <li>\n            Use <code>:unlet</code> for variables that may change types,\n            particularly those assigned inside loops.\n          </li>\n        </ul>\n      </li>\n      <li>\n        FuncRefs: <strong>No in most cases.</strong>\n        <ul>\n          <li>\n            FuncRefs have inconsistently enforced naming restrictions.\n            (Functions can have names that FuncRefs can not.)\n          </li>\n          <li>\n            FuncRefs have inconsistent ability to be reassigned (in Vim\n            7.2 and before you must unlet a FuncRef before assigning it).\n          </li>\n          <li>\n            In most instances where a FuncRef is needed a string works\n            just as well: just pass the string that you would use to make\n            the FuncRef.\n          </li>\n          <li>\n            Consider using <code>maktaba#function</code> instead to create and\n            manipulate handles to functions.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Python: <strong>Sparingly</strong>\n        <ul>\n          \n          <li>\n            Hurts code reuse since python code embedded in python plugins is\n            awkward to share between plugins.\n          </li>\n          <li>\n            Using python introduces python language version dependencies, which\n            are likely to get stale.\n          </li>\n          <li>\n            Exception: It's reasonable to use python for plugin functionality\n            that needs to do work in the background, as vimscript can not do\n            this.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Ruby: <strong>No</strong>\n        <ul>\n          <li>\n            We can not assume ruby interoperability.\n          </li>\n          <li>\n            You shouldn't depend upon the version of the ruby language that the\n            user has installed.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Lua: <strong>No</strong>\n        <ul>\n          <li>\n            For the same reasons an Ruby.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Dict Functions: <strong>Encouraged</strong>\n        <ul>\n          <li>\n            Vimscript can attach functions to dictionaries. Such functions\n            have access to the <code>self</code> parameter which access\n            the dict state.\n          </li>\n          <li>\n            Use these where you would use a class in python.\n          </li>\n          <li>\n            Do not over-use this feature; it is not necessary for helper\n            functions or API functions, only for encapsulated objects.\n          </li>\n        </ul>\n      </li>\n    </ul>\n    <p>\n      All other language features are fair game.\n    </p>\n  </CATEGORY>\n  <CATEGORY title=\"Structure\">\n    <ul>\n      <li>\n        Provided functionality should be packed into modular plugins.\n        <ul>\n          <li>\n            Every function in your plugin should be specific to your\n            plugin.\n          </li>\n          <li>\n            General utility functions should be abstracted into library plugins.\n          </li>\n          <li>\n            Manage dependencies with <code>maktaba</code>.\n          </li>\n        </ul>\n      </li>\n      <li>\n        <code>plugin-names-like-this</code>\n        <ul>\n          <li>\n            Plugin names should be descriptive and concise.\n          </li>\n          \n          \n        </ul>\n      </li>\n      <li>\n        Each plugin must consist of one directory (or code repository), sharing\n        a name with the plugin (with a \"vim-\" prefix or \".vim\" suffix if\n        desired).\n      </li>\n      <li>\n        Plugin metadata should be declared in the addon-info.json format (see\n        the <a href=\"https://github.com/MarcWeber/vim-addon-manager/blob/master/doc/vim-addon-manager-additional-documentation.txt\">VAM documentation</a> for details).\n      </li>\n      <li>\n        Functions should go in the <code>autoload/</code> subdirectory of\n        your plugin.\n        <ul>\n          <li>\n            This allows them to be late-loaded, which speeds up startup\n            time.\n          </li>\n          <li>\n            This helps vim enforce namespacing conventions.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Each file in the <code>plugin/</code> or <code>instant/</code> directory\n        should begin with the boilerplate\n        <CODE_SNIPPET>\n          let [s:plugin, s:enter] = maktaba#plugin#Enter(expand('&lt;sfile&gt;:p'))\n          if !s:enter\n            finish\n          endif\n        </CODE_SNIPPET>\n        (This prevents re-entry and allows users to selectively disable\n        functionality.)\n      </li>\n      <li>\n        User configuration should be via plugin flags defined in\n        <code>instant/flags.vim</code>.\n        <ul>\n          <li>\n            Define flags with\n            <code>call s:plugin.Flag('FLAGNAME', DEFAULT_VALUE)</code>.\n          </li>\n          <li>\n            Users can configure these flags using the <code>:Glaive</code>\n            command (see <a href=\"https://github.com/google/glaive\">glaive</a>).\n          </li>\n        </ul>\n      </li>\n      <li>\n        Commands, autocommands, mappings, and settings changes should\n        occur either in the <code>plugin/</code> or the\n        <code>ftplugin/</code> subdirectories.\n        <ul>\n          <li>\n            All commands should be defined in <code>plugin/commands.vim</code>\n            or <code>ftplugin/</code> files.\n          </li>\n          <li>\n            Autocommands should be defined in <code>plugin/autocmds.vim</code>,\n            inside an augroup.\n          </li>\n          <li>\n            Mappings should be defined in <code>plugin/mappings.vim</code> and\n            will be disabled unless explicitly enabled by users.\n          </li>\n          <li>\n            If the plugin configures any standard vim settings, those should be\n            configured in <code>plugin/settings.vim</code> or\n            <code>instant/settings.vim</code>.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Avoid using the <code>after/</code> subdirectory.\n        <ul>\n          <li>\n            <code>after/</code> should be reserved for the user.\n          </li>\n          <li>\n            It is difficult for the user to add their own overrides when\n            plugins use <code>after/</code>.\n          </li>\n        </ul>\n      </li>\n    </ul>\n\n    <STYLEPOINT title=\"Libraries vs. Functionality\">\n      <SUMMARY>\n        Separate library-providing plugins from command-providing plugins.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Many plugins provide either user functionality (commands,\n          autocommands, etc) or an API (of autoloaded functions) but not both.\n          This separation is encouraged, as it allows other plugins to pull in a\n          library without also pulling in commands, setting changes, and other\n          plugin functionality that affects the end user.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Configuration\">\n      <SUMMARY>\n        Don't clobber user settings. Provide as much configurability as\n        possible: that's what Vim's all about.\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            Use maktaba flags for plugin configuration. Users can configure them\n            using the <code>:Glaive</code> command.\n            \n          </li>\n          <li>\n            Check if configuration variables exist before setting them.\n            <CODE_SNIPPET>\n              if !exists('g:myplugin_option')\n                let g:myplugin_option = 1\n              endif\n            </CODE_SNIPPET>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n  <CATEGORY title=\"Style Guide\">\n    <p>\n      Follow google-wide style conventions. Mimic google python style when\n      in doubt.\n    </p>\n\n    \n\n    <STYLEPOINT title=\"Documentation\">\n      <SUMMARY>\n        Use <a href=\"https://github.com/google/vimdoc\">vimdoc</a>.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Provide help files generated by\n          <a href=\"https://github.com/google/vimdoc\">vimdoc</a>. Write\n          documentation in .vim files in conformance with the vimdoc standards\n          and include fields like \"description\" and \"author\" in the\n          addon-info.json file (see the\n          <a href=\"https://github.com/MarcWeber/vim-addon-manager/blob/master/doc/vim-addon-manager-additional-documentation.txt\">VAM documentation</a>).\n        </p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Whitespace\">\n      <SUMMARY>\n        Follow google-wide conventions.\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            Use two spaces for indents.\n          </li>\n          <li>\n            Do not use tabs.\n          </li>\n          <li>\n            Use spaces around operators except for arguments to commands.\n            <ul>\n              <li>\n                Using spaces around operators for commands is often invalid\n                syntax. This is inconsistently enforced by vimscript. To be\n                safe, always omit whitespace around arguments to commands.\n              </li>\n              <li>\n                <CODE_SNIPPET>\n                  let s:variable = \"concatenated \" . \"strings\"\n                  command -range=% MyCommand\n                </CODE_SNIPPET>\n                <BAD_CODE_SNIPPET>\n                  let s:variable=\"concatenated \".\"strings\"\n                  command -range = % MyCommand\n                </BAD_CODE_SNIPPET>\n              </li>\n            </ul>\n          </li>\n          <li>\n            Do not introduce trailing whitespace.\n            <ul>\n              <li>\n                You need not go out of your way to remove it.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Restrict lines to 80 columns wide.\n          </li>\n          <li>\n            Indent continued lines by two tabs (four spaces).\n          </li>\n          <li>\n            Do not waste whitespace aligning common segments of similar\n            commands. It is both difficult and expensive to maintain.\n            <ul>\n              <li>\n                <CODE_SNIPPET>\n                  command -bang MyCommand call myplugin#foo()\n                  command MyCommand2 call myplugin#bar()\n                </CODE_SNIPPET>\n                <BAD_CODE_SNIPPET>\n                  command -bang MyCommand  call myplugin#foo()\n                  command       MyCommand2 call myplugin#bar()\n                </BAD_CODE_SNIPPET>\n              </li>\n            </ul>\n          </li>\n        </ul>\n        <SUBSECTION title=\"Line Continuations\">\n          <ul start=\"7\">\n            <li>\n              Prefer line continuations on semantic boundaries.\n              <ul>\n                <li>\n                  <CODE_SNIPPET>\n                    command SomeLongCommand\n                        \\ call some#function()\n                  </CODE_SNIPPET>\n                  <BAD_CODE_SNIPPET>\n                    command SomeLongCommand call\n                        \\ some#function()\n                  </BAD_CODE_SNIPPET>\n                </li>\n                <li>\n                  Use your best judgement.\n                </li>\n              </ul>\n            </li>\n            <li>\n              Place one space after the backslash denoting a line continuation.\n              <ul>\n                <li>\n                  When continuing a multi-line command a pipe can be substituted\n                  for this space as necessary, as follows:\n                  <CODE_SNIPPET>\n                    autocommand BufEnter &lt;buffer&gt;\n                        \\ if !empty(s:var)\n                        \\|  call some#function()\n                        \\|else\n                        \\|  call some#function(s:var)\n                        \\|endif\n                  </CODE_SNIPPET>\n                </li>\n              </ul>\n            </li>\n            <li>\n              Do not continue multi-line commands when you can avoid it. Prefer\n              function calls.\n            </li>\n          </ul>\n        </SUBSECTION>\n        <SUBSECTION title=\"Comments\">\n          <ul>\n            <li>\n              Place a space after the <code>\"</code> before the comment text.\n              <ul>\n                <li>\n                  <CODE_SNIPPET>\n                    \" I am a line comment.\n                    call call(s:my_function)\n                  </CODE_SNIPPET>\n                </li>\n              </ul>\n            </li>\n            <li>\n              Do not use inline comments.\n              <ul>\n                <li>\n                  Some commands treat them as comments and others as unclosed\n                  quotes.  There are many edge cases. It's difficult to get\n                  right and difficult to maintain.\n                </li>\n                <li>\n                  Where you would use an inline comment, put a line comment on\n                  the line above.\n                </li>\n              </ul>\n            </li>\n            <li>\n              When leaving blank lines in comments, include the quote in the\n              blank line.\n              <ul>\n                <li>\n                  <CODE_SNIPPET>\n                    \" I am one continuous\n                    \"\n                    \" comment block\n                  </CODE_SNIPPET>\n                </li>\n              </ul>\n            </li>\n          </ul>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Variables\">\n      <SUMMARY>\n        <p>\n          <code>plugin-names-like-this</code>,\n          <code>FunctionNamesLikeThis</code>,\n          <code>CommandNamesLikeThis</code>,\n          <code>augroup_names_like_this</code>,\n          <code>variable_names_like_this</code>.\n        </p>\n        <p>\n          Prefix all variables with their scope.\n        </p>\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            <code>variable_names_like_this</code>\n            <ul>\n              <li>\n                FuncRef variables count as functions and should be named like\n                functions.\n              </li>\n              <li>\n                This (pathological) convention is enforced by vim itself.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Prefix global variables with <code>g:</code>\n            <ul>\n              <li>\n                Vimscript allows you to create global variables without\n                prefixing them.\n              </li>\n              <li>\n                It is very bad practice to introduce non-prefixed global\n                variables into scope.\n              </li>\n              <li>\n                Global variables should only be used for plugin configuration.\n              </li>\n              <li>\n                This does not apply to functions defined in\n                <code>autoload</code> directories.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Prefix script-local variables with <code>s:</code>\n            <ul>\n              <li>\n                This prevents namespace collisions between plugins.\n              </li>\n              <li>\n                This also applies to script-local functions.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Prefix function arguments with <code>a:</code>\n            <ul>\n              <li>\n                This is enforced by vim itself.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Prefix function-local variables with <code>l:</code>\n            <ul>\n              <li>\n                This is not enforced by vimscript but is good practice.\n              </li>\n              <li>\n                It helps you remember that all other variables must be\n                prefixed with scope.\n              </li>\n              <li>\n                <code>l:</code> disambiguates between function-local and\n                vim-predefined variables. For example, <code>count</code>\n                refers to\n                <code>v:count</code>, not <code>l:count</code>.\n              </li>\n              <li>\n                It future proofs your scripts against the introduction of new\n                vim-predefined variables.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Prefix pre-defined vim variables with <code>v:</code>\n            <ul>\n              <li>\n                This is not enforced by vimscript but is good practice.\n              </li>\n              <li>\n                It provides context as to where the (undeclared) variable is\n                coming from.\n              </li>\n              <li>\n                It reminds you that the variable can not be assigned to.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Prefix buffer-local variables with <code>b:</code>\n            <ul>\n              <li>\n                This is useful for plugins that keep per-buffer state.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Strings\">\n      <SUMMARY>\n        Prefer single quotes.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Prefer single quoted strings. Specifically, in order of precedence:\n        </p>\n        <ul>\n          <li>\n            Always use single quotes for regular expressions.\n            <ul>\n              <li>\n                <code>'\\s*'</code> is not the same as <code>\"\\s*\"</code>\n              </li>\n              <li>\n                Single quotes will prevent the need for excessive backslashes.\n              </li>\n              <li>\n                Double single quotes escape to one single quote in single\n                quoted strings: <code>'example ('')'</code> represents the\n                string\n                <code>example (')</code>\n              </li>\n            </ul>\n          </li>\n          <li>\n            If your string requires escape characters (<code>\\n</code>,\n            <code>\\t</code>, etc.) use double quotes.\n            <ul>\n              <li>\n                Escapes can not be expressed in single quoted strings.\n              </li>\n              <li>\n                Remember that <code>'\\n'</code> in a regex does not represent a\n                newline, but rather \"\\n\". You only need to use double quotes\n                when you want to embed the represented character itself (e.g. a\n                newline) in the string.\n              </li>\n            </ul>\n          </li>\n          <li>\n            If your string contains no escapes nor single quotes, use single\n            quoted strings.\n            <ul>\n              <li>\n                Most strings in vimscript are regexes, so this provides maximum\n                consistency.\n              </li>\n            </ul>\n          </li>\n          <li>\n            If your non-regex string contains single quotes but no double\n            quotes, use double quotes.\n            <ul>\n              <li>\n                Don't bother escaping strings if you don't have to.\n              </li>\n              <li>\n                This is similar to the python string rules.\n              </li>\n            </ul>\n          </li>\n          <li>\n            If your string contains both single and double quotes, use whichever\n            quoting style requires less escaping.\n            <ul>\n              <li>\n                Break ties in favor of single quotes.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Settings\">\n      <SUMMARY>\n        Prefer long names. Set settings locally.\n      </SUMMARY>\n      <BODY>\n        <ul start=\"6\">\n          <li>\n            Prefer long names of built in settings (i.e. <code>tabstop</code>\n            over\n            <code>ts</code>).\n          </li>\n          <li>\n            Set local settings unless you explicitly want to set global\n            settings.\n            <ul>\n              <li>\n                Use <code>setlocal</code> and <code>&amp;l:</code> instead of\n                <code>set</code> and <code>&amp;</code>.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n  <CATEGORY title=\"Usage Guide\">\n    <p>\n      Vim plugins should provide any or all of the following:\n      <strong>Commands,</strong> <strong>Autocommands,</strong>\n      <strong>Functions,</strong> <strong>Statusline Flags, and</strong>\n      <strong>Mappings.</strong>\n    </p>\n\n    <STYLEPOINT title=\"Commands\">\n      <SUMMARY>\n        <ul>\n          <li>Define in <code>plugin/commands.vim</code>.</li>\n          <li>CommandNamesLikeThis.</li>\n          <li>Prefer semantic names to a unified prefix.</li>\n          <li>Do not use <code>[!]</code></li>\n          <li>Extract logic into functions.</li>\n        </ul>\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            <code>CommandNamesLikeThis</code>\n          </li>\n          <li>\n            Commands should be defined in one block with no whitespace between\n            them.\n            <ul>\n              <li>\n                Name commands semantically at the expense of a common prefix.\n              </li>\n              <li>\n                <BAD_CODE_SNIPPET>\n                  command WhitespaceFixTrailing\n                  command WhitespaceFixIndentation\n                </BAD_CODE_SNIPPET>\n                <CODE_SNIPPET>\n                  command FixTrailingWhitespace\n                  command FixIndentation\n                </CODE_SNIPPET>\n              </li>\n            </ul>\n          </li>\n          <li>\n            Use <code>command</code> without a bang.\n            <ul>\n              <li>\n                This notifies users to command name conflicts immediately at\n                startup.\n              </li>\n              <li>\n                Command name collisions are an error and should not fail\n                silently.\n              </li>\n              <li>\n                Plugins are guarded against re-entry, so a single vim session\n                should never attempt to re-define defined commands.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Do not put logic in commands.\n            <ul>\n              <li>\n                Delegate to functions instead.\n              </li>\n              <li>\n                Pass non-argument command parameters (<code>&lt;bang&gt;</code>,\n                <code>&lt;register&gt;</code>, etc.) before argument parameters\n                (<code>&lt;f-args&gt;</code>, etc.).\n              </li>\n              <li>\n                Otherwise variable-length argument functions are difficult to\n                implement.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Do not autoload commands.\n            <ul>\n              <li>\n                Autoloaded commands will not be available until after a function\n                in the same file is called.\n              </li>\n              <li>\n                Commands intended to be used in the .vimrc should be defined in\n                a <code>instant/commands.vim</code> file in plugins using\n                maktaba, or explicitly installed via an autoload function in\n                non-maktaba plugins.\n              </li>\n            </ul>\n          </li>\n        </ul>\n        <SUBSECTION title=\"Conventions\">\n          <ul>\n            <li>\n              Pass <code>&lt;bang&gt;</code> to functions with\n              <code>'&lt;bang&gt;' == '!'</code>.\n              <ul>\n                <li>\n                  The function should receive a boolean parameter, not a string.\n                </li>\n              </ul>\n            </li>\n          </ul>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Autocommands\">\n      <SUMMARY>\n        <ul>\n          <li>Define in <code>plugin/autocmds.vim</code>.</li>\n          <li>Use augroups.</li>\n          <li>augroup_names_like_this.</li>\n          <li>Clear the augroup first.</li>\n          <li>Extract logic into functions.</li>\n        </ul>\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            All autocommands should be defined in the\n            <code>plugin/autocmds.vim</code> file.\n            <ul>\n              <li>\n                This allows users to disable your autocommands with\n                <code>Glaive myplugin !plugin[autocmds]</code>.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Declare all autocommands in an <code>augroup</code> block.\n            <ul>\n              <li>\n                This allows your autocommands to be cleared with\n                <code>autocmd!</code>.\n              </li>\n              <li>\n                If your plugin only has one <code>augroup</code>, the\n                <code>augroup</code> name should be the same as your plugin\n                name, with underscores in place of any hyphens.\n              </li>\n              <li>\n                Otherwise <code>augroup</code> names should start with your\n                plugin name followed by an underscore.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Do not put logic in autocommands.\n            <ul>\n              <li>\n                Delegate to functions instead.\n              </li>\n            </ul>\n          </li>\n          <li>\n            When creating a new <code>augroup</code>, clear it with\n            <code>autocmd!</code>\n            <ul>\n              <li>\n                This allows your plugins to be re-enterable.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Functions\">\n      <SUMMARY>\n        <ul>\n          <li>FunctionNamesLikeThis.</li>\n          <li>Autoload all functions.</li>\n          <li>Prefix script-local functions with <code>s:</code></li>\n          <li>Use <code>[!]</code>.</li>\n          <li>Use <code>[abort]</code>.</li>\n        </ul>\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            <code>FunctionNamesLikeThis</code>\n          </li>\n          <li>\n            Prefix all script-local functions with <code>s:</code>\n          </li>\n          <li>\n            Do not provide global functions. Use autoloaded functions instead.\n          </li>\n          <li>\n            Place two blank lines between top-level functions.\n          </li>\n          <li>\n            Declare all functions with <code>abort</code>.\n            <ul>\n              <li>\n                If you do not do this, the function's behavior depends upon\n                whether it is called within a <code>try..endtry</code> block\n                somewhere on the stack.\n              </li>\n              <li>\n                The <code>abort</code> keyword forces the function to act\n                consistently.\n              </li>\n              <li>\n                Without it, the function may (or may not) attempt to continue\n                execution after an error occurs.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Use <code>function!</code> with a bang.\n            <ul>\n              <li>\n                This allows developers to re-source their scripts and have the\n                functions reloaded without complaint.\n              </li>\n              <li>\n                Function names should never collide because functions should\n                always be either script-local or defined in an\n                <code>autoload</code> directory.\n              </li>\n              <li>\n                Failing to use a bang in any function in an autoload file will\n                lead to cryptic errors if vim tries to re-source the file\n                (e.g., if you refer to an nonexistent autoload function).\n              </li>\n            </ul>\n          </li>\n          <li>\n            Use <code>...</code> for optional arguments, not for lists of\n            arguments.\n            <ul>\n              <li>\n                Vimscript functions take at most 20 arguments.\n              </li>\n              <li>\n                Lists have no such length restriction.\n              </li>\n              <li>\n                Your function is likely to break when given too many arguments\n                if you use <code>...</code> for a list of arguments.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Throw exceptions rather than printing errors.\n            <ul>\n              <li>\n                Printed errors can not be caught.\n              </li>\n              <li>\n                Top-level functions expecting errors may catch them and print\n                error messages, but even those should throw their own errors\n                when they choke.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Mappings\">\n      <SUMMARY>\n        <ul>\n          <li>\n            Provide opt-in key mappings in <code>plugin/mappings.vim</code>.\n          </li>\n          <li>\n            <code>&lt;Plug&gt;</code> mappings can be defined in\n            <code>plugin/plugs.vim</code> (unlike mappings.vim, plugs.vim is\n            opt-out).\n          </li>\n        </ul>\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>\n            Define key mappings in <code>plugin/mappings.vim</code>, using\n            <code>maktaba#plugin#MapPrefix</code> to get a prefix.\n            <ul>\n              <li>\n                Mappings defined in the special <code>plugin/mappings.vim</code>\n                file will be disabled by default (by the standard\n                <code>maktaba#plugin#Enter()</code> boilerplate).\n              </li>\n              <li>\n                Users can enable key mappings with\n                <code>Glaive myplugin plugin[mappings]</code>.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Make all mappings with <code>&lt;unique&gt;</code>.\n            <ul>\n              <li>\n                This will inform the user when they have a mapping conflict\n                instead of silently clobbering their existing mappings.\n              </li>\n            </ul>\n          </li>\n          <li>\n            You may provide pseudo-mappings using <code>&lt;Plug&gt;</code> and\n            your plugin's name in <code>plugin/plugs.vim</code> (separate from\n            standard key mappings).\n            <ul>\n              <li>\n                <code>&lt;Plug&gt;</code> is a sequence which can not be typed.\n              </li>\n              <li>\n                You can do something like\n                <code>noremap &lt;Plug&gt;namespace#MappingName\n                  some_key_sequence</code>\n                and then users can do\n                <code>noremap &lt;leader&gt;x\n                  &lt;Plug&gt;namespace#MappingName</code>\n                to take advantage of your pseudo-mapping.\n              </li>\n              <li>\n                Pseudo-mappings should <strong>not</strong> be in\n                <code>plugin/mappings.vim</code> or they will be disabled by\n                default.\n              </li>\n              <li>\n                Such pseudo-mappings should be named <code>&lt;Plug&gt;</code>\n                followed by your plugin name, a pound sign, and a unique mapping\n                name (CamelCased like a function).\n              </li>\n            </ul>\n          </li>\n          <li>\n            Always use the <code>noremap</code> family of commands. Never use\n            the <code>map</code> family.\n            <ul>\n              <li>\n                <code>map</code> depends upon the user's existing mappings, and\n                could do anything.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Only use <code>noremap</code> for commands that both make a motion\n            and take a range.\n            <ul>\n              <li>\n                <code>noremap</code> makes mappings in normal, visual, and\n                operator-pending modes.\n              </li>\n              <li>\n                If you don't want all these use <code>nnoremap</code>\n                <code>onoremap</code> or <code>vnoremap</code> explicitly.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Always use <code>&lt;SID&gt;</code> in place of <code>s:</code> when\n            accessing script locals in mappings.\n            <ul>\n              <li>\n                Using <code>s:</code> will often fail as the mapping attempts to\n                type a literal s and colon.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n  <CATEGORY title=\"Conventions\">\n    <STYLEPOINT title=\"Dependency Checking\">\n      <SUMMARY>\n        Declare dependencies in addon-info.json and use <code>maktaba</code>.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Declaring dependencies in addon-info.json allows conformant plugin\n          managers (like VAM) to ensure dependencies are installed. See the\n          <a href=\"https://github.com/MarcWeber/vim-addon-manager/blob/master/doc/vim-addon-manager-additional-documentation.txt\">VAM documentation</a> for details.\n        </p>\n        <p>\n          Calling <code>maktaba#library#Require</code> from dependent code at\n          runtime ensures that dependencies have been installed and that they\n          don't include unsafe non-library files.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Statusline Flags\">\n      <SUMMARY>\n        Use <code>&lt;plugin-name&gt;#status#Status()</code> or its\n        finer-grained variants to provide statusline flags.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Following is a convention for exposing statusline flags to the user. A\n          plugin should never modify the user's statusline except for when that\n          is the only purpose of the plugin (powerline, etc.).\n        </p>\n        <ul>\n          <li>\n            Provide the\n            <code class=\"green\">Info</code>,\n            <code class=\"yellow\">Alert</code>,\n            <code class=\"orange\">Warning</code>, and\n            <code class=\"red\">Error</code> functions under the\n            <code>&lt;plugin-name&gt;#status</code> namespace.\n          </li>\n          <li>\n            <code class=\"green\">Info</code> should provide information about the\n            state of the buffer.\n            <ul>\n              <li>\n                Example: The current git branch.\n              </li>\n            </ul>\n          </li>\n          <li>\n            <code class=\"yellow\">Alert</code> should provide a quiet reminder\n            that the buffer is non-standard.\n            <ul>\n              <li>\n                Example: The readonly setting is on.\n              </li>\n            </ul>\n          </li>\n          <li>\n            <code class=\"orange\">Warning</code> should provide a warning about\n            the current state of the buffer.\n            <ul>\n              <li>\n                Example: The file has been edited elsewhere.\n              </li>\n            </ul>\n          </li>\n          <li>\n            <code class=\"red\">Error</code> should bring to attention a loud\n            issue with the buffer.\n            <ul>\n              <li>\n                Example: The file does not pass the syntax checker.\n              </li>\n            </ul>\n          </li>\n          <li>\n            By following these conventions, users can easily build up their own\n            statusline customizing the verbosity and colors to their tastes.\n          </li>\n          <li>\n            All functions should take no arguments and should return either\n            empty strings or strings enclosed by square brackets, e.g.\n            <code>[Google]</code>. For example:\n            <ul>\n              <li>\n                A trailing whitespace plugin might return <code>[$]</code> if\n                the file contains trailing whitespace\n              </li>\n              <li>\n                A prose writing plugin might return <code>[write]</code> if vim\n                is in writing mode.\n              </li>\n            </ul>\n          </li>\n          <li>\n            Consider providing the\n            <code>&lt;plugin-name&gt;#status#Status</code> function.\n            <ul>\n              <li>\n                It should return the first non-empty of <code>Error</code>,\n                <code>Warning</code>, <code>Alert</code>, or <code>Info</code>.\n              </li>\n              <li>\n                This is useful for users who want only the most relevant flag\n                and do not have a colored statusline.\n              </li>\n            </ul>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n  <CATEGORY title=\"Forbidden Commands\">\n    <p>\n      These are commands which can only be used by a limited number of\n      plugins, and should not in general be used by yours.\n    </p>\n    <ul>\n      <li>\n        Do not use <code>:match :2match</code> or <code>:3match</code>\n        <ul>\n          <li>\n            These are reserved for the user and for vim itself.\n          </li>\n          <li>\n            Use <code>matchadd()</code> to create a matchlevel unique to your\n            plugin.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Do not use <code>echoerr</code>.\n        <ul>\n          <li>\n            <code>echoerr</code> does not print the red error message that you\n            might think it does.\n          </li>\n          <li>\n            <code>echoerr</code> prints an error message as well as context\n            about the code where <code>echoerr</code> was called.\n          </li>\n          <li>\n            <code>echoerr</code> is best suited for debugging.\n          </li>\n          <li>\n            Use <code>echohl</code> in tandem with <code>echomsg</code>  if\n            you want the red error bar.\n          </li>\n        </ul>\n      </li>\n      <li>\n        Use <code>echomsg</code> instead of <code>echo</code>.\n        <ul>\n          <li>\n            <code>echomsg</code> messages can be reviewed with the\n            <code>:messages</code> command.\n          </li>\n          <li>\n            <code>echo</code> messages disappear permanently on redraw, which\n            can be very annoying to users who failed to read the message in\n            time.\n          </li>\n        </ul>\n      </li>\n    </ul>\n  </CATEGORY>\n  <CATEGORY title=\"Layout\">\n    <p>\n      Lay out <code>plugin/</code> files in the following sections, if\n      applicable, separated by two blank lines:\n    </p>\n    <ul>\n      <li>\n        Declaration of script constants\n      </li>\n      <li>\n        Declaration of configuration variables\n      </li>\n      <li>\n        Other declarations (commands in <code>commands.vim</code> file,\n        autocommands in <code>autocmds.vim</code> file, etc.)\n      </li>\n    </ul>\n    <p>\n      Lay out <code>autoload/</code> files in the following sections, if\n      applicable, separated by two blank lines:\n    </p>\n    <ul>\n      <li>\n        <code>maktaba#library#Require</code> calls\n      </li>\n      <li>\n        Script-local variables\n      </li>\n      <li>\n        Script-local functions\n      </li>\n      <li>\n        Private autoloaded functions\n      </li>\n      <li>\n        Public autoloaded functions\n      </li>\n    </ul>\n    <p>\n      This is recommended convention and is not enforced.\n    </p>\n\n  </CATEGORY>\n  <CATEGORY title=\"Recommended Shortcuts\">\n    \n    <p>\n      Use the following shortcuts:\n    </p>\n    <ul>\n      <li>\n        <code>catch</code> over <code>catch /.*/</code>\n      </li>\n      <li>\n        <code>return</code> over <code>return 0</code> when the return value\n        has no semantic purpose.\n      </li>\n    </ul>\n\n  </CATEGORY>\n  <CATEGORY title=\"Errata\">\n    <p>\n      This section plumbs some of the darker corners of vimscript, explaining\n      the language pathologies that you wish you didn't have to know.\n      \n    </p>\n\n    <STYLEPOINT title=\"Compatibility Mode\">\n      <SUMMARY>\n        If you don't support vi-compatibility mode, fail gracefully.\n      </SUMMARY>\n      <BODY>\n        <p>\n          When <code>compatible</code> is set, many vim features are not\n          available. The vim feature which most commonly affects vimscript\n          authors is line continuations.\n        </p>\n        <p>\n          If you want your plugin to work in vim with vi compatibility on, you\n          will need to save the compatibility options at the beginning of each\n          plugin file, clear them, and restore them at the end of each plugin\n          file. See <code>:help use-cpo-save</code> for details.\n        </p>\n        <p>\n          Plugins that depend on maktaba generally don't need to worry about\n          compatible mode since maktaba currently just disables it, printing a\n          warning.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n\n  <p align=\"right\">\n    Revision 1.1\n  </p>\n\n  \n  <address>\n    Nate Soares<br/>\n    Artemis Sparks<br/>\n    David Barnett<br/>\n  </address>\n</GUIDE>\n"
  },
  {
    "path": "vimscriptguide.xml",
    "content": "<?xml version = '1.0'?>\n<?xml-stylesheet type=\"text/xsl\" href=\"styleguide.xsl\"?>\n<GUIDE title=\"Google Vimscript Style Guide\">\n  <p class=\"revision\">\n\n    Revision 1.1\n  </p>\n\n  \n  <address>\n    Nate Soares<br/>\n    Artemis Sparks<br/>\n    David Barnett<br/>\n  </address>\n\n  <OVERVIEW>\n    <CATEGORY title=\"Background\">\n      <p>\n        This is a casual version of the vimscript style guide, because\n        vimscript is a casual language. When submitting vim plugin code, you\n        must adhere to these rules. For clarifications, justifications, and\n        explanations about the finer points of vimscript, please refer to the\n        <a href=\"vimscriptfull.xml\">heavy guide</a>.\n      </p>\n    </CATEGORY>\n  </OVERVIEW>\n\n  <CATEGORY title=\"Portability\">\n    <p>\n      It's hard to get vimscript right. Many commands depend upon the user's\n      settings. By following these guidelines, you can hope to make your\n      scripts portable.\n    </p>\n    <STYLEPOINT title=\"Strings\">\n      <SUMMARY>Prefer single quoted strings</SUMMARY>\n      <BODY>\n        <p>\n          Double quoted strings are semantically different in vimscript, and\n          you probably don't want them (they break regexes).\n        </p>\n        <p>\n          Use double quoted strings when you need an escape sequence (such as\n          <code>\"\\n\"</code>) or if you know it doesn't matter and you need to\n          embed single quotes.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Matching Strings\">\n      <SUMMARY>\n        Use the <code>=~#</code> or <code>=~?</code> operator families over the\n        <code>=~</code> family.\n      </SUMMARY>\n      <BODY>\n        <p>\n          The matching behavior depends upon the user's ignorecase and smartcase\n          settings and on whether you compare them with the <code>=~</code>,\n          <code>=~#</code>, or <code>=~?</code> family of operators. Use the\n          <code>=~#</code> and <code>=~?</code> operator families explicitly\n          when comparing strings unless you explicitly need to honor the user's\n          case sensitivity settings.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Regular Expressions\">\n      <SUMMARY>Prefix all regexes with <code>\\m\\C</code>.</SUMMARY>\n      <BODY>\n        <p>\n          In addition to the case sensitivity settings, regex behavior depends\n          upon the user's nomagic setting. To make regexes act like nomagic and\n          noignorecase are set, prepend all regexes with <code>\\m\\C</code>.\n        </p>\n        <p>\n          You are welcome to use other magic levels (<code>\\v</code>) and case\n          sensitivities (<code>\\c</code>) so long as they are intentional and\n          explicit.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Dangerous commands\">\n      <SUMMARY>Avoid commands with unintended side effects.</SUMMARY>\n      <BODY>\n        <p>\n          Avoid using <code>:s[ubstitute]</code> as it moves the cursor and\n          prints error messages. Prefer functions (such as\n          <code>search()</code>) better suited to scripts.\n        </p>\n        <p>\n          For many vim commands, functions exist that do the same thing with\n          fewer side effects. See <code>:help functions()</code> for a list of\n          built-in functions.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Fragile commands\">\n      <SUMMARY>Avoid commands that rely on user settings.</SUMMARY>\n      <BODY>\n        <p>\n          Always use <code>normal!</code> instead of <code>normal</code>. The\n          latter depends upon the user's key mappings and could do anything.\n        </p>\n        <p>\n          Avoid <code>:s[ubstitute]</code>, as its behavior depends upon a\n          number of local settings.\n        </p>\n        <p>\n          The same applies to other commands not listed here.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Catching Exceptions\">\n      <SUMMARY>Match error codes, not error text.</SUMMARY>\n      <BODY>\n        <p>Error text may be locale dependent.</p>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n\n  <CATEGORY title=\"General Guidelines\">\n    \n    \n    <STYLEPOINT title=\"Messaging\">\n      <SUMMARY>Message the user infrequently.</SUMMARY>\n      <BODY>\n        <p>\n          Loud scripts are annoying. Message the user only when:\n          <ul>\n            <li>A long-running process has kicked off.</li>\n            <li>An error has occurred.</li>\n          </ul>\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Type checking\">\n      <SUMMARY>Use strict and explicit checks where possible.</SUMMARY>\n      <BODY>\n        <p>\n          Vimscript has unsafe, unintuitive behavior when dealing with some\n          types. For instance, <code>0 == 'foo'</code> evaluates to true.\n        </p>\n        <p>\n          Use strict comparison operators where possible. When comparing against\n          a string literal, use the <code>is#</code> operator. Otherwise, prefer\n          <code>maktaba#value#IsEqual</code> or check <code>type()</code>\n          explicitly.\n        </p>\n        <p>\n          Check variable types explicitly before using them. Use functions from\n          <code>maktaba#ensure</code>, or check <code>maktaba#value</code> or\n          <code>type()</code> and throw your own errors.\n        </p>\n        <p>\n          Use <code>:unlet</code> for variables that may change types,\n          particularly those assigned inside loops.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Python\">\n      <SUMMARY>Use sparingly.</SUMMARY>\n      <BODY>\n        <p>\n          Use python only when it provides critical functionality, for example\n          when writing threaded code.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Other Languages\">\n      <SUMMARY>Use vimscript instead.</SUMMARY>\n      <BODY>\n        <p>\n          Avoid using other scripting languages such as ruby and lua. We can\n          not guarantee that the end user's vim has been compiled with support\n          for non-vimscript languages.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Boilerplate\">\n      <SUMMARY>\n        Use <a href=\"https://github.com/google/maktaba\">maktaba</a>.\n      </SUMMARY>\n      <BODY>\n        <p>\n          maktaba removes boilerplate, including:\n          <ul>\n            <li>Plugin creation</li>\n            <li>Error handling</li>\n            <li>Dependency checking</li>\n          </ul>\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Plugin layout\">\n      <SUMMARY>Organize functionality into modular plugins</SUMMARY>\n      <BODY>\n        <p>\n          Group your functionality as a plugin, unified in one directory (or\n          code repository) which shares your plugin's name (with a \"vim-\" prefix\n          or \".vim\" suffix if desired). It should be split into plugin/,\n          autoload/, etc. subdirectories as necessary, and it should declare\n          metadata in the addon-info.json format (see the\n          <a href=\"https://github.com/MarcWeber/vim-addon-manager/blob/master/doc/vim-addon-manager-additional-documentation.txt\">VAM documentation</a> for details).\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Functions\">\n      <SUMMARY>\n        In the autoload/ directory, defined with <code>[!]</code> and\n        <code>[abort]</code>.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Autoloading allows functions to be loaded on demand, which makes\n          startuptime faster and enforces function namespacing.\n        </p>\n        <p>\n          Script-local functions are welcome, but should also live in autoload/\n          and be called by autoloaded functions.\n        </p>\n        <p>\n          Non-library plugins should expose commands instead of functions.\n          Command logic should be extracted into functions and autoloaded.\n        </p>\n        <p>\n          <code>[!]</code> allows developers to reload their functions\n          without complaint.\n        </p>\n        <p>\n          <code>[abort]</code> forces the function to halt when it encounters\n          an error.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Commands\">\n      <SUMMARY>\n        In the plugin/commands.vim or under the ftplugin/ directory, defined\n        without <code>[!]</code>.\n      </SUMMARY>\n      <BODY>\n        <p>\n          General commands go in <code>plugin/commands.vim</code>.\n          Filetype-specific commands go in <code>ftplugin/</code>.\n        </p>\n        <p>\n          Excluding <code>[!]</code> prevents your plugin from silently\n          clobbering existing commands.  Command conflicts should be resolved by\n          the user.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Autocommands\">\n      <SUMMARY>\n        Place them in plugin/autocmds.vim, within augroups.\n      </SUMMARY>\n      <BODY>\n        <p>\n          Place all autocommands in augroups.\n        </p>\n        <p>\n          The augroup name should be unique. It should either be, or be prefixed\n          with, the plugin name.\n        </p>\n        <p>\n          Clear the augroup with <code>autocmd!</code> before defining new\n          autocommands in the augroup. This makes your plugin re-entrable.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Mappings\">\n      <SUMMARY>\n        Place them in <code>plugin/mappings.vim</code>, using\n        <code>maktaba#plugin#MapPrefix</code> to get a prefix.\n      </SUMMARY>\n      <BODY>\n        <p>\n          All key mappings should be defined in\n          <code>plugin/mappings.vim</code>.\n        </p>\n        <p>\n          Partial mappings (see :help using-&lt;Plug&gt;.) should be defined in\n          <code>plugin/plugs.vim</code>.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n    <STYLEPOINT title=\"Settings\">\n      <SUMMARY>Change settings locally</SUMMARY>\n      <BODY>\n        <p>\n          Use <code>:setlocal</code> and <code>&amp;l:</code> instead of\n          <code>:set</code> and <code>&amp;</code> unless you have explicit\n          reason to do otherwise.\n        </p>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n\n  <CATEGORY title=\"Style\">\n    <p>\n      Follow google style conventions. When in doubt, treat vimscript style\n      like python style.\n    </p>\n\n    <STYLEPOINT title=\"Whitespace\">\n      <SUMMARY>\n        Similar to python.\n        \n        <br/>\n        <br/>\n      </SUMMARY>\n      <BODY>\n        <ul>\n          <li>Use two spaces for indents</li>\n          <li>Do not use tabs</li>\n          <li>Use spaces around operators\n            <p>This does not apply to arguments to commands.</p>\n            <CODE_SNIPPET>\n              let s:variable = \"concatenated \" . \"strings\"\n              command -range=% MyCommand\n            </CODE_SNIPPET>\n          </li>\n          <li>Do not introduce trailing whitespace\n            <p>You need not go out of your way to remove it.</p>\n            <p>\n              Trailing whitespace is allowed in mappings which prep commands\n              for user input, such as\n              \"<code>noremap &lt;leader&gt;gf :grep -f </code>\".\n            </p>\n          </li>\n          <li>Restrict lines to 80 columns wide</li>\n          <li>Indent continued lines by four spaces</li>\n          <li>Do not align arguments of commands\n            <BAD_CODE_SNIPPET>\n              command -bang MyCommand  call myplugin#foo()\n              command       MyCommand2 call myplugin#bar()\n            </BAD_CODE_SNIPPET>\n            <CODE_SNIPPET>\n              command -bang MyCommand call myplugin#foo()\n              command MyCommand2 call myplugin#bar()\n            </CODE_SNIPPET>\n          </li>\n        </ul>\n      </BODY>\n    </STYLEPOINT>\n\n    <STYLEPOINT title=\"Naming\">\n      <SUMMARY>\n        <p>\n          In general, use\n          <code>plugin-names-like-this</code>,\n          <code>FunctionNamesLikeThis</code>,\n          <code>CommandNamesLikeThis</code>,\n          <code>augroup_names_like_this</code>,\n          <code>variable_names_like_this</code>.\n        </p>\n        <p>Always prefix variables with their scope.</p>\n      </SUMMARY>\n      <BODY>\n        <SUBSECTION title=\"plugin-names-like-this\">\n          <p>Keep them short and sweet.</p>\n          \n        </SUBSECTION>\n        <SUBSECTION title=\"FunctionNamesLikeThis\">\n          <p>Prefix script-local functions with <code>s:</code></p>\n          <p>Autoloaded functions may not have a scope prefix.</p>\n          <p>\n            Do not create global functions. Use autoloaded functions\n            instead.\n          </p>\n        </SUBSECTION>\n        <SUBSECTION title=\"CommandNamesLikeThis\">\n          <p>Prefer succinct command names over common command prefixes.</p>\n        </SUBSECTION>\n        <SUBSECTION title=\"variable_names_like_this\">\n          <p>Augroup names count as variables for naming purposes.</p>\n        </SUBSECTION>\n        <SUBSECTION title=\"Prefix all variables with their scope.\">\n          <ul>\n            <li>Global variables with <code>g:</code></li>\n            <li>Script-local variables with <code>s:</code></li>\n            <li>Function arguments with <code>a:</code></li>\n            <li>Function-local variables with <code>l:</code></li>\n            <li>Vim-predefined variables with <code>v:</code></li>\n            <li>Buffer-local variables with <code>b:</code></li>\n          </ul>\n          <p>\n            <code>g:</code>, <code>s:</code>, and <code>a:</code> must always\n            be used.\n          </p>\n          <p>\n            <code>b:</code> changes the variable semantics; use it when you\n            want buffer-local semantics.\n          </p>\n          <p>\n            <code>l:</code> and <code>v:</code> should be used for consistency,\n            future proofing, and to avoid subtle bugs. They are not strictly\n            required. Add them in new code but don’t go out of your way to add\n            them elsewhere.\n          </p>\n        </SUBSECTION>\n      </BODY>\n    </STYLEPOINT>\n  </CATEGORY>\n\n  <p align=\"right\">\n    Revision 1.1\n  </p>\n\n  \n  <address>\n    Nate Soares<br/>\n    Artemis Sparks<br/>\n    David Barnett<br/>\n  </address>\n</GUIDE>\n"
  },
  {
    "path": "xmlstyle.html",
    "content": "<link href=\"/styleguide/favicon.ico\" type=\"image/x-icon\" rel=\"shortcut icon\">\n<style type=\"text/css\">\n/* default css */\ntable {\nfont-size: 1em;\nline-height: inherit;\n}\ntr {\ntext-align: left;\n}\ndiv, address, ol, ul, li, option, select {\nmargin-top: 0px;\nmargin-bottom: 0px;\n}\np {\nmargin: 0px;\n}\nbody {\nmargin: 6px;\npadding: 0px;\nfont-family: Verdana, sans-serif;\nfont-size: 10pt;\nbackground-color: #ffffff;\n}\nimg {\n-moz-force-broken-image-icon: 1;\n}\n@media screen {\nhtml.pageview {\nbackground-color: #f3f3f3 !important;\n}\nbody {\nmin-height: 1100px;\ncounter-reset: __goog_page__;\n}\n* html body {\nheight: 1100px;\n}\n.pageview body {\nborder-top: 1px solid #ccc;\nborder-left: 1px solid #ccc;\nborder-right: 2px solid #bbb;\nborder-bottom: 2px solid #bbb;\nwidth: 648px !important;\nmargin: 15px auto 25px;\npadding: 40px 50px;\n}\n/* IE6 */\n* html {\noverflow-y: scroll;\n}\n* html.pageview body {\noverflow-x: auto;\n}\n/* Prevent repaint errors when scrolling in Safari. This \"Star-7\" css hack\ntargets Safari 3.1, but not WebKit nightlies and presumably Safari 4.\nThat's OK because this bug is fixed in WebKit nightlies/Safari 4 :-). */\nhtml*#wys_frame::before {\ncontent: '\\A0';\nposition: fixed;\noverflow: hidden;\nwidth: 0;\nheight: 0;\ntop: 0;\nleft: 0;\n}\n.writely-callout-data {\ndisplay: none;\n*display: inline-block;\n*width: 0;\n*height: 0;\n*overflow: hidden;\n}\n.writely-footnote-marker {\nbackground-image: url('images/footnote_doc_icon.gif');\nbackground-color: transparent;\nbackground-repeat: no-repeat;\nwidth: 7px;\noverflow: hidden;\nheight: 16px;\nvertical-align: top;\n-moz-user-select: none;\n}\n.editor .writely-footnote-marker {\ncursor: move;\n}\n.writely-footnote-marker-highlight {\nbackground-position: -15px 0;\n-moz-user-select: text;\n}\n.writely-footnote-hide-selection ::-moz-selection, .writely-footnote-hide-selection::-moz-selection {\nbackground: transparent;\n}\n.writely-footnote-hide-selection ::selection, .writely-footnote-hide-selection::selection {\nbackground: transparent;\n}\n.writely-footnote-hide-selection {\ncursor: move;\n}\n.editor .writely-comment-yellow {\nbackground-color: #FF9;\nbackground-position: -240px 0;\n}\n.editor .writely-comment-yellow-hover {\nbackground-color: #FF0;\nbackground-position: -224px 0;\n}\n.editor .writely-comment-blue {\nbackground-color: #C0D3FF;\nbackground-position: -16px 0;\n}\n.editor .writely-comment-blue-hover {\nbackground-color: #6292FE;\nbackground-position: 0 0;\n}\n.editor .writely-comment-orange {\nbackground-color: #FFDEAD;\nbackground-position: -80px 0;\n}\n.editor .writely-comment-orange-hover {\nbackground-color: #F90;\nbackground-position: -64px 0;\n}\n.editor .writely-comment-green {\nbackground-color: #99FBB3;\nbackground-position: -48px 0;\n}\n.editor .writely-comment-green-hover {\nbackground-color: #00F442;\nbackground-position: -32px 0;\n}\n.editor .writely-comment-cyan {\nbackground-color: #CFF;\nbackground-position: -208px 0;\n}\n.editor .writely-comment-cyan-hover {\nbackground-color: #0FF;\nbackground-position: -192px 0;\n}\n.editor .writely-comment-purple {\nbackground-color: #EBCCFF;\nbackground-position: -144px 0;\n}\n.editor .writely-comment-purple-hover {\nbackground-color: #90F;\nbackground-position: -128px 0;\n}\n.editor .writely-comment-magenta {\nbackground-color: #FCF;\nbackground-position: -112px 0;\n}\n.editor .writely-comment-magenta-hover {\nbackground-color: #F0F;\nbackground-position: -96px 0;\n}\n.editor .writely-comment-red {\nbackground-color: #FFCACA;\nbackground-position: -176px 0;\n}\n.editor .writely-comment-red-hover {\nbackground-color: #FF7A7A;\nbackground-position: -160px 0;\n}\n.editor .writely-comment-marker {\nbackground-image: url('images/markericons_horiz.gif');\nbackground-color: transparent;\npadding-right: 11px;\nbackground-repeat: no-repeat;\nwidth: 16px;\nheight: 16px;\n-moz-user-select: none;\n}\n.editor .writely-comment-hidden {\npadding: 0;\nbackground: none;\n}\n.editor .writely-comment-marker-hidden {\nbackground: none;\npadding: 0;\nwidth: 0;\n}\n.editor .writely-comment-none {\nopacity: .2;\nfilter:progid:DXImageTransform.Microsoft.Alpha(opacity=20);\n-moz-opacity: .2;\n}\n.editor .writely-comment-none-hover {\nopacity: .2;\nfilter:progid:DXImageTransform.Microsoft.Alpha(opacity=20);\n-moz-opacity: .2;\n}\n.br_fix br:not(:-moz-last-node):not(:-moz-first-node) {\nposition:relative;\nleft: -1ex\n}\n.br_fix br+br {\nposition: static !important\n}\n}\nh6 { font-size: 8pt }\nh5 { font-size: 8pt }\nh4 { font-size: 10pt }\nh3 { font-size: 12pt }\nh2 { font-size: 14pt }\nh1 { font-size: 18pt }\nblockquote {padding: 10px; border: 1px #DDD dashed }\na img {border: 0}\n.pb {\nborder-width: 0;\npage-break-after: always;\n/* We don't want this to be resizeable, so enforce a width and height\nusing !important */\nheight: 1px !important;\nwidth: 100% !important;\n}\n.editor .pb {\nborder-top: 1px dashed #C0C0C0;\nborder-bottom: 1px dashed #C0C0C0;\n}\ndiv.google_header, div.google_footer {\nposition: relative;\nmargin-top: 1em;\nmargin-bottom: 1em;\n}\n/* Table of contents */\n.editor div.writely-toc {\nbackground-color: #f3f3f3;\nborder: 1px solid #ccc;\n}\n.writely-toc > ol {\npadding-left: 3em;\nfont-weight: bold;\n}\nol.writely-toc-subheading {\npadding-left: 1em;\nfont-weight: normal;\n}\n/* IE6 only */\n* html writely-toc ol {\nlist-style-position: inside;\n}\n.writely-toc-none {\nlist-style-type: none;\n}\n.writely-toc-decimal {\nlist-style-type: decimal;\n}\n.writely-toc-upper-alpha {\nlist-style-type: upper-alpha;\n}\n.writely-toc-lower-alpha {\nlist-style-type: lower-alpha;\n}\n.writely-toc-upper-roman {\nlist-style-type: upper-roman;\n}\n.writely-toc-lower-roman {\nlist-style-type: lower-roman;\n}\n.writely-toc-disc {\nlist-style-type: disc;\n}\n/* Ordered lists converted to numbered lists can preserve ordered types, and\nvice versa. This is confusing, so disallow it */\nul[type=\"i\"], ul[type=\"I\"], ul[type=\"1\"], ul[type=\"a\"], ul[type=\"A\"] {\nlist-style-type: disc;\n}\nol[type=\"disc\"], ol[type=\"circle\"], ol[type=\"square\"] {\nlist-style-type: decimal;\n}\n/* end default css */\n/* custom css */\n/* end custom css */\n/* ui edited css */\nbody {\nfont-family: Verdana;\nfont-size: 10.0pt;\nline-height: normal;\nbackground-color: #ffffff;\n}\n/* end ui edited css */\n/* editor CSS */\n.editor a:visited {color: #551A8B}\n.editor table.zeroBorder {border: 1px dotted gray}\n.editor table.zeroBorder td {border: 1px dotted gray}\n.editor table.zeroBorder th {border: 1px dotted gray}\n.editor div.google_header, .editor div.google_footer {\nborder: 2px #DDDDDD dashed;\nposition: static;\nwidth: 100%;\nmin-height: 2em;\n}\n.editor .misspell {background-color: yellow}\n.editor .writely-comment {\nfont-size: 9pt;\nline-height: 1.4;\npadding: 1px;\nborder: 1px dashed #C0C0C0\n}\n/* end editor CSS */\n</style>\n<style>\nbody {\nmargin: 0px;\n}\n#doc-contents {\nmargin: 6px;\n}\n#google-view-footer {\nclear: both;\nborder-top: thin solid;\npadding-top: 0.3em;\npadding-bottom: 0.3em;\n}\na.google-small-link:link, a.google-small-link:visited {\ncolor:#112ABB;\nfont-family:Arial,Sans-serif;\nfont-size:11px !important;\n}\nbody, p, div, td {\ndirection: inherit;\n}\n@media print {\n#google-view-footer {\ndisplay: none;\n}\n}\n</style>\n<script>\nfunction viewOnLoad() {\nif (document.location.href.indexOf('spi=1') != -1) {\nif (navigator.userAgent.toLowerCase().indexOf('msie') != -1) {\nwindow.print();\n} else {\nwindow.setTimeout(window.print, 10);\n}\n}\nif (document.location.href.indexOf('hgd=1') != -1) {\nvar footer = document.getElementById(\"google-view-footer\");\nif (footer) {\nfooter.style.display = 'none';\n}\n}\n}\n</script>\n</head>\n<body>\n<div id=\"doc-contents\">\n<div>\n\n<h1 style=\"text-align: center;\">\nGoogle XML Document Format Style Guide</h1><div style=\"text-align: center;\">Version 1.0<br>Copyright Google 2008<br><br></div><h2>Introduction</h2>This document provides a set of guidelines for general use when designing new XML document formats (and to some extent XML documents as well; see Section 11).&nbsp; Document formats usually include both formal parts (DTDs, schemas) and parts expressed in normative English prose.<br><br>These guidelines apply to new designs, and are not intended to force retroactive changes in existing designs.&nbsp; When participating in the creation of public or private document format designs, the guidelines may be helpful but should not control the group consensus.<br><br>This guide is meant for the design of XML that is to be generated and consumed by machines rather than human beings.&nbsp; Its rules are <i>not applicable</i> to formats such as XHTML (which should be formatted as much like HTML as possible) or ODF which are meant to express rich text.&nbsp; A document that includes embedded content in XHTML or some other rich-text format, but also contains purely machine-interpretable portions, SHOULD follow this style guide for the machine-interpretable portions.&nbsp; It also does not affect XML document formats that are created by translations from proto buffers or through some other type of format.<br><br>Brief rationales have been added to most of the guidelines.&nbsp; They are maintained in the same document in hopes that they won't get out of date, but they are not considered normative.<br><br>The terms MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY are used in this document in the sense of <a title=\"RFC 2119\" href=\"https://www.ietf.org/rfc/rfc2119.txt\" id=\"iecm\">RFC 2119.</a><br>&nbsp;<br><h2>1. To design or not to design, that is the question<br></h2><ol><li>Attempt to reuse existing XML formats whenever possible, especially those which allow extensions.&nbsp; Creating an entirely new format should be done only with care and consideration; read <a title=\"Tim Bray's warnings\" href=\"https://www.tbray.org/ongoing/When/200x/2006/01/08/No-New-XML-Languages\" id=\"d3cy\">Tim Bray's warnings</a> first.&nbsp; Try to get wide review of your format, from outside your organization as well, if possible.&nbsp; [<i>Rationale:</i> New document formats have a cost: they must be reviewed, documented, and learned by users.]<br><br></li><li>If you are reusing or extending an existing format, make <i>sensible</i>\n\nuse of the prescribed elements and attributes, especially any that are\nrequired.&nbsp; Don't completely repurpose them, but do try to see how they\nmight be used in creative ways if the vanilla semantics aren't\nsuitable.&nbsp; As a last resort when an element or attribute is required by the format but is not appropriate for your use case, use some\nfixed string as its value.&nbsp; [<i>Rationale:</i>&nbsp; Markup reuse is good, markup abuse is bad.]<br><br></li><li>When extending formats, use the implicit style of the existing format, even if it contradicts this guide.&nbsp; [<i>Rationale: </i>Consistency.]<br></li></ol><br><h2>2. Schemas</h2><ol><li>Document formats SHOULD be expressed using a schema language.&nbsp; [<i>Rationale: </i>Clarity and machine-checkability.]<br><br></li><li>The schema language SHOULD be <a title=\"RELAX NG\" href=\"http://www.relaxng.org/\" id=\"p1s7\">RELAX NG</a> <a title=\"compact syntax\" href=\"http://www.relaxng.org/compact-tutorial-20030326.html\" id=\"ulci\">compact syntax</a>.&nbsp; Embedded <a title=\"Schematron\" href=\"http://www.schematron.com/\" id=\"ymh-\">Schematron</a> rules MAY be added to the schema for additional fine control.&nbsp; [<i>Rationale:</i>\n\nRELAX NG is the most flexible schema language, with very few arbitrary\nrestrictions on designs.&nbsp; The compact syntax is quite easy to read and\nlearn, and can be converted one-to-one to and from the XML syntax when\nnecessary.&nbsp; Schematron handles arbitrary cross-element and\ncross-attribute constraints nicely.]<br><br></li><li>Schemas SHOULD use the <a title=\"&quot;Salami Slice&quot; style\" href=\"http://www.xfront.com/GlobalVersusLocal.html#SecondDesign\" id=\"r:fj\">\"Salami Slice\" style</a> (one rule per element).&nbsp; Schemas MAY use the <a title=\"&quot;Russian Doll&quot; style\" href=\"http://www.xfront.com/GlobalVersusLocal.html#FirstDesign\" id=\"h14y\">\"Russian Doll\" style</a> (schema resembles document) if they are short and simple.&nbsp; The <a title=\"&quot;Venetian Blind&quot; style\" href=\"http://www.xfront.com/GlobalVersusLocal.html#ThirdDesign\" id=\"dr_g\">\"Venetian Blind\" style</a> (one rule per element type) is unsuited to RELAX NG and SHOULD NOT be used.<br><br></li><li>Regular expressions SHOULD be provided to assist in validating complex values.<br><br></li><li>DTDs and/or W3C XML Schemas MAY be provided for compatibility with existing products, tools, or users.&nbsp; [<i>Rationale:</i> We can't change the world all at once.]<br></li></ol></div><div><br><h2>3. Namespaces</h2><ol><li>Element names MUST be in a namespace, except\nwhen extending pre-existing document types that do not use namespaces.&nbsp;\n\nA default namespace SHOULD be used.&nbsp; [<i>Rationale:</i> Namespace-free\ndocuments are obsolete; every set of names should be in some\nnamespace.&nbsp; Using a default namespace improves readability.]<br><br></li><li>Attribute\nnames SHOULD NOT be in a namespace unless they are drawn from a foreign\ndocument type or are meant to be used in foreign document types.&nbsp; [<i>Rationale:</i> Attribute names in a namespace must always have a prefix, which is annoying to type and hard to read.]<br><br>\n</li><li>Namespace names are HTTP URIs.&nbsp; Namespace names SHOULD take the form <span style=\"font-family: Courier New;\">https://example.com/</span><i style=\"font-family: Courier New;\">whatever</i><span style=\"font-family: Courier New;\">/</span><i><span style=\"font-family: Courier New;\">year</span>, </i>where <i>whatever</i> is a unique value based on the name of the document type, and <i>year</i>\n\nis the year the namespace was created.&nbsp; There may be additional URI-path parts\nbefore the <i>year.</i>&nbsp; [<i>Rationale:</i> Existing convention.&nbsp; Providing the year allows for the possible recycling of code names.]<br><br></li><li>Namespaces MUST NOT be changed unless the semantics of particular elements or attributes has changed in drastically incompatible ways.&nbsp; [<i>Rationale:</i> Changing the namespace requires changing all client code.]<br><br></li><li>Namespace prefixes SHOULD be short (but not so short that they are likely to be conflict with another project).&nbsp; Single-letter prefixes MUST NOT be used. Prefixes SHOULD contain only lower-case ASCII letters.&nbsp; [<i>Rationale:</i> Ease of typing and absence of encoding compatibility problems.]</li></ol><br>\n\n<h2>4. Names and enumerated values</h2><b>Note: </b>\"Names\" refers to the names of elements, attributes, and enumerated values.<br><br><ol><li>All names MUST use lowerCamelCase. That is, they start with an initial lower-case letter, then each new word within the name starts with an initial capital letter. [<i>Rationale:</i> Adopting a single style provides consistency, which helps when referring to names since the capitalization is known and so does not have to be remembered.&nbsp; It matches Java style, and other languages can be dealt with using automated name conversion.]<br><br></li><li>Names MUST contain only ASCII letters and digits.&nbsp;\n[<i>Rationale:</i> Ease of typing and absence of encoding compatibility problems.]<br> <br></li><li>Names SHOULD NOT exceed 25 characters. Longer names SHOULD be\navoided by devising concise and informative names.&nbsp; If a name can only remain within this limit by becoming obscure, the limit SHOULD be ignored.&nbsp; [<i>Rationale: </i>Longer names are awkward to use and require additional bandwidth.]<br><br></li><li>Published standard abbreviations, if sufficiently well-known, MAY be employed in constructing names. Ad hoc abbreviations MUST NOT be used.&nbsp; Acronyms MUST be treated as words for camel-casing purposes: informationUri, not informationURI. [<i>Rationale:</i>&nbsp; An abbreviation that is well known\nto one community is often incomprehensible to others who need to use\nthe same document format (and who do understand the full name); treating an acronym as a word makes it easier to see where the word boundaries are.] <br></li></ol><p><br></p><p>\n\n</p><h2>\n5. Elements</h2><ol><li>All elements MUST contain either nothing, character content, or child elements.&nbsp; Mixed content MUST NOT be used.&nbsp; [<i>Rationale:</i> Many XML data models don't handle mixed content properly, and its use makes the element order-dependent.&nbsp; As always, textual formats are not covered by this rule.]<br><br></li><li>XML elements that merely wrap repeating child elements SHOULD NOT be used.&nbsp; [<i>Rationale:</i> They are not used in Atom and add nothing.]</li></ol>\n\n<p><br></p><h2>6. Attributes</h2><ol><li>Document formats MUST NOT depend on the order of attributes in a start-tag.&nbsp; [<i>Rationale:</i> Few XML parsers report the order, and it is not part of the XML Infoset.]<br><br></li><li>Elements SHOULD NOT be overloaded with too many attributes (no more\nthan 10 as a rule of thumb).&nbsp; Instead, use child elements to\nencapsulate closely related attributes.&nbsp; [<i>Rationale:</i> This\napproach maintains the built-in extensibility that XML provides with\nelements, and is useful for providing forward compatibility as a\nspecification evolves.]<br><br></li><li>Attributes MUST NOT be used to hold values in which line breaks are significant.&nbsp; [<i>Rationale:</i> Such line breaks are converted to spaces by conformant XML parsers.]<br><br></li><li>Document formats MUST allow either single or double quotation marks around attribute values.&nbsp; [<i>Rationale:</i>&nbsp; XML parsers don't report the difference.]<br></li></ol>\n\n<p><br></p>\n<p>\n</p><h2>\n7. Values</h2><ol><li>Numeric values SHOULD be 32-bit signed integers, 64-bit signed integers, or 64-bit IEEE doubles, all expressed in base 10.&nbsp; These correspond to the XML Schema types <span style=\"font-family: Courier New;\">xsd:int</span>, <span style=\"font-family: Courier New;\">xsd:long</span>, and <span style=\"font-family: Courier New;\">xsd:double</span> respectively.&nbsp; If required in particular cases, <span style=\"font-family: Courier New;\">xsd:integer</span> (unlimited-precision integer) values MAY also be used.&nbsp; [<i>Rationale:</i> There are far too many numeric types in XML Schema: these provide a reasonable subset.]&nbsp; <br><br></li><li>\n\nBoolean values SHOULD NOT be used (use enumerations instead).&nbsp; If they must be used, they MUST be expressed as <span style=\"font-family: Courier New;\">true</span> or <span style=\"font-family: Courier New;\">false</span>, corresponding to a subset of the XML Schema type <span style=\"font-family: Courier New;\">xsd:boolean</span>.&nbsp; The alternative <span style=\"font-family: Courier New;\">xsd:boolean</span> values <span style=\"font-family: Courier New;\">1</span> and <span style=\"font-family: Courier New;\">0</span> MUST NOT be used.&nbsp; [<i>Rationale:</i> Boolean arguments are not extensible.&nbsp; The additional flexibility of allowing numeric values is not abstracted away by any parser.]<br><br></li><li>Dates should be represented using <a title=\"RFC 3339\" href=\"https://www.ietf.org/rfc/rfc3339.txt\" id=\"sk98\">RFC 3339</a> format, a subset of both\nISO 8601 format and XML Schema <span style=\"font-family: Courier New;\">xsd:dateTime</span> format.&nbsp; UTC times SHOULD be used rather than local times.&nbsp;\n\n[<i>Rationale:</i> There are far too many date formats and time zones, although it is recognized that sometimes local time preserves important information.]<br><br></li><li>Embedded syntax in character content and attribute values SHOULD NOT be\nused.&nbsp; Syntax in values means XML tools are largely useless.&nbsp; Syntaxes such as&nbsp; dates, URIs, and\nXPath expressions are exceptions.&nbsp; [<i>Rationale:</i>&nbsp;\nUsers should be able to process XML documents using only an XML parser\nwithout requiring additional special-purpose parsers, which are easy to\nget wrong.]<br><br></li><li>Be careful with whitespace in values.&nbsp; XML parsers don't strip whitespace in elements, but do convert newlines to spaces in attributes.&nbsp; However, application frameworks may do more aggressive whitespace stripping.&nbsp; Your document format SHOULD give rules for whitespace stripping.<br></li></ol>\n\n<p><br>\n</p>\n<p>\n</p><h2>8. Key-value pairs<br></h2><ol><li>\nSimple key-value pairs SHOULD be represented with an empty element whose name represents the key, with the <span style=\"font-family: Courier New;\">value</span> attribute containing the value. Elements that have a <span style=\"font-family: Courier New;\">value</span> attribute MAY also have a <span style=\"font-family: Courier New;\">unit</span> attribute to specify the unit of a measured value.&nbsp; For physical measurements, the <a title=\"SI system\" href=\"https://en.wikipedia.org/wiki/International_System_of_Units\" id=\"rhxg\">SI system</a> SHOULD be used.&nbsp; [<i>Rationale:</i>\n\nSimplicity and design consistency.&nbsp; Keeping the value in an attribute\nhides it from the user, since displaying just the value without the key is not useful.]<br><br></li><li>If the number of possible keys is very large or unbounded, key-value pairs MAY be represented by a single generic element with <span style=\"font-family: Courier New;\">key</span>, <span style=\"font-family: Courier New;\">value</span>, and optional <span style=\"font-family: Courier New;\">unit</span> and <span style=\"font-family: Courier New;\">scheme</span>\nattributes (which serve to discriminate keys from different domains).&nbsp;\nIn that case, also provide (not necessarily in the same document) a\nlist of keys with human-readable explanations.</li></ol><br><h2>9. Binary data</h2><p><b>Note: </b>There are no hard and fast rules about whether binary data should be included as part of an XML document or not.&nbsp; If it's too large, it's probably better to link to it.</p><p><br></p><ol><li>Binary data MUST NOT be included directly as-is in XML documents, but MUST be encoded using Base64 encoding.&nbsp; [<i>Rationale:</i> XML does not allow arbitrary binary bytes.]<br><br></li><li>\n\nThe line breaks required by Base64 MAY be omitted.&nbsp; [<i>Rationale:</i> The line breaks are meant to keep plain text lines short, but XML is not really plain text.]<br><br></li><li>An attribute named <span style=\"font-family: Courier New;\">xsi:type</span> with value <span style=\"font-family: Courier New;\">xs:base64Binary</span> MAY be attached to this element to signal that the Base64 format is in use.&nbsp; [Rationale: Opaque blobs should have decoding instructions attached.]<br><br></li></ol>\n<h2>10. Processing instructions</h2><ol><li>New processing instructions MUST NOT be created except in order to specify purely local processing conventions, and SHOULD be avoided altogether.&nbsp; Existing standardized processing instructions MAY be used.&nbsp; [<i>Rationale:</i> Processing instructions fit awkwardly into XML data models and can always be replaced by elements; they exist primarily to avoid breaking backward compatibility.]</li></ol><p>&nbsp;</p>\n\n<p>\n</p><p>&nbsp;</p><h2>11. Representation of XML document instances<br></h2><p><b>Note:</b>&nbsp; These points are only guidelines, as the format of program-created instances will often be outside the programmer's control (for example, when an XML serialization library is being used).&nbsp; <i>In no case</i> should XML parsers rely on these guidelines being followed.&nbsp; Use standard XML parsers, not hand-rolled hacks.<br></p><p><br></p><ol><li>The character encoding used SHOULD be UTF-8.&nbsp; Exceptions should require extremely compelling circumstances.&nbsp; [<i>Rationale:</i> UTF-8 is universal and in common use.]<br><br></li><li>Namespaces SHOULD be declared in the root element of a document wherever possible.&nbsp; [<i>Rationale: </i>Clarity and consistency.]<br><br></li><li>The mapping of namespace URIs to prefixes SHOULD remain constant throughout the document, and SHOULD also be used in documentation of the design.&nbsp; [<i>Rationale: </i>Clarity and consistency.]<br><br></li><li>Well-known prefixes such as html: (for XHTML), dc: (for Dublin Core metadata), and xs: (for XML Schema) should be used for standard namespaces.&nbsp; [<i>Rationale:</i> Human readability.]<br><br></li><li>Redundant whitespace in a tag SHOULD NOT be\nused.&nbsp; Use one space before each attribute in a start-tag; if the start\ntag is too long, the space MAY be replaced by a newline.&nbsp; [<i>Rationale:</i> Consistency and conciseness.]<br><br></li><li>Empty elements MAY be expressed as empty tags or a start-tag\nimmediately followed by an end-tag. No distinction should be made\nbetween these two formats by any application.&nbsp; [<i>Rationale:</i> They are not distinguished by XML parsers.]<br><br></li><li>Documents MAY be pretty-printed using 2-space indentation for child\nelements.&nbsp; Elements that contain character content SHOULD NOT be\nwrapped.&nbsp; Long start-tags MAY be broken using newlines (possibly with extra indentation) after any attribute value except the last.&nbsp; [<i>Rationale:</i> General compatibility with our style.&nbsp; Wrapping character content affects its value.]<br><br></li><li>Attribute values MAY be surrounded with either quotation marks or apostrophes.\nSpecifications MUST NOT require or forbid the use of either form.&nbsp; <span style=\"font-family: Courier New;\">&amp;apos;</span> and <span style=\"font-family: Courier New;\">&amp;quot;</span> may be freely used to escape each type of quote.&nbsp; [<i>Rationale:</i> No XML parsers report the distinction.]<br><br>\n\n</li><li>Comments MUST NOT be used to carry real data.&nbsp; Comments MAY be used to contain TODOs in hand-written XML.&nbsp; Comments SHOULD NOT be used at all in publicly transmitted documents. [<i>Rationale:&nbsp; </i>Comments are often discarded by parsers.]<br><br></li><li>If comments are nevertheless used, they SHOULD appear only in the document prolog or in elements that\ncontain child elements.&nbsp; If pretty-printing is required, pretty-print\ncomments like elements, but with line wrapping.&nbsp; Comments SHOULD NOT\nappear in elements that contain character content.&nbsp; [<i>Rationale:&nbsp; </i>Whitespace in and around comments improves readability, but embedding a\ncomment in character content can lead to confusion about what\nwhitespace is or is not in the content.]<br><br></li><li>Comments SHOULD have whitespace following <span style=\"font-family: Courier New;\">&lt;!--</span> and preceding <span style=\"font-family: Courier New;\">--&gt;</span>.&nbsp; [<i>Rationale:</i> Readability.]<br><br></li><li>CDATA sections MAY be used; they are equivalent to the use of <span style=\"font-family: Courier New;\">&amp;amp;</span> and <span style=\"font-family: Courier New;\">&amp;lt;</span>.&nbsp; Specifications MUST NOT require or forbid the use of CDATA sections.&nbsp; [<i>Rationale:</i> Few XML parsers report the distinction, and combinations of CDATA and text are often reported as single objects anyway.]<br><br></li><li>Entity references other than the XML standard entity references <span style=\"font-family: Courier New;\">&amp;amp;</span>, <span style=\"font-family: Courier New;\">&amp;lt;</span>, <span style=\"font-family: Courier New;\">&amp;gt;</span>, <span style=\"font-family: Courier New;\">&amp;quot;</span>, and <span style=\"font-family: Courier New;\">&amp;apos;</span> MUST NOT be used.&nbsp; Character references MAY be used, but actual characters are preferred, unless the character encoding is not UTF-8.&nbsp; As usual, textual formats are exempt from this rule.<br></li></ol>\n\n<br><p>&nbsp;</p><p>\n</p>\n<p>\n</p><br><br><h2>\n12. Elements vs. Attributes\n</h2>\n<p>\n<b>Note:</b>&nbsp; There are no hard and fast rules for deciding when to use attributes and when to use elements.&nbsp; Here are some of the considerations that designers should take into account; no rationales are given.\n</p>\n<h3>\n12.1. General points:<br>\n</h3>\n\n<ol>\n<li>\n<p>\nAttributes are more restrictive than elements, and all designs have some elements, so an all-element design is simplest -- which is not the same as best.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nIn a tree-style data model, elements are typically represented internally as nodes, which use more memory than the strings used to represent attributes.&nbsp; Sometimes the nodes are of different application-specific classes, which in many languages also takes up memory to represent the classes.\n</p>\n<p>\n<br>\n\n</p>\n</li>\n<li>\n<p>\nWhen streaming, elements are processed one at a time (possibly even piece by piece, depending on the XML parser you are using), whereas all the attributes of an element and their values are reported at once, which costs memory, particularly if some attribute values are very long.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nBoth element content and attribute values need to be escaped appropriately, so escaping should not be a consideration in the design.\n</p>\n<p>\n<br>\n</p>\n\n</li>\n<li>\n<p>\nIn some programming languages and libraries, processing elements is easier; in others, processing attributes is easier.&nbsp; Beware of using ease of processing as a criterion.&nbsp; In particular, XSLT can handle either with equal facility.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nIf a piece of data should usually be shown to the user, consider using an element; if not, consider using an attribute.&nbsp; (This rule is often violated for one reason or another.)\n\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nIf you are extending an existing schema, do things by analogy to how things are done in that schema.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nSensible schema languages, meaning RELAX NG and Schematron, treat elements and attributes symmetrically.&nbsp; Older and cruder<a href=\"https://www.w3.org/TR/2004/REC-xmlschema-0-20041028/\" id=\"h2c3\" title=\"XML Schema\"> </a>schema languages such as DTDs and XML Schema, tend to have better support for elements.\n\n</p>\n</li>\n</ol>\n<p>\n</p>\n<h3>\n12.2 Using elements<br>\n</h3>\n<ol>\n<li>\n<p>\nIf something might appear more than once in a data model, use an element rather than introducing attributes with names like <span style=\"font-family: Courier New;\">foo1, foo2, foo3</span> ....\n</p>\n\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nUse elements to represent a piece of information that can be considered an independent object and when the information is related via a parent/child relationship to another piece of information.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nUse elements when data incorporates strict typing or relationship rules.\n</p>\n<p>\n\n<br>\n</p>\n</li>\n<li>\n<p>\nIf order matters between two pieces of data, use elements for them: attributes are inherently unordered.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nIf a piece of data has, or might have, its own substructure, use it in an element: getting substructure into an attribute is always messy.&nbsp; Similarly, if the data is a constituent part of some larger piece of data, put it in an element.\n</p>\n\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nAn exception to the previous rule: multiple whitespace-separated tokens can safely be put in an attribute.&nbsp; In principle, the separator can be anything, but schema-language validators are currently only able to handle whitespace, so it's best to stick with that.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nIf a piece of data extends across multiple lines, use an element: XML parsers will change newlines in attribute values into spaces.\n\n<br><br></p></li><li>If a piece of data is very large, use an element so that its content can be streamed.<br><br></li>\n<li>\n<p>\nIf a piece of data is in a natural language, put it in an element so you can use the <span style=\"font-family: Courier New;\">xml:lang</span> attribute to label the language being used.&nbsp; Some kinds of natural-language text, like Japanese, often make use <a href=\"https://www.w3.org/TR/2001/REC-ruby-20010531\" id=\"pa2f\" title=\"annotations\">annotations</a> that are conventionally represented using child elements; right-to-left languages like Hebrew and Arabic may similarly require child elements to manage <a href=\"https://www.w3.org/TR/2001/REC-ruby-20010531\" id=\"ehyv\" title=\"bidirectionality\">bidirectionality</a> properly.\n</p>\n\n<p>\n</p>\n</li>\n</ol>\n<h3>\n12.3 Using attributes<br>\n</h3>\n<ol>\n<li>\n<p>\nIf the data is a code from an enumeration, code list, or controlled vocabulary, put it in an attribute if possible.&nbsp; For example, language tags, currency codes, medical diagnostic codes, etc. are best handled as attributes.\n</p>\n<p>\n<br>\n\n</p>\n</li>\n<li>\n<p>\nIf a piece of data is really metadata on some other piece of data (for example, representing a class or role that the main data serves,&nbsp; or specifying a method of processing it), put it in an attribute if possible.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nIn particular, if a piece of data is an ID for some other piece of data, or a reference to such an ID, put the identifying piece in an attribute.&nbsp; When it's an ID, use the name <span style=\"font-family: Courier New;\">xml:id</span> for the attribute.\n\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\nHypertext references are conventionally put in <span style=\"font-family: Courier New;\">href</span> attributes.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n\n<p>\nIf a piece of data is applicable to an element and any descendant elements unless it is overridden in some of them, it is conventional to put it in an attribute.&nbsp; Well-known examples are <span style=\"font-family: Courier New;\">xml:lang</span>, <span style=\"font-family: Courier New;\">xml:space</span>, <span style=\"font-family: Courier New;\">xml:base</span>, and namespace declarations.\n</p>\n<p>\n<br>\n</p>\n</li>\n<li>\n<p>\n\nIf terseness is really the <i>most</i> important thing, use attributes, but consider <span style=\"font-family: Courier New;\">gzip</span> compression instead -- it works very well on documents with highly repetitive structures.</p></li>\n</ol></div><br><div><div><div><div><div>\n<br><h2>13. Parting words\n</h2>\n<p>\n</p><p>\nUse common sense and <i>BE CONSISTENT</i>.&nbsp;&nbsp; Design for extensibility.&nbsp; You <i>are</i> gonna need it.&nbsp; [<i>Rationale:</i> Long and painful experience.]<br></p><p><br> </p>\n\n<p>\nWhen designing XML formats, take a few minutes to look at other formats and determine their style.&nbsp; The point of having style guidelines is so that people can concentrate on what you are\nsaying, rather than on how you are saying it. <br></p><p>\n<br>\nBreak <i>ANY OR ALL</i> of these rules (yes, even the ones that say MUST) rather than create a crude, arbitrary, disgusting mess of a design if that's what following them slavishly would give you.&nbsp; In particular, random mixtures of attributes and child elements are hard to follow and hard to use, though it often makes good sense to use both when the data clearly fall into two different groups such as simple/complex or metadata/data.\n</p>\n<div><p>\n<br>\nNewbies always ask:\n</p>\n\n<p>\n&nbsp;&nbsp;&nbsp; \"Elements or attributes?\n</p>\n<p>\nWhich will serve me best?\"\n</p>\n<p>\n&nbsp;&nbsp;&nbsp; Those who know roar like lions;\n</p>\n<p>\n&nbsp;&nbsp;&nbsp; Wise hackers smile like tigers.\n</p>\n<p>\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; --a <a href=\"https://en.wikipedia.org/wiki/Waka_%28poetry%29#Forms_of_waka\" id=\"s3k3\" title=\"tanka\">tanka</a>, or extended haiku\n\n</p>\n</div>\n<p>\n<br>\n</p>\n<br>[TODO: if a registry of schemas is set up, add a link to it]<br><br></div><br></div><br></div></div></div><br>\n<br clear=\"all\"/>\n</div>\n"
  }
]