agentleFS
vndeevndee/engineering-skills/.claude/skills/go-refactor/SKILL.md

go-refactor

Skill3 starsChanged 9 months agoMITView on GitHub

Use when refactoring Go code, cleaning up legacy codebases, optimizing performance, or enforcing clean architecture boundaries in a Go/Fiber backend

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

11 rules. About 0 are common, 7 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈7

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Core principle: Never refactor without characterization tests.

    line 12
  2. Very specific:

    3-strikes rule: If the same refactoring approach fails 3 times, stop.

    line 14
  3. Distinctive:

    N+1 detection: If you see N queries for N items in logs, fix with JOIN or batch query.

    line 111
  4. Distinctive:

    When working with legacy Go code that has no tests, bad structure, or mixed concerns:

    line 135
  5. Distinctive:

    Never change legacy code without characterization tests: Write tests that capture current behavior — even if the behavior is wrong.

    line 139
  6. Distinctive:

    Don't rewrite — wrap and replace incrementally:

    line 163
  7. Distinctive:

    Delete it: Don't comment it out. Git has history.

    line 208
  8. Very specific:

    REQUIRED: Use superpowers:systematic-debugging for performance investigation

    line 212
  9. Distinctive:

    REQUIRED: Write characterization tests before any refactoring — no exceptions

    line 213
  10. Very specific:

    REQUIRED: Update CLAUDE.md with discovered gotchas and conventions (claude-md)

    line 214
  11. Very specific:

    Legacy codebases: Run fullstack-healthcheck first to prioritize what to fix

    line 215

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Go Refactoring & Performance

Overview

Safe refactoring patterns and performance optimization for Go backends. Always characterize before changing.

Core principle: Never refactor without characterization tests. Never optimize without profiling.

3-strikes rule: If the same refactoring approach fails 3 times, stop. The problem is architectural — escalate to system-design for a deeper review instead of thrashing.

Safe Refactoring Process

  1. Write characterization tests — capture current behavior
  2. Refactor — change structure, not behavior
  3. Verify — all characterization tests still pass
  4. Clean up — remove temporary tests if redundant

Architecture Enforcement

The dependency rule: Dependencies point inward. Domain imports nothing external.

interfaces → application → domain
infrastructure → domain

Violations to check:

# Domain should not import infrastructure or interfaces
grep -r "infrastructure\|interfaces\|fiber\|pgx\|sqlalchemy" internal/domain/

# Application should not import infrastructure
grep -r "infrastructure\|pgx\|redis" internal/application/

Common Refactoring Moves

SmellMove
Fat handlerExtract use case
Duplicate validationExtract domain value object
Concrete dependencyExtract interface + inject
Sequential I/Oerrgroup for concurrent calls
God structSplit by responsibility
Copy-paste handlersExtract middleware

Extract Interface

// Before: handler directly uses concrete repo
type Handler struct { repo *postgres.UserRepo }

// After: handler uses interface from domain
type Handler struct { repo domain.UserRepository }

Concurrent I/O with errgroup

g, ctx := errgroup.WithContext(ctx)
var users []domain.User
var posts []domain.Post

g.Go(func() error {
    var err error
    users, err = userRepo.List(ctx)
    return err
})
g.Go(func() error {
    var err error
    posts, err = postRepo.List(ctx)
    return err
})
if err := g.Wait(); err != nil {
    return err
}

Performance Profiling

import _ "net/http/pprof"

// In main.go, add alongside Fiber:
go http.ListenAndServe(":6060", nil)
# CPU profile
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

# Memory profile
go tool pprof http://localhost:6060/debug/pprof/heap

# Goroutine dump
curl http://localhost:6060/debug/pprof/goroutine?debug=2

SQL Optimization

-- Always check query plans
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@test.com';

N+1 detection: If you see N queries for N items in logs, fix with JOIN or batch query.

// Bad: N+1
for _, user := range users {
    posts, _ := postRepo.GetByUserID(ctx, user.ID)
}

// Good: batch
posts, _ := postRepo.GetByUserIDs(ctx, userIDs)

pgxpool Tuning

config, _ := pgxpool.ParseConfig(connStr)
config.MaxConns = 25
config.MinConns = 5
config.MaxConnLifetime = 30 * time.Minute
config.MaxConnIdleTime = 5 * time.Minute

Legacy Code Rescue

When working with legacy Go code that has no tests, bad structure, or mixed concerns:

Step 1: Characterize Before Touching

Never change legacy code without characterization tests. Write tests that capture current behavior — even if the behavior is wrong. You need a safety net before refactoring.

// Characterization test: document what the code ACTUALLY does
func TestLegacy_CreateUser_CurrentBehavior(t *testing.T) {
    // This test captures existing behavior, not desired behavior
    // If this test breaks during refactoring, you changed behavior (not just structure)
    result, err := legacyCreateUser(input)
    assert.NoError(t, err)
    assert.Equal(t, expectedOutput, result) // whatever it currently returns
}

Step 2: Identify the Worst Offenders

Prioritize by risk, not by ugliness:

  1. Code handling user input without validation — security risk, fix first
  2. Code with no error handling — silent failures, data corruption risk
  3. God files (500+ lines) — impossible to test, split by responsibility
  4. Circular dependencies — extract interfaces to break cycles
  5. Dead code — remove to reduce cognitive load

Step 3: Incremental Strangler Fig

Don't rewrite — wrap and replace incrementally:

// 1. Extract interface from legacy code
type UserService interface {
    Create(ctx context.Context, input CreateInput) (*User, error)
}

// 2. Legacy implementation stays as-is (for now)
type legacyUserService struct { db *sql.DB }

// 3. New implementation follows clean architecture
type cleanUserService struct { repo domain.UserRepository }

// 4. Feature flag or gradual rollover
func NewUserService(useLegacy bool) UserService {
    if useLegacy { return &legacyUserService{} }
    return &cleanUserService{}
}

Step 4: Add Missing Error Handling

// Before: legacy swallows errors
result, _ := db.Query(query)

// After: handle every error
result, err := db.Query(query)
if err != nil {
    return fmt.Errorf("query users: %w", err)
}

Step 5: Remove Dead Code

# Find unused functions
grep -rn "^func " --include="*.go" | while read line; do
  func_name=$(echo "$line" | grep -oP 'func \K\w+')
  count=$(grep -rn "$func_name" --include="*.go" | wc -l)
  [ "$count" -le 1 ] && echo "UNUSED: $line"
done

Delete it. Don't comment it out. Git has history.

Chains

  • REQUIRED: Use superpowers:systematic-debugging for performance investigation
  • REQUIRED: Write characterization tests before any refactoring — no exceptions
  • REQUIRED: Update CLAUDE.md with discovered gotchas and conventions (claude-md)
  • Legacy codebases: Run fullstack-healthcheck first to prioritize what to fix

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.