### Document Resource Cleanup with Example (HTTP Get)
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
When resources like `resp.Body` need explicit cleanup, document this requirement and provide a clear example. This prevents resource leaks by showing callers how to properly close the 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)
```
--------------------------------
### Initialization Examples
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Examples of variable initialization with varying levels of predictability regarding ordering.
```cpp
int n = 5; // Fine
int m = f(); // ? (Depends on f)
Foo x; // ? (Depends on Foo::Foo)
Bar y = g(); // ? (Depends on g and on Bar::Bar)
```
--------------------------------
### Go Multiline Package Comment with Example
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
Multiline package comments are useful for including sections like command-line examples. This example shows a block comment with an indented command.
```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
```
--------------------------------
### Go Main Package Comment Example
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
For main packages, the package comment should describe the binary, using the name from the BUILD file. 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
```
--------------------------------
### Handle setup failures in acceptance tests
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Uses t.Fatal only for exceptional setup failures, adhering to standard testing practices.
```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).
}
```
--------------------------------
### Class Docstring Examples
Source: https://github.com/google/styleguide/blob/gh-pages/pyguide.md
Provides examples of correct class docstring formatting. The first example shows a descriptive docstring for a specific address type. The second shows a concise docstring for a custom exception.
```python
# Yes:
class CheeseShopAddress:
"""The address of a cheese shop.
...
"""
class OutOfCheeseError(Exception):
"""No more cheese is available."""
```
--------------------------------
### Java Module Import Example
Source: https://github.com/google/styleguide/blob/gh-pages/javaguide.html
Module imports are not used in this style guide. This example shows the syntax that should be avoided.
```java
import module java.base;
```
--------------------------------
### Amortize Expensive Test Setup with sync.Once
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Use sync.Once to perform expensive setup that does not require teardown. This pattern is suitable when the setup is shared across multiple tests.
```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
}
```
```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)
}
}
```
--------------------------------
### Module Docstring Example
Source: https://github.com/google/styleguide/blob/gh-pages/pyguide.md
Standard format for a module-level docstring including a summary and usage example.
```python
"""A one-line summary of the module or program, terminated by a period.
Leave one blank line. The rest of this docstring should contain an
overall description of the module or program. Optionally, it may also
contain a brief description of exported classes and functions and/or usage
examples.
Typical usage example:
foo = ClassFoo()
bar = foo.function_bar()
"""
```
--------------------------------
### Setup Failure Message in Go Test
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
For setup failures, a concise message indicating the failure and the error is usually sufficient. Avoid excessive detail about test inputs.
```go
t.Fatalf("Setup: Failed to set up test database: %s", err)
```
--------------------------------
### Godoc Runnable Example
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Test files can contain runnable examples that appear attached to the corresponding documentation in godoc.
```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"
// }
}
```
--------------------------------
### Runnable Examples in Go's Sort Package
Source: https://github.com/google/styleguide/blob/gh-pages/go/guide.md
Runnable examples in Go packages serve as both user-facing documentation and test cases. They appear in generated documentation and are executed as part of the test suite.
```go
package sort_test
import (
"fmt"
"sort"
)
func ExampleSearch() {
items := []int{1, 2, 3, 4, 5}
fmt.Println(sort.Search(len(items), func(i int) bool {
return items[i] >= 3
}))
// Output:
// 2
}
```
--------------------------------
### Documenting Function Parameters
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Examples showing how to provide meaningful commentary for function parameters versus redundant documentation.
```go
// Bad:
// Sprintf formats according to a format specifier and returns the resulting
// string.
//
// format is the format, and data is the interpolation data.
func Sprintf(format string, data ...any) string
```
```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
```
--------------------------------
### Java Class Structure Example
Source: https://context7.com/google/styleguide/llms.txt
Demonstrates proper Java class structure, including package declaration, imports, Javadoc, class definition, constants, fields, constructors, and methods. Follows Google's Java Style Guide.
```java
package com.google.example;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* A sample class demonstrating Google Java Style.
*
*
This class provides utility methods for processing user data.
* All public methods are thread-safe.
*/
public final class UserProcessor {
private static final int MAX_BATCH_SIZE = 100;
private final List processedUsers;
/** Creates a new UserProcessor with empty state. */
public UserProcessor() {
this.processedUsers = new ArrayList<>();
}
/**
* Processes a user by their ID.
*
* @param userId the unique identifier for the user, must not be null
* @return the processed user data, or empty if user not found
* @throws IllegalArgumentException if userId is empty
*/
public Optional processUser(String userId) {
Preconditions.checkNotNull(userId, "userId cannot be null");
Preconditions.checkArgument(!userId.isEmpty(), "userId cannot be empty");
// Process the user
UserData userData = fetchUserData(userId);
if (userData == null) {
return Optional.empty();
}
processedUsers.add(userId);
return Optional.of(userData);
}
/**
* Processes multiple users in batch.
*
* @param userIds list of user IDs to process
* @return number of successfully processed users
*/
public int processBatch(List userIds) {
int processed = 0;
for (String userId : userIds) {
if (processUser(userId).isPresent()) {
processed++;
}
if (processed >= MAX_BATCH_SIZE) {
break;
}
}
return processed;
}
private UserData fetchUserData(String userId) {
// Implementation details
return null;
}
}
```
--------------------------------
### Avoid placing %w at the start of error strings
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Example of a discouraged pattern where %w is placed at the start, resulting in oldest-to-newest printing.
```go
// Bad:
err1 := fmt.Errorf("err1")
err2 := fmt.Errorf("%w: err2", err1)
err3 := fmt.Errorf("%w: err3", err2)
fmt.Println(err3) // err1: err2: err3
```
--------------------------------
### TypeScript Module Structure Example
Source: https://context7.com/google/styleguide/llms.txt
Illustrates a proper TypeScript module structure, including imports, interfaces for configuration and results, and a class with asynchronous methods. Adheres to Google's TypeScript Style Guide.
```typescript
import {Logger} from '../common/logger';
import {UserService} from '../services/user_service';
/** Configuration options for the processor. */
interface ProcessorConfig {
readonly maxRetries: number;
readonly timeoutMs: number;
readonly enableLogging?: boolean;
}
/** Result of a processing operation. */
interface ProcessResult {
success: boolean;
data?: unknown;
error?: Error;
}
/**
* Processes user requests with retry logic and logging.
*
* Example usage:
* ```
* const processor = new RequestProcessor({maxRetries: 3, timeoutMs: 5000});
* const result = await processor.process('user-123');
* ```
*/
export class RequestProcessor {
private readonly logger: Logger;
private readonly userService: UserService;
constructor(private readonly config: ProcessorConfig) {
this.logger = new Logger('RequestProcessor');
this.userService = new UserService();
}
/**
* Processes a request for the given user ID.
* @param userId - The unique identifier for the user
* @returns A promise that resolves to the process result
*/
async process(userId: string): Promise {
if (!userId) {
return {success: false, error: new Error('userId is required')};
}
for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
try {
const data = await this.userService.fetchUser(userId);
this.log(`Successfully processed user: ${userId}`);
return {success: true, data};
} catch (error) {
this.log(`Attempt ${attempt + 1} failed: ${error}`);
if (attempt === this.config.maxRetries - 1) {
return {success: false, error: error as Error};
}
}
}
return {success: false, error: new Error('Max retries exceeded')};
}
private log(message: string): void {
if (this.config.enableLogging) {
this.logger.info(message);
}
}
}
```
--------------------------------
### Constant Initialization
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Examples of constant initialization using constexpr constructors and constant expressions.
```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
```
--------------------------------
### Good: Data-driven test with explicit dependency setup
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
Use this pattern when the setup for dependencies (like Codex) is slow or complex. It allows for clear separation of test cases and dependency initialization.
```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 Example
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
Package comments must be placed immediately above the package clause with no blank line. This example shows a good practice for a standard package.
```go
// Good:
// Package math provides basic constants and mathematical functions.
//
// This package does not guarantee bit-identical results across architectures.
package math
```
--------------------------------
### Documenting Context Usage
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Examples demonstrating when to document context behavior, specifically when it deviates from standard cancellation expectations.
```go
// Bad:
// Run executes the worker's run loop.
//
// The method will process work until the context is cancelled and accordingly
// returns an error.
func (Worker) Run(ctx context.Context) error
```
```go
// Good:
// Run executes the worker's run loop.
func (Worker) Run(ctx context.Context) error
```
```go
// Good:
// Run executes the worker's run loop.
//
// If the context is cancelled, Run returns a nil error.
func (Worker) Run(ctx context.Context) error
```
```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()
```
```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 Package Naming
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Examples comparing descriptive package names against generic, uninformative ones.
```go
// Good:
db := spannertest.NewDatabaseFromFile(...)
_, err := f.Seek(0, io.SeekStart)
b := elliptic.Marshal(curve, x, y)
```
```go
// Bad:
db := test.NewDatabaseFromFile(...)
_, err := f.Seek(0, common.SeekStart)
b := helper.Marshal(curve, x, y)
```
--------------------------------
### Typedef Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Example of a typedef named 'uint', following existing naming conventions.
```c++
uint
```
--------------------------------
### Define a production package
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Example of a production package structure for credit card operations.
```go
package creditcard
import (
"errors"
"path/to/money"
)
// ErrDeclined indicates that the issuer declines the charge.
var ErrDeclined = errors.New("creditcard: declined")
// Card contains information about a credit card, such as its issuer,
// expiration, and limit.
type Card struct {
// omitted
}
// Service allows you to perform operations with credit cards against external
// payment processor vendors like charge, authorize, reimburse, and subscribe.
type Service struct {
// omitted
}
func (s *Service) Charge(c *Card, amount money.Money) error { /* omitted */ }
```
--------------------------------
### Python Comprehensive Import Grouping Example
Source: https://github.com/google/styleguide/blob/gh-pages/pyguide.md
This example demonstrates the recommended order and grouping for various types of Python imports, including standard library, third-party, and local packages. Imports within each group should be sorted lexicographically.
```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
```
--------------------------------
### Assertion Library Implementation Example
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
This is an example of how assertion library functions might be implemented. These functions often call t.Fatalf, which halts test execution.
```go
package assert
func IsNotNil(t *testing.T, name string, val any) {
if val == nil {
t.Fatalf("Data %s = nil, want not nil", name)
}
}
func StringEq(t *testing.T, name, got, want string) {
if got != want {
t.Fatalf("Data %s = %q, want %q", name, got, want)
}
}
```
--------------------------------
### ATX-Style Headings Example
Source: https://github.com/google/styleguide/blob/gh-pages/docguide/style.md
Shows the correct usage of ATX-style headings in Markdown for different levels.
```markdown
# Heading 1
## Heading 2
```
--------------------------------
### Problematic Initializations
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Examples of initializations that are not constant expressions and are discouraged.
```cpp
// Some declarations used below.
time_t time(time_t*); // Not constexpr!
int f(); // Not constexpr!
struct Bar { Bar() {} };
// Problematic initializations.
time_t m = time(nullptr); // Initializing expression not a constant expression.
Foo y(f()); // Ditto
Bar b; // Chosen constructor Bar::Bar() not constexpr.
```
--------------------------------
### Conditional System-Specific Includes
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Example of how to handle system-specific code with conditional includes, placed after other standard includes.
```cpp
#include "foo/public/fooserver.h"
#ifdef _WIN32
#include
#endif // _WIN32
```
--------------------------------
### Formatting Function Signatures
Source: https://github.com/google/styleguide/blob/gh-pages/pyguide.md
Examples of how to break lines in function signatures for readability.
```python
def my_method(
self,
first_var: int,
second_var: Foo,
third_var: Bar | None,
) -> int:
...
```
```python
def my_method(self, first_var: int) -> int:
...
```
```python
Yes:
def my_method(
self,
other_arg: MyLongType | None,
) -> tuple[MyLongType1, MyLongType1]:
...
```
```python
Okay:
def my_method(
self,
first_var: int,
second_var: int) -> dict[OtherLongType, MyLongType]:
...
```
```python
No:
def my_method(self,
other_arg: MyLongType | None,
) -> dict[OtherLongType, MyLongType]:
...
```
```python
def my_method(
self,
first_var: tuple[list[MyLongType1],
list[MyLongType2]],
second_var: list[dict[
MyLongType3, MyLongType4]],
) -> None:
...
```
```python
Yes:
def my_function(
long_variable_name:
long_module_name.LongTypeName,
) -> None:
...
```
```python
No:
def my_function(
long_variable_name: long_module_name.
LongTypeName,
) -> None:
...
```
--------------------------------
### Permitted Dynamic Initialization
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Example of dynamic initialization that is permitted when sequencing does not affect program behavior.
```cpp
int p = getpid(); // Allowed, as long as no other static variable
// uses p in its own initialization.
```
--------------------------------
### Example Function Call
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Illustrates a function call that follows the naming convention of an existing C or C++ entity.
```c++
bigopen()
```
--------------------------------
### Singleton Client Initialization Example (Bad)
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Shows a common pattern for initializing a singleton client for a service. This approach can lead to issues with testability and managing dependencies.
```go
package useradmin
var client pb.UserAdminServiceClientInterface
func Client() *pb.UserAdminServiceClient {
if client == nil {
client = ... // Set up client.
}
return client
}
```
--------------------------------
### Markdown Table Formatting Example
Source: https://github.com/google/styleguide/blob/gh-pages/docguide/style.md
Demonstrates the formatting for Markdown tables, which are an exception to the 80-character line limit.
```markdown
Foo | Bar | Baz
----------------------------------------------------------------------------- | --- | ---
Somehow-unavoidable-long-cell-filled-with-content-that-simply-refuses-to-wrap | Foo | Bar
```
--------------------------------
### Explicit Deduction Guide for std::array
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
This is an example of an explicit deduction guide for `std::array`, which enables Class Template Argument Deduction (CTAD). It specifies how template arguments should be deduced from constructor arguments.
```cpp
namespace std {
template
array(T, U...) -> std::array;
}
```
--------------------------------
### TypeScript Import Examples
Source: https://github.com/google/styleguide/blob/gh-pages/tsguide.html
Demonstrates various ways to import modules in TypeScript, including namespace, named, default, and side-effect imports.
```typescript
// Good: choose between two options as appropriate (see below).
import * as ng from '@angular/core';
import {Foo} from './foo';
// Only when needed: default imports.
import Button from 'Button';
// Sometimes needed to import libraries for their side effects:
import 'jasmine';
import '@polymer/paper-button';
```
--------------------------------
### C++ Style Conventions
Source: https://context7.com/google/styleguide/llms.txt
Examples demonstrating proper header file structure with include guards and class definitions, alongside implementation file practices.
```cpp
// Example: Proper header file structure (my_class.h)
#ifndef PROJECT_MY_CLASS_H_
#define PROJECT_MY_CLASS_H_
#include
#include
#include
#include "project/base/base.h"
namespace project {
// Forward declarations
class Helper;
// Class documentation explaining purpose and usage
class MyClass {
public:
// Use explicit for single-argument constructors
explicit MyClass(std::string name);
// Default destructor is fine for simple classes
~MyClass() = default;
// Disallow copy and assign (Rule of Five)
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;
// Allow move operations
MyClass(MyClass&&) = default;
MyClass& operator=(MyClass&&) = default;
// Accessors should be const
const std::string& name() const { return name_; }
// Methods that modify state
void ProcessData(const std::vector& data);
private:
std::string name_;
std::unique_ptr helper_;
};
} // namespace project
#endif // PROJECT_MY_CLASS_H_
// Example: Implementation file (my_class.cc)
#include "project/my_class.h"
#include
#include
#include "project/helper.h"
namespace project {
MyClass::MyClass(std::string name)
: name_(std::move(name)),
helper_(std::make_unique()) {}
void MyClass::ProcessData(const std::vector& data) {
// Use range-based for loops
for (const int value : data) {
helper_->Process(value);
}
}
} // namespace project
```
--------------------------------
### Class Template Argument Deduction (CTAD) Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
CTAD allows the compiler to deduce template arguments for class templates from the initializer. Use this feature only with templates that explicitly opt-in by providing deduction guides.
```cpp
std::array a = {1, 2, 3}; // `a` is a std::array
```
--------------------------------
### Running Specific Tests Without Expensive Initialization
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Demonstrates how to run a specific test function using `go test -run` without executing potentially slow or failure-prone global setup code.
```shell
# No reason for this to perform the expensive initialization.
$ go test -run TestRegression682831
```
--------------------------------
### Defining the FS Interface
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
An example of the FS interface from the io/fs package, which developers may implement and validate using fstest.TestFS.
```go
type FS interface {
Open(name string) (File, error)
}
```
--------------------------------
### Go Package Structure and Service Implementation
Source: https://context7.com/google/styleguide/llms.txt
Demonstrates a proper Go package structure for a userservice, including common errors, user representation, repository interface, and service methods for getting and creating users. Ensure proper error wrapping and validation.
```go
// Example: Proper Go package structure
// Package userservice provides user management functionality.
package userservice
import (
"context"
"errors"
"fmt"
"time"
)
// Common errors returned by this package.
var (
ErrUserNotFound = errors.New("userservice: user not found")
ErrInvalidInput = errors.New("userservice: invalid input")
)
// User represents a user in the system.
type User struct {
ID string
Name string
Email string
CreatedAt time.Time
}
// Service provides user management operations.
type Service struct {
repo Repository
}
// Repository defines the interface for user data storage.
type Repository interface {
GetUser(ctx context.Context, id string) (*User, error)
SaveUser(ctx context.Context, user *User) error
}
// NewService creates a new user service with the given repository.
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
// GetUser retrieves a user by ID.
//
// It returns ErrUserNotFound if the user does not exist.
func (s *Service) GetUser(ctx context.Context, id string) (*User, error) {
if id == "" {
return nil, fmt.Errorf("%w: id cannot be empty", ErrInvalidInput)
}
user, err := s.repo.GetUser(ctx, id)
if err != nil {
return nil, fmt.Errorf("getting user %q: %w", id, err)
}
if user == nil {
return nil, fmt.Errorf("user %q: %w", id, ErrUserNotFound)
}
return user, nil
}
// CreateUser creates a new user with the given name and email.
func (s *Service) CreateUser(ctx context.Context, name, email string) (*User, error) {
if name == "" || email == "" {
return nil, fmt.Errorf("%w: name and email are required", ErrInvalidInput)
}
user := &User{
ID: generateID(),
Name: name,
Email: email,
CreatedAt: time.Now(),
}
if err := s.repo.SaveUser(ctx, user); err != nil {
return nil, fmt.Errorf("saving user: %w", err)
}
return user, nil
}
func generateID() string {
return fmt.Sprintf("user_%d", time.Now().UnixNano())
}
```
--------------------------------
### Define a production package with multiple types
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Example of a production package containing multiple types that may require test doubles.
```go
package creditcard
type Service struct {
// omitted
}
type Card struct {
// omitted
}
// StoredValue manages customer credit balances. This applies when returned
// merchandise is credited to a customer's local account instead of processed
// by the credit issuer. For this reason, it is implemented as a separate
// service.
type StoredValue struct {
// omitted
}
func (s *StoredValue) Credit(c *Card, amount money.Money) error { /* omitted */ }
```
--------------------------------
### Implement Custom TestMain Entrypoint
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Use a custom TestMain to manage expensive setup and teardown for an entire package. Ensure teardown is handled via defer within a separate runMain function to account for os.Exit behavior.
```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)
}
```
--------------------------------
### Consume an acceptance test package
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Example of how an end user invokes the acceptance test within a standard Go test function.
```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)
}
}
```
--------------------------------
### Constant Naming Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Example of a constant named 'LONGLONG_MAX', following the convention of 'INT_MAX'.
```c++
LONGLONG_MAX
```
--------------------------------
### Horizontal whitespace examples
Source: https://github.com/google/styleguide/blob/gh-pages/javaguide.html
Examples of required horizontal spacing for keywords, operators, and declarations.
```java
```
```java
catch (FooException | BarException e)
```
```java
(String str) -> str.length()
```
```java
case "FOO" -> bar();
```
```java
Object::toString
```
```java
object.toString()
```
```java
List list
```
```java
new int[] {5, 6}
```
```java
new int[] { 5, 6 }
```
--------------------------------
### Standard Include Order Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Demonstrates the preferred order of include directives for a .cc file, including related headers, C system headers, C++ standard library headers, other libraries, and project headers, separated by blank lines.
```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"
```
--------------------------------
### Pointer Initialization for Counter and Protobuf in Go
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Demonstrates preferred pointer initialization for types like Counter and protobuf messages, especially when returning pointers or when the type satisfies an interface like proto.Message.
```go
// Good:
func NewCounter(name string) *Counter {
c := new(Counter) // "&Counter{}" is also fine.
registerCounter(name, c)
return c
}
var msg = new(pb.Bar) // or "&pb.Bar{}".
```
```go
// Bad:
func NewCounter(name string) *Counter {
var c Counter
registerCounter(name, &c)
return &c
}
var msg = pb.Bar{}
```
--------------------------------
### Identifier Naming Examples
Source: https://github.com/google/styleguide/blob/gh-pages/tsguide.html
Examples of preferred and disallowed identifier names based on clarity and abbreviation rules.
```text
// Good identifiers:
errorCount // No abbreviation.
dnsConnectionIndex // Most people know what "DNS" stands for.
referrerUrl // Ditto for "URL".
customerId // "Id" is both ubiquitous and unlikely to be misunderstood.
```
```text
// 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".
```
--------------------------------
### Fileoverview JSDoc Example
Source: https://github.com/google/styleguide/blob/gh-pages/tsguide.html
An example of a top-level JSDoc comment for a file, providing a description of its content and purpose.
```typescript
/**
* @fileoverview Description of file. Lorem ipsum dolor sit amet, consectetur
* adipiscing elit, sed do eiusmod tempor incididunt.
*/
```
--------------------------------
### GargantuanTableIterator Class Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Demonstrates the usage of GargantuanTableIterator with an example code snippet. This class iterates over the contents of a GargantuanTable.
```c++
// 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 {
...
};
```
--------------------------------
### Struct or Class Naming Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Example of a struct or class named 'bigpos', following the naming form of 'pos'.
```c++
bigpos
```
--------------------------------
### Python Style Conventions
Source: https://context7.com/google/styleguide/llms.txt
Examples demonstrating proper function definitions with type annotations, import organization, pylint suppression, and the standard main function pattern.
```python
# Example: Proper function definition with type annotations and docstrings
def connect_to_next_port(self, minimum: int) -> int:
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
raise ValueError(f'Min port must be at least 1024, not {minimum}.')
port = self._find_next_open_port(minimum)
if port is None:
raise ConnectionError(
f'Could not connect to service on port {minimum} or higher.')
return port
# Example: Proper imports organization
# Standard library imports
import os
import sys
from typing import Optional
# Third-party imports
import numpy as np
import tensorflow as tf
# Local imports
from myproject.utils import helper
# Example: Using pylint suppression when necessary
def do_PUT(self): # WSGI name, so pylint: disable=invalid-name
"""Handle PUT request."""
pass
# Example: Main function pattern
def main():
"""Main entry point for the application."""
# Application logic here
pass
if __name__ == '__main__':
main()
```
--------------------------------
### Variable Naming: snake_case Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Use snake_case for local variables and function parameters. This example shows a valid snake_case variable name.
```cpp
std::string table_name; // OK - snake_case.
```
--------------------------------
### Define Objective-C Header and Implementation Files
Source: https://context7.com/google/styleguide/llms.txt
Demonstrates the structure of a header file with class declarations and a corresponding implementation file using thread-safe singleton patterns and asynchronous authentication.
```objectivec
// Example: Header file (GTMUserManager.h)
#import
@class GTMUser;
@protocol GTMUserManagerDelegate;
NS_ASSUME_NONNULL_BEGIN
/**
* Manages user authentication and session state.
*
* This class provides methods for logging in, logging out, and
* monitoring the current user's session. All methods are thread-safe.
*/
@interface GTMUserManager : NSObject
/** The currently authenticated user, or nil if not logged in. */
@property(nonatomic, readonly, nullable) GTMUser *currentUser;
/** Delegate for receiving authentication state changes. */
@property(nonatomic, weak, nullable) id delegate;
/** Returns the shared user manager instance. */
+ (instancetype)sharedManager;
/**
* Authenticates a user with the given credentials.
*
* @param username The user's username.
* @param password The user's password.
* @param completion Block called on completion with the user or error.
*/
- (void)loginWithUsername:(NSString *)username
password:(NSString *)password
completion:(void (^)(GTMUser *_Nullable user,
NSError *_Nullable error))completion;
/** Logs out the current user and clears session data. */
- (void)logout;
@end
/** Delegate protocol for user manager events. */
@protocol GTMUserManagerDelegate
@optional
- (void)userManager:(GTMUserManager *)manager didLoginUser:(GTMUser *)user;
- (void)userManager:(GTMUserManager *)manager didLogoutUser:(GTMUser *)user;
@end
NS_ASSUME_NONNULL_END
// Example: Implementation file (GTMUserManager.m)
#import "GTMUserManager.h"
#import "GTMUser.h"
@interface GTMUserManager ()
@property(nonatomic, readwrite, nullable) GTMUser *currentUser;
@end
@implementation GTMUserManager
+ (instancetype)sharedManager {
static GTMUserManager *sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init];
});
return sharedManager;
}
- (void)loginWithUsername:(NSString *)username
password:(NSString *)password
completion:(void (^)(GTMUser *, NSError *))completion {
NSParameterAssert(username.length > 0);
NSParameterAssert(password.length > 0);
NSParameterAssert(completion != nil);
// Perform authentication asynchronously
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
GTMUser *user = [self authenticateUsername:username password:password];
dispatch_async(dispatch_get_main_queue(), ^{
if (user) {
self.currentUser = user;
[self.delegate userManager:self didLoginUser:user];
completion(user, nil);
} else {
NSError *error = [NSError errorWithDomain:@"GTMUserManagerErrorDomain"
code:401
userInfo:@{NSLocalizedDescriptionKey: @"Invalid credentials"}];
completion(nil, error);
}
});
});
}
- (void)logout {
GTMUser *user = self.currentUser;
self.currentUser = nil;
if (user) {
[self.delegate userManager:self didLogoutUser:user];
}
}
- (nullable GTMUser *)authenticateUsername:(NSString *)username
password:(NSString *)password {
// Authentication implementation
return nil;
}
@end
```
--------------------------------
### Disallowed Identifier Naming Examples
Source: https://github.com/google/styleguide/blob/gh-pages/jsguide.html
Examples of disallowed identifier naming conventions, including meaningless, ambiguous, or abbreviated names, and Hungarian notation.
```javascript
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.
```
--------------------------------
### Global Variable Comment Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Provide a comment for global variables explaining their purpose and why they are global. This example defines the total number of test cases.
```cpp
// The total number of test cases that we run through in this regression test.
const int kNumTestCases = 6;
```
--------------------------------
### Class Documentation with Attributes
Source: https://github.com/google/styleguide/blob/gh-pages/pyguide.md
Shows how to document a class with a summary line, longer description, and an 'Attributes' section detailing public attributes. The `__init__` method also includes its own docstring with 'Args'.
```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 laid.
"""
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."""
```
--------------------------------
### Variable Naming: Mixed Case Example (Bad)
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Avoid mixed case for variable names; snake_case is preferred. This example illustrates an incorrect naming style.
```cpp
std::string tableName; // Bad - mixed case.
```
--------------------------------
### Avoiding `bind` for event handler installation
Source: https://github.com/google/styleguide/blob/gh-pages/tsguide.html
Do not use `bind` when installing event handlers, as 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?');
}
}
```
--------------------------------
### Calling Function with Variadic Options
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
This Go code shows how to call a function that accepts variadic options. It includes examples of both complex calls with multiple options and simple calls 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"})
}
```
--------------------------------
### Create an error chain with %w
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Demonstrates the basic syntax for creating a chain of wrapped errors using the %w verb.
```go
err1 := fmt.Errorf("err1")
err2 := fmt.Errorf("err2: %w", err1)
err3 := fmt.Errorf("err3: %w", err2)
```
--------------------------------
### Class Data Member Comment Example
Source: https://github.com/google/styleguide/blob/gh-pages/cppguide.html
Comment on class data members to clarify invariants, sentinel values, or non-obvious meanings. This example explains the use of -1.
```cpp
// Used to bounds-check table accesses. -1 means
// that we don't yet know how many entries the table has.
int num_total_entries_;
```
--------------------------------
### Local variable initialization
Source: https://github.com/google/styleguide/blob/gh-pages/go/decisions.md
Both forms are equivalent for initializing local variables.
```go
var i int
```
```go
i := 0
```
--------------------------------
### Python Variable Naming Examples
Source: https://github.com/google/styleguide/blob/gh-pages/pyguide.md
Examples of descriptive naming for various Python entities, including modules, classes, methods, exceptions, functions, constants, variables, and parameters.
```python
module_name
```
```python
package_name
```
```python
ClassName
```
```python
method_name
```
```python
ExceptionName
```
```python
function_name
```
```python
GLOBAL_CONSTANT_NAME
```
```python
global_var_name
```
```python
instance_var_name
```
```python
function_parameter_name
```
```python
local_var_name
```
```python
query_proper_noun_for_thing
```
```python
send_acronym_via_https
```
--------------------------------
### Camel Case Conversion Examples
Source: https://github.com/google/styleguide/blob/gh-pages/javaguide.html
These examples demonstrate the conversion of English phrases into camel case, including handling acronyms and version numbers according to the specified rules.
```plaintext
Prose form
Correct
Incorrect
"XML HTTP request"
`XmlHttpRequest`
`XMLHTTPRequest`
"new customer ID"
`newCustomerId`
`newCustomerID`
"inner stopwatch"
`innerStopwatch`
`innerStopWatch`
"supports IPv6 on iOS?"
`supportsIpv6OnIos`
`supportsIPv6OnIOS`
"YouTube importer"
`YouTubeImporter`
`YoutubeImporter`*
"Turn on 2SV"
`turnOn2sv`
`turnOn2Sv`
"Guava 33.4.6"
`guava33_4_6`
`guava3346`
*Acceptable, but not recommended.
```
--------------------------------
### Discouraged Horizontal Alignment Example
Source: https://github.com/google/styleguide/blob/gh-pages/jsguide.html
Demonstrates the use of horizontal alignment, which is permitted but generally discouraged due to maintenance difficulties. This example shows aligned values in an object literal.
```javascript
{
tiny: 42, // permitted, but future edits
longer: 435, // may leave it unaligned
}
```
--------------------------------
### Importing Protocol Buffer Messages and Stubs
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Use descriptive names for proto imports, preferring the package name with a 'pb' or 'grpc' suffix. Avoid overly short names like 'xpb' in new code.
```go
// Good:
import (
foopb "path/to/package/foo_service_go_proto"
foogrpc "path/to/package/foo_service_go_grpc"
)
```
```go
// Good:
import (
pushqueueservicepb "path/to/package/push_queue_service_go_proto"
)
```
--------------------------------
### Define an instance-based registry in Go
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Use a struct to manage state instead of package-level variables.
```go
// Good:
// Package sidecar manages subprocesses that provide features for applications.
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 { ... }
```
--------------------------------
### Callback Registry Example (Bad)
Source: https://github.com/google/styleguide/blob/gh-pages/go/best-practices.md
Illustrates a package-level slice used to store callback functions. This global registry can be problematic for managing state and concurrent access.
```go
package health
var unhealthyFuncs []func
func OnUnhealthy(f func()) {
unhealthyFuncs = append(unhealthyFuncs, f)
}
```