### Custom TestMain Entrypoint for Common Setup/Teardown Source: https://google.github.io/styleguide/go/best-practices.html Provides a 'Good' example of using TestMain for common setup and teardown across all tests in a package, especially when setup is expensive and requires cleanup. ```go // Good: var db *sql.DB func TestInsert(t *testing.T) { /* omitted */ } func TestSelect(t *testing.T) { /* omitted */ } func TestUpdate(t *testing.T) { /* omitted */ } func TestDelete(t *testing.T) { /* omitted */ } // runMain sets up the test dependencies and eventually executes the tests. // It is defined as a separate function to enable the setup stages to clearly // defer their teardown steps. func runMain(ctx context.Context, m *testing.M) (code int, err error) { ctx, cancel := context.WithCancel(ctx) defer cancel() d, err := setupDatabase(ctx) if err != nil { return 0, err } defer d.Close() // Expressly clean up database. db = d // db is defined as a package-level variable. // m.Run() executes the regular, user-defined test functions. // Any defer statements that have been made will be run after m.Run() // completes. return m.Run(), nil } func TestMain(m *testing.M) { code, err := runMain(context.Background(), m) if err != nil { // Failure messages should be written to STDERR, which log.Fatal uses. log.Fatal(err) } // NOTE: defer statements do not run past here due to os.Exit // terminating the process. os.Exit(code) } ``` -------------------------------- ### Using Amortized Setup in Multiple Tests Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates how multiple test functions can call a common setup function (`mustLoadDataset`) to benefit from amortized setup costs. ```go // Good: func TestParseData(t *testing.T) { data := mustLoadDataset(t) // As documented above. } func TestListContents(t *testing.T) { data := mustLoadDataset(t) // As documented above. } func TestRegression682831(t *testing.T) { if got, want := guessOS("zpc79.example.com"), "grhat"; got != want { t.Errorf(`guessOS("zpc79.example.com") = %q, want %q`, got, want) } } ``` -------------------------------- ### Documenting Resource Cleanup with Example Source: https://google.github.io/styleguide/go/best-practices.html Explain how to clean up resources, especially when it might be unclear, by providing a clear example, such as closing a response body. ```go // Good: // Get issues a GET to the specified URL. // // When err is nil, resp always contains a non-nil resp.Body. // Caller should close resp.Body when done reading from it. // // resp, err := http.Get("http://example.com/") // if err != nil { // // handle error // } // defer resp.Body.Close() // body, err := io.ReadAll(resp.Body) func (c *Client) Get(url string) (resp *Response, err error) ``` -------------------------------- ### Variable Initialization Examples Source: https://google.github.io/styleguide/cppguide.html Shows examples of simple variable initialization, highlighting cases that depend on function or constructor behavior. ```cpp int n = 5; // Fine int m = f(); // ? (Depends on f) Foo x; Bar y = g(); // ? (Depends on g and on Bar::Bar) ``` -------------------------------- ### Running Specific Tests with Global Setup Source: https://google.github.io/styleguide/go/best-practices.html Shows how running a specific test might still incur the cost of global setup, even if the test doesn't use the setup resources. ```shell # No reason for this to perform the expensive initialization. $ go test -run TestRegression682831 ``` -------------------------------- ### Amortize Test Setup with sync.Once Source: https://google.github.io/styleguide/go/best-practices.html Use this pattern when common test setup is expensive, applies to only some tests, and does not require teardown. The setup cost is amortized across multiple test functions. ```go // Good: var dataset struct { once sync.Once data []byte err error } func mustLoadDataset(t *testing.T) []byte { t.Helper() dataset.once.Do(func() { data, err := os.ReadFile("path/to/your/project/testdata/dataset") // dataset is defined as a package-level variable. dataset.data = data dataset.err = err }) if err := dataset.err; err != nil { t.Fatalf("Could not load dataset: %v", err) } return dataset.data } ``` -------------------------------- ### Good: Data-driven test with separate Codex setup Source: https://google.github.io/styleguide/go/decisions.html This snippet demonstrates a good approach to data-driven testing where the test setup (Codex creation) is handled separately for each test function. This improves clarity by isolating the test logic from the setup variations. ```go // Good: type decodeCase struct { name string input string output string err error } func TestDecode(t *testing.T) { // setupCodex is slow as it creates a real Codex for the test. codex := setupCodex(t) var tests []decodeCase // rows omitted for brevity for _, test := range tests { t.Run(test.name, func(t *testing.T) { output, err := Decode(test.input, codex) if got, want := output, test.output; got != want { t.Errorf("Decode(%q) = %v, want %v", test.input, got, want) } if got, want := err, test.err; !cmp.Equal(got, want) { t.Errorf("Decode(%q) err %q, want %q", test.input, got, want) } }) } } func TestDecodeWithFake(t *testing.T) { // A fakeCodex is a fast approximation of a real Codex. codex := newFakeCodex() var tests []decodeCase // rows omitted for brevity for _, test := range tests { t.Run(test.name, func(t *testing.T) { output, err := Decode(test.input, codex) if got, want := output, test.output; got != want { t.Errorf("Decode(%q) = %v, want %v", test.input, got, want) } if got, want := err, test.err; !cmp.Equal(got, want) { t.Errorf("Decode(%q) err %q, want %q", test.input, got, want) } }) } } ``` -------------------------------- ### Go Package Comment - Multiline Example with Code Source: https://google.github.io/styleguide/go/decisions.html Multiline comments can be used instead of multiple single-line comments, especially useful for including sample command-lines or template examples. Code examples within comments should be indented. ```go // Good: /* The seed_generator command is a utility that generates a Finch seed file from a set of JSON study configs. seed_generator *.json | base64 > finch-seed.base64 */ package template ``` -------------------------------- ### Reference Link Example Source: https://google.github.io/styleguide/docguide/style.html Use reference links when the link destination is long, improving readability. This example shows a basic reference link setup. ```markdown In this example, the link destination is long enough that it makes sense to use a reference link: ``` The [style guide] says not to use reference links unless you have to. [style guide]: https://docs.google.com/document/d/13HQBxfhCwx8lVRuN2Wf6poqvAfVeEXmFVcawP5I6B3c/edit ``` ``` -------------------------------- ### Calling Scoped Setup in Tests Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates the correct way to call a scoped setup function within individual test functions that require its resources. ```go // Good: func TestParseData(t *testing.T) { data := mustLoadDataset(t) parsed, err := ParseData(data) if err != nil { t.Fatalf("Unexpected error parsing data: %v", err) } want := &DataTable{ /* ... */ } if got := parsed; !cmp.Equal(got, want) { t.Errorf("ParseData(data) = %v, want %v", got, want) } } func TestListContents(t *testing.T) { data := mustLoadDataset(t) contents, err := ListContents(data) if err != nil { t.Fatalf("Unexpected error listing contents: %v", err) } want := []string{ /* ... */ } if got := contents; !cmp.Equal(got, want) { t.Errorf("ListContents(data) = %v, want %v", got, want) } } func TestRegression682831(t *testing.T) { if got, want := guessOS("zpc79.example.com"), "grhat"; got != want { t.Errorf(`guessOS("zpc79.example.com") = %q, want %q`, got, want) } } ``` -------------------------------- ### Handle Exceptional Setup Failures in Go Tests Source: https://google.github.io/styleguide/go/best-practices.html Shows how to use t.Fatalf for exceptional setup failures in Go tests, such as failing to provision a modem for an opponent in a simulation. ```go func ExerciseGame(t *testing.T, cfg *Config, p chess.Player) error { t.Helper() if cfg.Simulation == Modem { conn, err := modempool.Allocate() if err != nil { t.Fatalf("No modem for the opponent could be provisioned: %v", err) } t.Cleanup(func() { modempool.Return(conn) }) } // Run acceptance test (a whole game). } ``` -------------------------------- ### Incorrect Global Test Setup Source: https://google.github.io/styleguide/go/best-practices.html Illustrates an anti-pattern where setup code is run globally (e.g., in init) and not scoped, potentially impacting tests that do not require the setup. ```go // Bad: var dataset []byte func TestParseData(t *testing.T) { // As documented above without calling mustLoadDataset directly. } func TestListContents(t *testing.T) { // As documented above without calling mustLoadDataset directly. } func TestRegression682831(t *testing.T) { if got, want := guessOS("zpc79.example.com"), "grhat"; got != want { t.Errorf(`guessOS("zpc79.example.com") = %q, want %q`, got, want) } } func init() { dataset = mustLoadDataset() } ``` -------------------------------- ### Comprehensive Import Example Source: https://google.github.io/styleguide/pyguide.html Demonstrates the recommended grouping and ordering of imports, including standard library, third-party, and repository sub-packages. ```python import collections import queue import sys from absl import app from absl import flags import bs4 import cryptography import tensorflow as tf from book.genres import scifi from myproject.backend import huxley from myproject.backend.hgwells import time_machine from myproject.backend.state_machine import main_loop from otherproject.ai import body from otherproject.ai import mind from otherproject.ai import soul # Older style code may have these imports down here instead: #from myproject.backend.hgwells import time_machine #from myproject.backend.state_machine import main_loop ``` -------------------------------- ### Runnable Example in Go Godoc Source: https://google.github.io/styleguide/go/best-practices.html Test files can contain runnable examples that appear attached to the corresponding documentation in godoc. This helps validate godoc formatting. ```go // Good: func ExampleConfig_WriteTo() { cfg := &Config{ Name: "example", } if err := cfg.WriteTo(os.Stdout); err != nil { log.Exitf("Failed to write config: %s", err) } // Output: // { // "name": "example" // } } ``` -------------------------------- ### Go Acceptance Test Structure Example Source: https://google.github.io/styleguide/go/best-practices.html A canonical example of a Go acceptance test structure, demonstrating how to instantiate a player and run an acceptance test function, reporting any errors. ```go // Good: package deepblue_test import ( "chesstest" "deepblue" ) func TestAcceptance(t *testing.T) { player := deepblue.New() err := chesstest.ExerciseGame(t, chesstest.SimpleGame, player) if err != nil { t.Errorf("Deep Blue player failed acceptance test: %v", err) } } ``` -------------------------------- ### Test Module Docstring Example in Python Source: https://google.github.io/styleguide/pyguide.html Module-level docstrings for test files are optional but recommended when providing additional information, such as how to run the test or unusual setup patterns. ```python """This blaze test uses golden files. You can update those files by running `blaze run //foo/bar:foo_test -- --update_golden_files` from the `google3` directory. """ ``` -------------------------------- ### Include Order Example Source: https://google.github.io/styleguide/cppguide.html Demonstrates the recommended order for include directives in C++ source files for better build break detection and organization. ```cpp #include "foo/server/fooserver.h" #include #include #include #include #include "base/basictypes.h" #include "foo/server/bar.h" #include "third_party/absl/flags/flag.h" ``` -------------------------------- ### Conditional Includes Example Source: https://google.github.io/styleguide/cppguide.html Shows how to handle system-specific code using conditional includes, which should be placed after other standard includes. ```cpp #include "foo/public/fooserver.h" #ifdef _WIN32 #include #endif // _WIN32 ``` -------------------------------- ### Good Documentation: Concise Context Cancellation Source: https://google.github.io/styleguide/go/best-practices.html This example demonstrates good documentation by omitting the implied behavior of returning an error when the context is cancelled. ```go // Good: // Run executes the worker's run loop. func (Worker) Run(ctx context.Context) error ``` -------------------------------- ### Table Formatting Example (Avoid) Source: https://google.github.io/styleguide/docguide/style.html This example demonstrates a poorly formatted table with unbalanced dimensions, rambling prose, and redundant columns. Avoid such structures. ```markdown DO NOT DO THIS Fruit | Metrics | Grows on | Acute curvature | Attributes | Notes ------ | -------- | -------- | ------------------ | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- Apple | Very popular | Trees | | [Juicy](http://cs/SomeReallyReallyReallyReallyReallyReallyReallyReallyLongQuery), Firm, Sweet | Apples keep doctors away. Banana | 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. ``` -------------------------------- ### File Header Comment Example Source: https://google.github.io/styleguide/objcguide.html An example of a file header comment including a description of the delegate's purpose and ownership. ```objc /** * A delegate for NSApplication to handle notifications about app * launch and shutdown. Owned by the main app controller. */ @interface MyAppDelegate : NSObject { /** * The background task in progress, if any. This is initialized * to the value UIBackgroundTaskInvalid. */ UIBackgroundTaskIdentifier _backgroundTaskID; } /** The factory that creates and manages fetchers for the app. */ @property(nonatomic) GTMSessionFetcherService *fetcherService; @end ``` -------------------------------- ### Objective-C Implementation Example Source: https://google.github.io/styleguide/objcguide.html Shows the correct commenting and spacing for the @implementation of an Objective-C interface. Includes private properties and method implementations. ```objc // GOOD: #import "Shared/Util/Foo.h" @implementation Foo { /** The string used for displaying "hi". */ NSString *_string; } + (instancetype)fooWithBar:(Bar *)bar { return [[self alloc] initWithBar:bar]; } - (instancetype)init { // Classes with a custom designated initializer should always override // the superclass's designated initializer. return [self initWithBar:nil]; } - (instancetype)initWithBar:(Bar *)bar { self = [super init]; if (self) { _bar = [bar copy]; _string = [[NSString alloc] initWithFormat:@"hi %d", 3]; _attributes = @{ @"color" : UIColor.blueColor, @"hidden" : @NO }; } return self; } - (BOOL)doWorkWithBlah:(NSString *)blah { // Work should be done here. return NO; } @end ``` -------------------------------- ### Multi-line JSDoc Example Source: https://google.github.io/styleguide/jsguide.html Demonstrates the standard multi-line format for JSDoc comments, including a parameter description. ```javascript /** * Multiple lines of JSDoc text are written here, * wrapped normally. * @param {number} arg A number to do something to. */ function doSomething(arg) { … } ``` -------------------------------- ### Redundant Break Example (Bad Practice) Source: https://google.github.io/styleguide/go/decisions.html This example demonstrates the incorrect use of `break` statements within `switch` clauses, which are unnecessary in Go. ```go switch x { case "A", "B": buf.WriteString(x) break // this break is redundant case "C": break // this break is redundant default: return fmt.Errorf("unknown value: %q", x) } ``` -------------------------------- ### Use t.Fatalf in Test Helpers for Setup Failures Source: https://google.github.io/styleguide/go/best-practices.html When a test helper function encounters a setup failure that prevents the rest of the test from running, use t.Fatalf to report the error and abort the test. This keeps the calling test function cleaner. ```go func mustAddGameAssets(t *testing.T, dir string) { t.Helper() if err := os.WriteFile(path.Join(dir, "pak0.pak"), pak0, 0644); err != nil { t.Fatalf("Setup failed: could not write pak0 asset: %v", err) } if err := os.WriteFile(path.Join(dir, "pak1.pak"), pak1, 0644); err != nil { t.Fatalf("Setup failed: could not write pak1 asset: %v", err) } } ``` -------------------------------- ### Scoped Test Setup Function Source: https://google.github.io/styleguide/go/best-practices.html Define setup functions like mustLoadDataset to load resources needed by specific tests. Call these functions directly within the tests that require them. ```go // mustLoadDataSet loads a data set for the tests. // // This example is very simple and easy to read. Often realistic setup is more // complex, error-prone, and potentially slow. func mustLoadDataset(t *testing.T) []byte { t.Helper() data, err := os.ReadFile("path/to/your/project/testdata/dataset") if err != nil { t.Fatalf("Could not load dataset: %v", err) } return data } ``` -------------------------------- ### Goroutine Panic Example Source: https://google.github.io/styleguide/go/decisions.html Demonstrates a scenario where sending on a closed channel causes a panic. ```go // Bad: ch := make(chan int) ch <- 42 close(ch) ch <- 13 // panic ``` -------------------------------- ### Unused Parameter Formatting (Bad Example) Source: https://google.github.io/styleguide/cppguide.html Illustrates an incorrect way to handle unused parameters by simply omitting the name, which can lead to ambiguity. ```cpp // Bad - if someone wants to implement later, it's not clear what the // variable means. void Circle::Rotate(double) {} ``` -------------------------------- ### Table Example in Markdown Source: https://google.github.io/styleguide/docguide/style.html Demonstrates how to create a table in Markdown for structured data. Reference links are used to keep cells manageable. ```markdown Transport | Favored by | Advantages ---------------- | -------------- | ----------------------------------------------- Swallow | Coconuts | [Fast when unladen][airspeed] Bicycle | Miss Gulch | [Weatherproof][tornado_proofing] X-34 landspeeder | Whiny farmboys | [Cheap][tosche_station] since the XP-38 came out ``` -------------------------------- ### Explicit Deduction Guide for std::array Source: https://google.github.io/styleguide/cppguide.html Explicit deduction guides define how template arguments are deduced. This example shows the guide for std::array. ```cpp namespace std { template array(T, U...) -> std::array; } ``` -------------------------------- ### Good: Instantiating and Passing Dependencies Source: https://google.github.io/styleguide/go/best-practices.html This example shows how a client application instantiates a `Registry` and passes it as an explicit dependency during configuration. This is the recommended approach for managing dependencies. ```go package main import ( "context" "log" "myapp" "sidecar" ) func main() { sidecars := sidecar.New() if err := sidecars.Register("Cloud Logger", cloudlogger.New()); err != nil { log.Exitf("Could not setup cloud logger: %v", err) } cfg := &myapp.Config{Sidecars: sidecars} myapp.Run(context.Background(), cfg) } ``` -------------------------------- ### File-level JSDoc Overview Source: https://google.github.io/styleguide/jsguide.html Provides an example of a top-level file overview comment, including optional metadata like @package. ```javascript /** * @fileoverview Description of file, its uses and information * about its dependencies. * @package */ ``` -------------------------------- ### Go Getter Naming Convention Source: https://google.github.io/styleguide/go/decisions.html Avoid 'Get' or 'get' prefixes for function and method names unless the concept inherently involves 'getting' (e.g., HTTP GET). Prefer starting with the noun. ```go // Prefer Counts over GetCounts // Use Fetch or Compute for complex/remote operations. ``` -------------------------------- ### Good Documentation: Informative Sprintf Explanation Source: https://google.github.io/styleguide/go/best-practices.html This example demonstrates good documentation for Sprintf, explaining non-obvious behavior regarding data mismatch and formatting errors. ```go // Good: // Sprintf formats according to a format specifier and returns the resulting // string. // // The provided data is used to interpolate the format string. If the data does // not match the expected format verbs or the amount of data does not satisfy // the format specification, the function will inline warnings about formatting // errors into the output string as described by the Format errors section // above. func Sprintf(format string, data ...any) string ``` -------------------------------- ### Objective-C Accessor Naming: No 'get' Prefix Source: https://google.github.io/styleguide/objcguide.html Accessor methods should be named the same as the object they are getting, without a 'get' prefix. This example shows the correct way to name a delegate accessor. ```Objective-C - (id)delegate; ``` -------------------------------- ### Using Internal Implementation Detail Source: https://google.github.io/styleguide/cppguide.html Example of using a type from an internal implementation detail namespace, typically discouraged for external use. ```cpp // We shouldn't use this internal name in non-absl code. using ::absl::container_internal::ImplementationDetail; ``` -------------------------------- ### Objective-C Accessor Naming: Avoid 'get' Prefix Source: https://google.github.io/styleguide/objcguide.html Avoid using a 'get' prefix for accessor methods. This example shows an incorrect naming convention. ```Objective-C - (id)getDelegate; ``` -------------------------------- ### Objective-C Method Naming: Basic Structure Source: https://google.github.io/styleguide/objcguide.html Objective-C method names start with a lowercase letter and use mixed case for subsequent words. This example shows a basic method signature. ```Objective-C + (NSURL *)URLWithString:(NSString *)URLString; ``` -------------------------------- ### Good Verbose Logging Example Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates the correct way to use verbose logging levels (`log.V`) to conditionally log information. This pattern ensures that expensive operations like `sql.Explain()` are only called when the corresponding verbose level is enabled. ```go // Good: for _, sql := range queries { log.V(1).Infof("Handling %v", sql) if log.V(2) { log.Infof("Handling %v", sql.Explain()) } sql.Run(...) } ``` -------------------------------- ### Class Documentation Example Source: https://google.github.io/styleguide/pyguide.html Demonstrates a class docstring with a summary, longer description, and an Attributes section for public members. The __init__ method also includes an Args section. ```python class SampleClass: """Summary of class here. Longer class information... Longer class information... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we haveшению. """ def __init__(self, likes_spam: bool = False): """Initializes the instance based on spam preference. Args: likes_spam: Defines if instance exhibits this preference. """ self.likes_spam = likes_spam self.eggs = 0 @property def butter_sticks(self) -> int: """The number of butter sticks we have.""" ``` -------------------------------- ### Short Javadoc Example Source: https://google.github.io/styleguide/javaguide.html An example of a concise Javadoc comment that fits on a single line. ```Java /** An especially short bit of Javadoc. */ ``` -------------------------------- ### Good: Calling a function with variadic options Source: https://google.github.io/styleguide/go/best-practices.html Illustrates how to call a function that accepts variadic options, showing both a complex call with multiple options and a simple call with no options. ```go // Good: func foo(ctx context.Context) { // Complex call: storage.EnableReplication(ctx, config, []string{"po", "is", "ea"}, storage.ReadonlyCells("ix", "gg"), storage.OverwritePolicies(true), storage.ReplicationInterval(1*time.Hour), storage.CopyWorkers(100), storage.HealthWatcher(watcher), ) // Simple call: storage.EnableReplication(ctx, config, []string{"po", "is", "ea"}) } ``` -------------------------------- ### Singleton Client Initialization in Go Source: https://google.github.io/styleguide/go/best-practices.html Shows a typical 'thick-client' singleton pattern where a package-level variable holds a client instance. This can create tight coupling and make testing difficult, especially when the client setup is complex or has external dependencies. ```go // Bad: package useradmin var client pb.UserAdminServiceClientInterface func Client() *pb.UserAdminServiceClient { if client == nil { client = ... // Set up client. } return client } ``` -------------------------------- ### Objective-C Method Naming: Avoidance Examples Source: https://google.github.io/styleguide/objcguide.html Examples of method names to avoid, such as unnecessary prefixes or 'the' for delegates. ```Objective-C - (CGFloat)calculateHeight; ``` ```Objective-C - (id)theDelegate; ``` -------------------------------- ### Go Package Naming - Good Examples Source: https://google.github.io/styleguide/go/best-practices.html Illustrates effective Go package naming by showing how specific package names like `spannertest`, `io`, and `elliptic` clearly indicate their functionality, improving code readability and reducing potential import conflicts. ```go // Good: db := spannertest.NewDatabaseFromFile(...) _, err := f.Seek(0, io.SeekStart) b := elliptic.Marshal(curve, x, y) ``` -------------------------------- ### Self-Describing Code Example in C++ Source: https://google.github.io/styleguide/cppguide.html Code that clearly expresses its intent does not require a comment. This example demonstrates self-describing code. ```cpp if (!IsAlreadyProcessed(element)) { Process(element); } ``` -------------------------------- ### Using MustXYZ for Package Initialization Source: https://google.github.io/styleguide/go/decisions.html Demonstrates a `MustXYZ` helper function for parsing a version string, used to initialize a package-level variable. This pattern is suitable for critical initialization steps where failure should halt the program. ```go // Good: func MustParse(version string) *Version { v, err := Parse(version) if err != nil { panic(fmt.Sprintf("MustParse(%q) = _, %v", version, err)) } return v } // Package level "constant". If we wanted to use `Parse`, we would have had to // set the value in `init`. var DefaultVersion = MustParse("1.2.3") ``` -------------------------------- ### Structural Typing Example Source: https://google.github.io/styleguide/tsguide.html Demonstrates TypeScript's structural typing. The 'cat' example shows an error at the function call site because 'cat' lacks the 'name' property. The 'horse' example shows an error at the declaration site because 'horse' is explicitly typed as 'Animal' but is missing the 'name' property. ```typescript interface Animal { sound: string; name: string; } function makeSound(animal: Animal) {} /** * 'cat' has an inferred type of '{sound: string}' */ const cat = { sound: 'meow', }; /** * 'cat' does not meet the type contract required for the function, so the * TypeScript compiler errors here, which may be very far from where 'cat' is * defined. */ makeSound(cat); /** * Horse has a structural type and the type error shows here rather than the * function call. 'horse' does not meet the type contract of 'Animal'. */ const horse: Animal = { sound: 'niegh', }; const dog: Animal = { sound: 'bark', name: 'MrPickles', }; makeSound(dog); makeSound(horse); ``` -------------------------------- ### Global Variable Comment Example Source: https://google.github.io/styleguide/cppguide.html Global variables require comments explaining their purpose and why they are global. This example documents a constant for the number of test cases. ```cpp // The total number of test cases that we run through in this regression test. const int kNumTestCases = 6; ``` -------------------------------- ### Discouraged Horizontal Alignment Example Source: https://google.github.io/styleguide/jsguide.html Demonstrates the use of horizontal alignment, which is permitted but generally discouraged. This example shows how alignment can lead to maintenance issues. ```javascript { tiny: 42, // this is great longer: 435, // this too }; { tiny: 42, // permitted, but future edits longer: 435, // may leave it unaligned }; ``` -------------------------------- ### Good Documentation: Special Context Lifetime Expectations Source: https://google.github.io/styleguide/go/best-practices.html This example documents functions with special expectations about context lifetime or attached values, advising against such patterns where possible. ```go // Good: // NewReceiver starts receiving messages sent to the specified queue. // The context should not have a deadline. func NewReceiver(ctx context.Context) *Receiver // Principal returns a human-readable name of the party who made the call. // The context must have a value attached to it from security.NewContext. func Principal(ctx context.Context) (name string, ok bool) ``` -------------------------------- ### Descriptive Proto Package Names Source: https://google.github.io/styleguide/go/best-practices.html When in doubt, use the proto package name up to _go with a pb suffix for clarity. ```go // Good: import ( pushqueueservicepb "path/to/package/push_queue_service_go_proto" ) ``` -------------------------------- ### Incorrect Capitalization Example Source: https://google.github.io/styleguide/docguide/style.html Avoid using lowercase for proper nouns like product names. This example shows the incorrect way to capitalize 'Markdown'. ```markdown # markdown bad style guide example `markdown` is a dead-simple platform for internal engineering documentation. ``` -------------------------------- ### Doc Comments for Struct Fields in Go Source: https://google.github.io/styleguide/go/decisions.html Shows how to write doc comments for struct fields, including general setup, dependencies, and optional fields with defaults. Comments should be concise and informative. ```go // Good: // Options configure the group management service. type Options struct { // General setup: Name string Group *FooGroup // Dependencies: DB *sql.DB // Customization: LargeGroupThreshold int // optional; default: 10 MinimumMembers int // optional; default: 2 } ``` -------------------------------- ### Bad Verbose Logging Example Source: https://google.github.io/styleguide/go/best-practices.html Illustrates an anti-pattern where an expensive function call (`sql.Explain()`) is made unconditionally, even when the verbose log level is not enabled. This can lead to performance degradation. ```go // Bad: // sql.Explain called even when this log is not printed. log.V(2).Infof("Handling %v", sql.Explain()) ``` -------------------------------- ### Avoid `bind` for Event Handler Installation Source: https://google.github.io/styleguide/tsguide.html Do not use `bind` when installing event handlers. It creates a temporary reference that cannot be uninstalled, leading to potential memory leaks. ```typescript // Binding listeners creates a temporary reference that prevents uninstalling. class Component { onAttached() { // This creates a temporary reference that we won't be able to uninstall window.addEventListener('onbeforeunload', this.listener.bind(this)); } onDetached() { // This bind creates a different reference, so this line does nothing. window.removeEventListener('onbeforeunload', this.listener.bind(this)); } private listener() { confirm('Do you want to exit the page?'); } } ``` -------------------------------- ### Good: Variadic options pattern in Go Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates the implementation of the variadic options pattern, including the options struct, option functions, default options, and the refactored function signature. ```go // Good: type replicationOptions struct { readonlyCells []string replicateExisting bool overwritePolicies bool replicationInterval time.Duration copyWorkers int healthWatcher health.Watcher } // A ReplicationOption configures EnableReplication. type ReplicationOption func(*replicationOptions) // ReadonlyCells adds additional cells that should additionally // contain read-only replicas of the data. // // Passing this option multiple times will add additional // read-only cells. // // Default: none func ReadonlyCells(cells ...string) ReplicationOption { return func(opts *replicationOptions) { opts.readonlyCells = append(opts.readonlyCells, cells...) } } // ReplicateExisting controls whether files that already exist in the // primary cells will be replicated. Otherwise, only newly-added // files will be candidates for replication. // // Passing this option again will overwrite earlier values. // // Default: false func ReplicateExisting(enabled bool) ReplicationOption { return func(opts *replicationOptions) { opts.replicateExisting = enabled } } // ... other options ... // DefaultReplicationOptions control the default values before // applying options passed to EnableReplication. var DefaultReplicationOptions = []ReplicationOption{ OverwritePolicies(true), ReplicationInterval(12 * time.Hour), CopyWorkers(10), } func EnableReplication(ctx context.Context, config *placer.Config, primaryCells []string, opts ...ReplicationOption) { var options replicationOptions for _, opt := range DefaultReplicationOptions { opt(&options) } for _, opt := range opts { opt(&options) } } ``` -------------------------------- ### JavaScript Constant Naming Examples Source: https://google.github.io/styleguide/jsguide.html Demonstrates correct and incorrect usage of CONSTANT_CASE for constants, including static properties and module-local declarations. Also shows examples of non-constants. ```javascript // Constants const NUMBER = 5; /** @const */ exports.NAMES = goog.debug.freeze(['Ed', 'Ann']); /** @enum */ exports.SomeEnum = { ENUM_CONSTANT: 'value' }; // Not constants let letVariable = 'non-const'; class MyClass { constructor() { /** @const {string} */ this.nonStatic = 'non-static'; } }; /** @type {string} */ MyClass.staticButMutable = 'not @const, can be reassigned'; const /** Set */ mutableCollection = new Set(); const /** MyImmutableContainer */ stillMutable = new MyImmutableContainer(mutableInner); const {Foo} = goog.require('my.foo'); // mirrors imported name const logger = log.getLogger('loggers.are.not.immutable'); ``` -------------------------------- ### Good Documentation: Multiple Interruption Mechanisms Source: https://google.github.io/styleguide/go/best-practices.html This example documents a function that can be interrupted by context cancellation or another method call, detailing their distinct behaviors. ```go // Good: // Run executes the worker's run loop. // // Run processes work until the context is cancelled or Stop is called. // Context cancellation is handled asynchronously internally: run may return // before all work has stopped. The Stop method is synchronous and waits // until all operations from the run loop finish. Use Stop for graceful // shutdown. func (Worker) Run(ctx context.Context) error func (Worker) Stop() ``` -------------------------------- ### Constant Initialization in C++ Source: https://google.github.io/styleguide/cppguide.html Demonstrates constant initialization using `constexpr` for constructors and variables. Use `constexpr` or `constinit` for static storage duration variables to ensure constant initialization. ```cpp struct Foo { constexpr Foo(int) {} }; int n = 5; // Fine, 5 is a constant expression. Foo x(2); // Fine, 2 is a constant expression and the chosen constructor is constexpr. Foo a[] = { Foo(1), Foo(2), Foo(3) }; // Fine ``` -------------------------------- ### Disallowed Identifier Examples in TypeScript Source: https://google.github.io/styleguide/tsguide.html Shows examples of identifier names that violate TypeScript naming conventions, highlighting common pitfalls like ambiguity and incorrect casing. ```typescript // Disallowed identifiers: n // Meaningless. nErr // Ambiguous abbreviation. nCompConns // Ambiguous abbreviation. wgcConnections // Only your group knows what this stands for. pcReader // Lots of things can be abbreviated "pc". cstmrId // Deletes internal letters. kSecondsPerDay // Do not use Hungarian notation. customerID // Incorrect camelcase of "ID". ``` -------------------------------- ### Go Constant Naming (MixedCaps) Source: https://google.github.io/styleguide/go/decisions.html Use MixedCaps for constant names, with exported constants starting uppercase and unexported starting lowercase. Avoid deriving names from values. ```go // Good: const MaxPacketSize = 512 const ( ExecuteBit = 1 << iota WriteBit ReadBit ) ``` -------------------------------- ### Logger API with Dependency Injection Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates a recommended API for infrastructure providers that need to be shared. It offers an API to create isolated instances and register them with a provided registry, avoiding reliance on package-level state. ```go // Good: package cloudlogger func New() *Logger { ... } func Register(r *sidecar.Registry, l *Logger) { r.Register("Cloud Logging", l) } ``` -------------------------------- ### Go Initialism Casing (Txn) Source: https://google.github.io/styleguide/go/decisions.html For initialisms like 'Txn', use all caps for exported names (e.g., Txn). ```go Txn ``` -------------------------------- ### Basic Function Call Formatting Source: https://google.github.io/styleguide/cppguide.html Demonstrates the standard single-line format for function calls with arguments. ```cpp bool result = DoSomething(argument1, argument2, argument3); ``` -------------------------------- ### Class Data Member Comment Example Source: https://google.github.io/styleguide/cppguide.html Comments for class data members should clarify invariants or the meaning of sentinel values like -1. This example explains the purpose of `num_total_entries_` and its sentinel value. ```cpp private: // Used to bounds-check table accesses. -1 means // that we don't yet know how many entries the table has. int num_total_entries_; ``` -------------------------------- ### Go Context with Timeout Example Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates the correct usage of `context.WithTimeout` for capping deadlines within a request handler. This pattern ensures that a portion of the request handling has a bounded execution time. ```go // Good: // innerHandler is a helper for some request handler, which itself issues // requests to other backends. func (s *Server) innerHandler(ctx context.Context, req *pb.MyRequest) *pb.MyResponse { // Unconditionally cap the deadline for this part of request handling. ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() ctxlog.Info(ctx, "Capped deadline in inner request") // Code here no longer has access to the original context. // This is good style if when first writing this, you anticipate // that even as the code grows, no operation legitimately should // use the (possibly unbounded) original context that the caller provided. // ... } ``` -------------------------------- ### Using Nil Slices in Go Source: https://google.github.io/styleguide/go/decisions.html Demonstrates that nil slices behave like empty slices for built-in functions and loops. Nil initialization is preferred for local variables that might be returned. ```go // Good: import "fmt" var s []int // nil fmt.Println(s) // [] fmt.Println(len(s)) // 0 fmt.Println(cap(s)) // 0 for range s {...} // no-op s = append(s, 42) fmt.Println(s) // [42] ``` ```go // Good: var t []string ``` ```go // Bad: t := []string{} ``` ```go // Good: // Ping pings its targets. // Returns hosts that successfully responded. func Ping(hosts []string) ([]string, error) { ... } ``` ```go // Bad: // Ping pings its targets and returns a list of hosts // that successfully responded. Can be empty if the input was empty. // nil signifies that a system error occurred. func Ping(hosts []string) []string { ... } ``` ```go // Good: // describeInts describes s with the given prefix, unless s is empty. func describeInts(prefix string, s []int) { if len(s) == 0 { return } fmt.Println(prefix, s) } ``` ```go // Bad: func maybeInts() []int { /* ... */ } // describeInts describes s with the given prefix; pass nil to skip completely. func describeInts(prefix string, s []int) { // The behavior of this function unintentionally changes depending on what // maybeInts() returns in 'empty' cases (nil or []int{}). if s == nil { return } fmt.Println(prefix, s) } describeInts("Here are some ints:", maybeInts()) ``` -------------------------------- ### Python Bad Comment Example Source: https://google.github.io/styleguide/pyguide.html Avoid describing the code's actions in comments. Assume the reader understands the programming language but not necessarily the specific intent. This example illustrates an unhelpful comment. ```python # BAD COMMENT: Now go through the b array and make sure whenever i occurs # the next element is i+1 ``` -------------------------------- ### Renaming Imports - Example Source: https://google.github.io/styleguide/tsguide.html Demonstrates how to rename imports using the 'as' keyword. This is useful for fixing name collisions, handling generated symbol names, or improving clarity when imported symbol names are ambiguous. ```typescript import {SomeThing as SomeOtherThing} from 'some-module'; ``` -------------------------------- ### Disallowed Getter Example Source: https://google.github.io/styleguide/jsguide.html Avoid using JavaScript getter and setter properties as they can be surprising and difficult to reason about. Provide ordinary methods instead. This example shows a disallowed getter that modifies observable state. ```javascript class Foo { get next() { return this.nextId++; } } ``` -------------------------------- ### Go Test Helper and Assertion Helper Example Source: https://google.github.io/styleguide/go/best-practices.html Demonstrates a `polygonCmp` function used as a test helper to equate s2 geometry objects with floating-point tolerance. The `TestFenceposts` function shows how to use this helper with `cmp.Diff` for asserting correctness. The `FuzzFencepost` function illustrates fuzz testing with a reference implementation for comparison. ```go // Good: // polygonCmp returns a cmp.Option that equates s2 geometry objects up to // some small floating-point error. func polygonCmp() cmp.Option { return cmp.Options{ cmp.Transformer("polygon", func(p *s2.Polygon) []*s2.Loop { return p.Loops() }), cmp.Transformer("loop", func(l *s2.Loop) []s2.Point { return l.Vertices() }), cmpopts.EquateApprox(0.00000001, 0), cmpopts.EquateEmpty(), } } func TestFenceposts(t *testing.T) { // This is a test for a fictional function, Fenceposts, which draws a fence // around some Place object. The details are not important, except that // the result is some object that has s2 geometry (github.com/golang/geo/s2) got := Fencepost(tomsDiner, 1*meter) if diff := cmp.Diff(want, got, polygonCmp()); diff != "" { t.Errorf("Fencepost(tomsDiner, 1m) returned unexpected diff (-want+got):\n%v", diff) } } func FuzzFencepost(f *testing.F) { // Fuzz test (https://go.dev/doc/fuzz) for the same. f.Add(tomsDiner, 1*meter) f.Add(school, 3*meter) f.Fuzz(func(t *testing.T, geo Place, padding Length) { got := Fencepost(geo, padding) // Simple reference implementation: not used in prod, but easy to // reason about and therefore useful to check against in random tests. reference := slowFencepost(geo, padding) // In the fuzz test, inputs and outputs can be large so don't // bother with printing a diff. cmp.Equal is enough. if !cmp.Equal(got, reference, polygonCmp()) { t.Errorf("Fencepost returned wrong placement") } }) } ``` -------------------------------- ### Function Declaration Comment Example Source: https://google.github.io/styleguide/cppguide.html Comments preceding a function declaration should describe its purpose and usage, including inputs, outputs, and potential iterator invalidation. This example shows how to document an iterator return type and its constraints. ```cpp // Returns an iterator for this table, positioned at the first entry // lexically greater than or equal to `start_word`. If there is no // such entry, returns a null pointer. The client must not use the // iterator after the underlying GargantuanTable has been destroyed. // // This method is equivalent to: // std::unique_ptr iter = table->NewIterator(); // iter->Seek(start_word); // return iter; std::unique_ptr GetIterator(absl::string_view start_word) const; ``` -------------------------------- ### Good: Using a Registry with Explicit Dependency Source: https://google.github.io/styleguide/go/best-practices.html This pattern demonstrates how to manage state using a struct and constructor, allowing clients to pass it as an explicit dependency. This avoids global state and improves testability. ```go package sidecar type Registry struct { plugins map[string]*Plugin } func New() *Registry { return &Registry{plugins: make(map[string]*Plugin)} } func (r *Registry) Register(name string, p *Plugin) error { ... } ``` -------------------------------- ### Class Comment Example Source: https://google.github.io/styleguide/cppguide.html Use class comments to explain the purpose and usage of a class. Include synchronization assumptions and multithreaded use cases if applicable. A small code example demonstrating focused usage is often helpful. ```cpp // Iterates over the contents of a GargantuanTable. // Example: // std::unique_ptr iter = table->NewIterator(); // for (iter->Seek("foo"); !iter->done(); iter->Next()) { // process(iter->key(), iter->value()); // } class GargantuanTableIterator { ... }; ``` -------------------------------- ### Multi-Line Constructor Initializer List (Wrapped Before Colon) Source: https://google.github.io/styleguide/cppguide.html Demonstrates wrapping the constructor signature and initializer list before the colon, with a 4-space indent for subsequent lines. ```cpp MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) { DoSomething(); } ``` -------------------------------- ### Go Package Comment - Main Package Source: https://google.github.io/styleguide/go/decisions.html For main packages, the package comment should describe the binary. The name of the `go_binary` rule in the BUILD file takes the place of the package name. This example demonstrates the correct format. ```go // Good: // The seed_generator command is a utility that generates a Finch seed file // from a set of JSON study configs. package main ``` -------------------------------- ### Single-line JSDoc Example Source: https://google.github.io/styleguide/jsguide.html Shows a concise single-line JSDoc comment for a constant private property. ```javascript /** @const @private {!Foo} A short bit of JSDoc. */ this.foo_ = foo; ``` -------------------------------- ### Renamed Proto Imports Source: https://google.github.io/styleguide/go/best-practices.html Use the 'pb' suffix for go_proto_library rules and 'grpc' for go_grpc_library rules. Prefer descriptive whole words for package names. ```go // Good: import ( foopb "path/to/package/foo_service_go_proto" foogrpc "path/to/package/foo_service_go_grpc" ) ``` -------------------------------- ### JSDoc @see Tag Example Source: https://google.github.io/styleguide/jsguide.html Use the @see tag to reference other classes, functions, or methods for related information. ```javascript /** * Adds a single item, recklessly. * @see #addSafely * @see goog.Collect * @see goog.RecklessAdder#add */ ```