MCP HubMCP Hub
SKILL·E8FE9F

go-interface-design

eduardo-sl
업데이트됨 22 days ago
6 조회
68
9
68
GitHub에서 보기
테스팅testingapidesign

정보

이 스킬은 암시적 인터페이스, 소비자 측 정의, 그리고 '인터페이스를 받고 구조체를 반환한다' 원칙을 포함한 Go 인터페이스 설계 패턴에 대한 지침을 제공합니다. 인터페이스를 설계하거나, 패키지를 분리하거나, 계약을 정의하거나, 테스트 가능성을 위해 리팩토링할 때 사용하세요. 이 스킬은 인터페이스 구성, 준수 확인, 그리고 피해야 할 일반적인 함정을 다룹니다.

빠른 설치

Claude Code

추천
기본
npx skills add eduardo-sl/go-agent-skills -a claude-code
플러그인 명령대체
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 클론대체
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-interface-design

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Go Interface Design

Go interfaces are implicit. This is the single most important design feature of the language, and most people coming from Java or C# get it wrong at first.

1. The Cardinal Rule: Define Interfaces at the Consumer

The consumer of a behavior defines the interface, NOT the provider:

// ❌ Wrong — producer defines interface (Java thinking)
// package store
type UserStore interface {      // defined alongside implementation
    GetByID(ctx context.Context, id string) (*User, error)
    Create(ctx context.Context, user *User) error
    // ... 15 more methods
}

type PostgresStore struct { ... }
func (s *PostgresStore) GetByID(...) { ... }
func (s *PostgresStore) Create(...) { ... }

// ✅ Right — consumer defines what it needs
// package service
type UserReader interface {     // only what THIS service needs
    GetByID(ctx context.Context, id string) (*domain.User, error)
}

type UserService struct {
    store UserReader  // depends on narrow interface
}

// package store (no interface defined here)
type PostgresStore struct { db *sql.DB }
func (s *PostgresStore) GetByID(ctx context.Context, id string) (*domain.User, error) { ... }
func (s *PostgresStore) Create(ctx context.Context, user *domain.User) error { ... }

// PostgresStore satisfies service.UserReader implicitly — no declaration needed

Why this matters:

  • Consumer depends only on what it uses (Interface Segregation Principle).
  • Producer can add methods without breaking consumers.
  • Testing requires only the methods the consumer calls.
  • No import cycle: consumer doesn't import producer's package.

2. Keep Interfaces Small

The bigger the interface, the weaker the abstraction.

// ✅ Good — focused, composable
type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

type ReadWriter interface {
    Reader
    Writer
}

// ❌ Bad — kitchen sink interface
type FileManager interface {
    Read(path string) ([]byte, error)
    Write(path string, data []byte) error
    Delete(path string) error
    List(dir string) ([]string, error)
    Move(src, dst string) error
    Copy(src, dst string) error
    Stat(path string) (os.FileInfo, error)
    Watch(path string) (<-chan Event, error)
}

Guideline: 1-3 methods is ideal. If you need more, compose smaller interfaces.

3. Accept Interfaces, Return Structs

// ✅ Good — accepts interface, returns concrete type
func NewUserService(store UserReader, logger Logger) *UserService {
    return &UserService{store: store, logger: logger}
}

// ❌ Bad — returns interface (hides the concrete type for no reason)
func NewUserService(store UserReader) UserServiceInterface {
    return &UserService{store: store}
}

Return a concrete type so callers get full access to the type's methods. Returning an interface only makes sense when the function genuinely returns different concrete types based on input (factory pattern).

4. Verify Interface Compliance at Compile Time

Use the blank identifier assignment to catch broken contracts early:

// Verify *PostgresStore implements service.UserReader at compile time
var _ service.UserReader = (*PostgresStore)(nil)

// Verify LogHandler implements http.Handler
var _ http.Handler = (*LogHandler)(nil)

// For value receivers:
var _ fmt.Stringer = Status(0)

Place these immediately after the type declaration. They cost nothing at runtime and prevent silent contract breakage.

5. Don't Use Pointers to Interfaces

// ❌ Bad — pointer to interface is almost never correct
func process(r *io.Reader) { ... }

// ✅ Good — interface is already a pointer internally
func process(r io.Reader) { ... }

An interface value is internally two pointers (type + data). A pointer to an interface is a pointer to a pointer — needless indirection.

The only exception: when you need to replace the interface value itself (swap the implementation at runtime), which is extremely rare.

6. The Empty Interface

interface{} (or any in Go 1.18+) means you've given up on type safety. Use it sparingly:

// ✅ Acceptable — generic container before generics / stdlib compatibility
func Marshal(v any) ([]byte, error)

// ✅ Better (Go 1.18+) — use generics instead of any
func Map[T, U any](slice []T, fn func(T) U) []U { ... }

// ❌ Bad — lazy interface design
func Process(data any) any { ... } // what does this even do?

7. Functional Options Pattern

When a constructor needs optional configuration, use functional options instead of a config struct with an interface:

type Option func(*Server)

func WithTimeout(d time.Duration) Option {
    return func(s *Server) { s.timeout = d }
}

func WithLogger(l Logger) Option {
    return func(s *Server) { s.logger = l }
}

func NewServer(addr string, opts ...Option) *Server {
    s := &Server{
        addr:    addr,
        timeout: 30 * time.Second,  // sensible default
        logger:  slog.Default(),    // default stdlib logger
    }
    for _, opt := range opts {
        opt(s)
    }
    return s
}

// Usage
srv := NewServer(":8080",
    WithTimeout(60 * time.Second),
    WithLogger(logger),
)

8. Common Interface Anti-Patterns

Premature interfaces:

// ❌ Bad — interface defined before second implementation exists
type Processor interface {
    Process(ctx context.Context, data []byte) error
}

type processor struct { ... }  // only one implementation ever

// ✅ Good — use concrete type until you need the abstraction
type Processor struct { ... }
// Add interface when you have 2+ implementations or need testing seam

"Don't design with interfaces, discover them." — Rob Pike

Interface pollution:

// ❌ Bad — wrapping every struct in an interface "for testability"
type UserServiceInterface interface { ... }
type OrderServiceInterface interface { ... }
type PaymentServiceInterface interface { ... }
// 50 more interfaces with exactly one implementation each

// ✅ Good — define interfaces where they're consumed
// Each consumer declares only the methods IT needs

Misusing interfaces for enums:

// ❌ Bad — interface used as enum/sum type
type Shape interface {
    isShape()
}
type Circle struct{}
func (Circle) isShape() {}

// ✅ Better — sealed interface pattern (if you need it)
// Or just use constants with a type
type ShapeKind int
const (
    ShapeCircle ShapeKind = iota
    ShapeRectangle
)

Decision Checklist

  1. Do I need an interface here? — Only if you have 2+ implementations, need a testing seam, or are crossing a package boundary.
  2. Where should it be defined? — At the consumer, not the producer.
  3. How many methods? — Fewer is better. 1-3 is ideal.
  4. Am I returning an interface? — Probably shouldn't. Return concrete.
  5. Have I verified compliance?var _ Interface = (*Type)(nil)

GitHub 저장소

eduardo-sl/go-agent-skills
경로: skills/(architecture)/go-interface-design
0
FAQ

자주 묻는 질문

go-interface-design Skill이란 무엇인가요?

go-interface-design은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-interface-design 관련 작업을 수행할 수 있게 합니다.

go-interface-design은(는) 어떻게 설치하나요?

이 페이지의 설치 명령을 사용하세요. go-interface-design을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.

go-interface-design은(는) 어떤 카테고리에 속하나요?

go-interface-design은(는) 테스팅 카테고리에 속합니다.

go-interface-design은(는) 무료로 사용할 수 있나요?

네. go-interface-design은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.

연관 스킬

evaluating-llms-harness
테스팅

이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.

스킬 보기
cloudflare-cron-triggers
테스팅

이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.

스킬 보기
webapp-testing
테스팅

이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.

스킬 보기
finishing-a-development-branch
테스팅

이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.

스킬 보기