Google Style Guides

repository·gh-pages·Indexed 12 days ago

https://github.com/google/styleguide

A collection of official Google style guides for various programming languages and document formats to ensure consistency in codebases. Includes guidelines for C++, C#, Go, Java, Python, JavaScript, TypeScript, and others, as well as a documentation guide covering Markdown, README files, and XML document formats.

Tokens
77.4K
Snippets
211
Records
310
Agent score
98%

What's inside Google Style Guides

  1. Access Google Style Guides for various languages

    gh-pages

    This repository provides links to the official Google style guidelines used for various programming languages and document formats. These guides are intended for developers working on projects that originated at Google to ensure consistency in code style (e.g., naming conventions, variable usage, and error handling).

    Available Style Guides:

    • Web/Frontend: AngularJS, HTML/CSS, JavaScript, TypeScript
    • Systems/General Purpose: C++, C#, Go, Java, Objective-C, Python, R, Shell, Swift
    • Data/Markup: JSON, Markdown, XML
    • Other: Common Lisp, Vim script

    External Guides: Some guides are hosted outside this repository:

    • Effective Dart
    • Kotlin Style Guide
  2. Go Style Guide Principles

    gh-pages

    The Google Go Style Guide is built upon five overarching principles for writing readable code, listed in order of importance:

    1. Clarity: The code's purpose and rationale are clear to the reader.
    2. Simplicity: The code accomplishes its goal in the simplest way possible.
    3. Concision: The code maintains a high signal-to-noise ratio.
    4. Maintainability: The code is written to be easily maintained and modified.
    5. Consistency: The code is consistent with the broader Google codebase and internal package patterns.
  3. Understand the Go Style Guide documentation structure

    gh-pages

    The Go Style Guide is composed of three primary documents that serve different purposes for authors and reviewers:

    1. Style Guide: The definitive foundation of Go style at Google. It is both Normative (used to establish consistency) and Canonical (prescriptive and enduring rules). It is intended for everyone.
    2. Style Decisions: A verbose document summarizing specific style points and the reasoning behind them. It is Normative but not Canonical. It is primarily intended for Readability Mentors.
    3. Best Practices: Documents evolved patterns that solve common problems and improve robustness. It is neither Normative nor Canonical. It is intended for anyone interested in improving code uniformity.

    When working with existing codebases, you are encouraged to write new code using the latest best practices and address nearby style issues over time rather than causing large-scale churn to fix every violation.

  4. Access the Google documentation guide

    gh-pages

    The Google documentation guide provides a collection of styleguides and best practices for creating high-quality documentation. It is organized into several key areas:

    • Markdown styleguide: Rules for formatting and structure when using Markdown.
    • Best practices: General guidelines for effective documentation.
    • README files: Specific standards for writing README files.
    • Philosophy: The underlying principles that drive Google's documentation approach.
  5. Follow the Markdown style guide principles

    gh-pages

    The Markdown style guide aims to balance three goals:

    1. Source text is readable and portable.
    2. The Markdown corpus is maintainable over time and across teams.
    3. The syntax is simple and easy to remember.

    To maintain high-quality documentation, follow the Minimum Viable Documentation approach: identify essential docs (release, API, testing), keep them accurate, and frequently delete cruft in small batches.

  6. Understand the purpose of Go Style Best Practices

    gh-pages

    The Go Style Best Practices document provides auxiliary guidance on how to apply the core Go Style Guide to common, frequent development situations.

    Important Note: This document is neither normative nor canonical. It is intended to supplement the core style guide by discussing multiple alternative approaches and the trade-offs involved in choosing between them. For the authoritative rules, refer to the core Go Style Guide.

  7. Prefer functions over aliases in shell scripts

    gh-pages

    Avoid using aliases in shell scripts because they are difficult to quote, escape, and can lead to subtle bugs (e.g., evaluating variables at definition time rather than execution time). Instead, use shell functions, which provide a superset of alias functionality and handle arguments via $@.

    # AVOID: Aliases can evaluate variables prematurely
    alias random_name="echo some_prefix_${RANDOM}"
    
    # PREFER: Functions are more robust
    random_name() {
      echo "some_prefix_${RANDOM}"
    }
    
    # Functions handle arguments via $@
    fancy_ls() {
      ls -lh "$@"
    }
    # this evaluates $RANDOM once when the alias is defined,
    # so the echo'ed string will be the same on each invocation
    alias random_name="echo some_prefix_${RANDOM}"
    
    random_name() {
      echo "some_prefix_${RANDOM}"
    }
    
    # Note that unlike aliases function's arguments are accessed via $@
    fancy_ls() {
      ls -lh "$@"
    }
  8. Avoid using Python 'Power Features'

    gh-pages

    Avoid using highly flexible or 'fancy' Python features that make code harder to read, understand, and debug. While these features can make code more compact, they often lead to maintenance difficulties when revisiting the code.

    Features to avoid include:

    • Custom metaclasses
    • Access to bytecode
    • On-the-fly compilation
    • Dynamic inheritance
    • Object reparenting
    • Import hacks
    • Reflection (e.g., certain uses of getattr())
    • Modification of system internals
    • __del__ methods implementing customized cleanup

    Note: It is acceptable to use standard library modules and classes that internally use these features, such as abc.ABCMeta, dataclasses, and enum.

  9. Use Properties for trivial computations

    gh-pages

    Use the @property decorator to wrap method calls for getting or setting attributes as standard attribute access. Properties should only be used when they provide a clear advantage and match the expectations of typical attribute access (cheap, straightforward, and unsurprising).

    When to use:

    • To make an attribute read-only.
    • To allow lazy calculations.
    • To maintain a public interface while evolving internals.
    • To control attribute access for trivial derived values.

    When NOT to use:

    • If the property simply gets and sets an internal attribute without any computation (use a public attribute instead).
    • If the computation is expensive or has significant side effects.
    • If the computation is something a subclass might need to override or extend (inheritance with properties can be non-obvious).
    # Example of using the @property decorator
    @property
    def my_property(self):
        return self._internal_value
  10. Avoid custom context types

    gh-pages
    Do not create custom context types or use interfaces other than context.Context in function signatures. If you need to pass application data, use function parameters, receivers, globals, or Context values. Creating custom context types undermines the ability of the Go toolchain to work properly in production and makes refactoring nearly impossible.
  11. Naming Objective-C methods

    gh-pages

    Objective-C methods should be designed to read like a sentence.

    • General Pattern: Start with lowercase and use mixed case. Use prepositions like with, from, or to in subsequent parameters only when necessary for clarity.
    • Attributes: If a method returns an attribute of the receiver, name the method after the attribute (e.g., - (CGFloat)height;).
    • Accessors: Name the method the same as the object it retrieves. Do not use the get prefix (e.g., use - (id)delegate; instead of - (id)getDelegate;).
    • Booleans: Accessors for boolean adjectives should start with is. The corresponding property name should omit the is (e.g., @property(nonatomic, getter=isGlorious) BOOL glorious; results in the method - (BOOL)isGlorious;).
    • Dot Notation: Use dot notation only with property names, not with method names. Avoid using dot notation for method calls like enumerators or arrayWithObject:.
    // GOOD
    + (NSURL *)URLWithString:(NSString *)URLString;
    - (void)addTarget:(id)target action:(SEL)action;
    - (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
    - (CGFloat)height;
    - (id)delegate;
    
    // Boolean property/method pattern
    @property(nonatomic, getter=isGlorious) BOOL glorious;
    BOOL isGood = object.glorious; // GOOD
    BOOL isGood = [object isGlorious]; // GOOD
  12. Naming conventions for underscores in Go

    gh-pages

    In general, Go names should not contain underscores. There are three specific exceptions:

    1. Package names that are only imported by generated code.
    2. Test, Benchmark, and Example function names within *_test.go files.
    3. Low-level libraries (e.g., syscall) that interoperate with the operating system or cgo.

    Note: Filenames are not Go identifiers and may contain underscores.