notque/vexjoy-agent / skills/programming/programming
programming
FlaggedLanguage rules, workflows, and tooling: Go, Python, Rust, Kotlin, Swift, PHP, TypeScript type checks and debugging, OpenStack Python, MCP local-docs servers, Node.js backend APIs.
references/go/google-style-guide/best-practices/part-09.md
View on GitHubfunc 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)
}
}
```
The reason that common teardown is tricky is there is no uniform place to
register cleanup routines. If the setup function (in this case
`mustLoadDataset`) relies on a context, `sync.Once` may be problematic. This is
because the second of two racing calls to the setup function would need to wait
for the first call to finish before returning. This period of waiting cannot be
easily made to respect the context's cancellation.
<a id="string-concat"></a>
## String concatenation
There are several ways to concatenate strings in Go. Some examples include:
* The "+" operator
* `fmt.Sprintf`
* `strings.Builder`
* `text/template`
* `safehtml/template`
Though there is no one-size-fits-all rule for which to choose, the following
guidance outlines when each method is preferred.
<a id="string-concat-simple"></a>
### Prefer "+" for simple cases
Prefer using "+" when concatenating few strings. This method is syntactically
the simplest and requires no import.
```go
// Good:
key := "projectid: " + p
```
<a id="string-concat-fmt"></a>
### Prefer `fmt.Sprintf` when formatting
Prefer using `fmt.Sprintf` when building a complex string with formatting. Using
many "+" operators may obscure the end result.
```go
// Good:
str := fmt.Sprintf("%s [%s:%d]-> %s", src, qos, mtu, dst)
```
```go
// Bad:
bad := src.String() + " [" + qos.String() + ":" + strconv.Itoa(mtu) + "]-> " + dst.String()
```
**Best Practice:** When the output of the string-building operation is an
`io.Writer`, don't construct a temporary string with `fmt.Sprintf` just to send
it to the Writer. Instead, use `fmt.Fprintf` to emit to the Writer directly.
When the formatting is even more complex, prefer [`text/template`] or
[`safehtml/template`] as appropriate.
[`text/template`]: https://pkg.go.dev/text/template
[`safehtml/template`]: https://pkg.go.dev/github.com/google/safehtml/template
<a id="string-concat-piecemeal"></a>
### Prefer `strings.Builder` for constructing a string piecemeal
Prefer using `strings.Builder` when building a string bit-by-bit.
`strings.Builder` takes amortized linear time, whereas "+" and `fmt.Sprintf`
take quadratic time when called sequentially to form a larger string.
```go
// Good:
b := new(strings.Builder)
for i, d := range digitsOfPi {
fmt.Fprintf(b, "the %d digit of pi is: %d\n", i, d)
}
str := b.String()
```
**Note:** For more discussion, see
[GoTip #29: Building Strings Efficiently](https://google.github.io/styleguide/go/index.html#gotip).
<a id="string-constants"></a>
### Constant strings
Prefer to use backticks (\`) when constructing constant, multi-line string
literals.
```go
// Good:
usage := `Usage:
custom_tool [args]`
```
```go
// Bad:
usage := "" +
"Usage:\n" +
"\n" +
"custom_tool [args]"
```
<!--
-->
{% endraw %}
<a id="globals"></a>
## Global state
Libraries should not force their clients to use APIs that rely on
[global state](https://en.wikipedia.org/wiki/Global_variable). They are advised
not to expose APIs or export
[package level](https://go.dev/ref/spec#TopLevelDecl) variables that control
behavior for all clients as parts of their API. The rest of the section uses
"global" and "package level state" synonymously.
Instead, if your functionality maintains state, allow your clients to create and
use instance values.
**Important:** While this guidance is applicable to all developers, it is most
critical for infrastructure providers who offer libraries, integrations, and
services to other teams.
```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 { ... }
```
Your users will instantiate the data they need (a `*sidecar.Registry`) and then
pass it as an explicit dependency:
```go
// Good:
package main
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)
}
```
There are different approaches to migrating existing code to support dependency
passing. The main one you will use is passing dependencies as parameters to
constructors, functions, methods, or struct fields on the call chain.
See also:
* [Go Tip #5: Slimming Your Client Libraries](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #24: Use Case-Specific Constructions](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #40: Improving Time Testability with Function Parameters](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #41: Identify Function Call Parameters](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #44: Improving Time Testability with Struct Fields](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #80: Dependency Injection Principles](https://google.github.io/styleguide/go/index.html#gotip)
APIs that do not support explicit dependency passing become fragile as the
number of clients increases:
```go
// Bad:
package sidecar
var registry = make(map[string]*Plugin)
func Register(name string, p *Plugin) error { /* registers plugin in registry */ }
```
Consider what happens in the case of tests exercising code that transitively
relies on a sidecar for cloud logging.
```go
// Bad:
package app
import (
"cloudlogger"
"sidecar"
"testing"
)
func TestEndToEnd(t *testing.T) {
// The system under test (SUT) relies on a sidecar for a production cloud
// logger already being registered.
... // Exercise SUT and check invariants.
}
func TestRegression_NetworkUnavailability(t *testing.T) {
// We had an outage because of a network partition that rendered the cloud
// logger inoperative, so we added a regression test to exercise the SUT with
// a test double that simulates network unavailability with the logger.
sidecar.Register("cloudlogger", cloudloggertest.UnavailableLogger)
... // Exercise SUT and check invariants.
}
func TestRegression_InvalidUser(t *testing.T) {
// The system under test (SUT) relies on a sidecar for a production cloud
// logger already being registered.
//
// Oops. cloudloggertest.UnavailableLogger is still registered from the
// previous test.
... // Exercise SUT and check invariants.
}
```
Go tests are executed sequentially by default, so the tests above run as:
1. `TestEndToEnd`
2. `TestRegression_NetworkUnavailability`, which overrides the default value of
cloudlogger
3. `TestRegression_InvalidUser`, which requires the default value of
cloudlogger registered in `package sidecar`
This creates an order-dependent test case, which breaks running with test
filters, and prevents tests from running in parallel or being sharded.
Using global state poses problems that lack easy answers for you and the API's
clients:
* What happens if a client needs to use different and separately operating
sets of `Plugin`s (for example, to support multiple servers) in the same
process space?
* What happens if a client wants to replace a registered `Plugin` with an
alternative implementation in a test, like a [test double]?
What happens if a client's tests require hermeticity between instances of a
`Plugin`, or between all of the plugins registered?
* What happens if multiple clients `Register` a `Plugin` under the same name?
Which one wins, if any?
How should errors be [handled](decisions#handle-errors)? If the code panics
or calls `log.Fatal`, will that always be
[appropriate for all places in which API would be called](decisions#dont-panic)?
Can a client verify it doesn't do something bad before doing so?
* Are there certain stages in a program's startup phases or lifetime during
which `Register` can be called and when it can't?
What happens if `Register` is called at the wrong time? A client could call
`Register` in [`func init`](https://go.dev/ref/spec#Package_initialization),
before flags are parsed, or after `main`. The stage at which a function is
called affects error handling. If the author of an API assumes the API is
*only* called during program initialization without the requirement that it
is, the assumption may nudge the author to design error handling to
[abort the program](best-practices#program-init) by modeling the API as a
`Must`-like function. Aborting is not appropriate for general-purpose
library functions that can be used at any stage.
* What if the client's and the designer's concurrency needs are mismatched?
See also:
* [Go Tip #36: Enclosing Package-Level State](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #71: Reducing Parallel Test Flakiness](https://google.github.io/styleguide/go/index.html#gotip)
* [Go Tip #80: Dependency Injection Principles](https://google.github.io/styleguide/go/index.html#gotip)
* Error Handling:
[Look Before You Leap](https://docs.python.org/3/glossary.html#term-LBYL)
versus
[Easier to Ask for Forgiveness than Permission](https://docs.python.org/3/glossary.html#term-EAFP)
* [Unit Testing Practices on Public APIs]
Global state has cascading effects on the
[health of the Google codebase](guide.md#maintainability). Global state should
be approached with **extreme scrutiny**.
[Global state comes in several forms](#globals-forms), and you can use a few
[litmus tests to identify when it is safe](#globals-litmus-tests).
[Unit Testing Practices on Public APIs]: index.md#unit-testing-practices
<a id="globals-forms"></a>
### Major forms of package state APIs
Several of the most common problematic API forms are enumerated below:
* Top-level variables irrespective of whether they are exported.
```go
// Bad:
package logger
// Sinks manages the default output sources for this package's logging API. This
// variable should be set at package initialization time and never thereafter.
var Sinks []Sink
```
See the [litmus tests](#globals-litmus-tests) to know when these are safe.
* The
[service locator pattern](https://en.wikipedia.org/wiki/Service_locator_pattern).
See the [first example](#globals). The service locator pattern itself is not
problematic, rather the locator being defined as global.
* Registries for
[callbacks](https://en.wikipedia.org/wiki/Callback_\(computer_programming\))
and similar behaviors.
```go
// Bad:
package health
var unhealthyFuncs []func
func OnUnhealthy(f func()) {
unhealthyFuncs = append(unhealthyFuncs, f)
}
```
* Thick-Client singletons for things like backends, storage, data access
layers, and other system resources. These often pose additional problems
with service reliability.
```go
// Bad:
package useradmin
var client pb.UserAdminServiceClientInterface
func Client() *pb.UserAdminServiceClient {
if client == nil {
client = ... // Set up client.
}
return client
}
```
> **Note:** Many legacy APIs in the Google codebase do not follow this guidance;
> in fact, some Go standard libraries allow for configuration via global values.
> Nevertheless, the legacy API's contravention of this guidance
> **[should not be used as precedent](guide#local-consistency)** for continuing
> the pattern.
>
> It is better to invest in proper API design today than pay for redesigning
> later.
<a id="globals-litmus-tests"></a>
### Litmus tests
[APIs using the patterns above](#globals-forms) are unsafe when:
* Multiple functions interact via global state when executed in the same
program, despite being otherwise independent (for example, authored by
different authors in vastly different directories).
* Independent test cases interact with each other through global state.
* Users of the API are tempted to swap or replace global state for testing
purposes, particularly to replace any part of the state with a
[test double], like a stub, fake, spy, or mock.
* Users have to consider special ordering requirements when interacting with
global state: `func init`, whether flags are parsed yet, etc.
Provided the conditions above are avoided, there are a **few limited
circumstances under which these APIs are safe**, namely when any of the
following is true:
* The global state is logically constant
([example](https://github.com/klauspost/compress/blob/290f4cfacb3eff892555a491e3eeb569a48665e7/zstd/snappy.go#L413)).
* The package's observable behavior is stateless. For example, a public
function may use a private global variable as a cache, but so long as the
caller can't distinguish cache hits from misses, the function is stateless.
* The global state does not bleed into things that are external to the
program, like sidecar processes or files on a shared filesystem.
* There is no expectation of predictable behavior
([example](https://pkg.go.dev/math/rand)).
> **Note:**
> [Sidecar processes](https://www.oreilly.com/library/view/designing-distributed-systems/9781491983638/ch02.html)
> may **not** strictly be process-local. They can and often are shared with more
> than one application process. Moreover, these sidecars often interact with
> external distributed systems.
>
> Further, the same stateless, idempotent, and local rules in addition to the
> base considerations above would apply to the code of the sidecar process
> itself!
An example of one of these safe situations is
[`package image`](https://pkg.go.dev/image) with its
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |