본문으로 건너뛰기
cccskills
무료GitHub에 공개

anti-defensive

Review common AI slops of defensive programming patterns, avoid silent errors. TRIGGER when reviewing code for defensive anti-patterns, writing fail-fast code, or auditing error handling quality.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md6.2 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Anti-Defensive Programming Guide

Philosophy

AI coding assistants systematically over-produce defensive code due to:

  • Training data bias — Web/app code dominates GitHub, where graceful degradation IS correct
  • RLHF reinforcement — Humans penalize crashes more than silent incorrectness

The result: code that swallows errors, fabricates data, and fails silently instead of failing fast.

Fail-fast principle: Internal errors should crash immediately and loudly. Problems get fixed instead of hidden. Systems that fail fast actually have fewer outages because they are honest about what can go wrong.

When defensive IS correct: At system boundaries handling external input (APIs, user forms, file uploads). Internal code should trust contracts and crash on violations.

Anti-Patterns

1. Swallowing Exceptions

# BAD — Error buried, pipeline continues with None
try:
    result = transform(data)
except Exception as e:
    logger.warning(f"Transform failed: {e}")
    result = None

# GOOD — Let it fail
result = transform(data)

Harm: Downstream code receives None, causing JOIN failures or corrupted data. Monitoring shows "fine" because no exceptions were thrown.

2. Dictionary Defaults on Required Fields

# BAD — Fabricates data for missing required field
user_id = record.get('user_id', -1)
amount = record.get('amount', 0.0)

# GOOD — Required fields should error if missing
user_id = record['user_id']
amount = record['amount']

Harm: The -1 user_id joins with user tables, returns nothing, analytics silently show zero activity.

3. Null Coalescing to Fabricate Data

# BAD — Invisible default, hides missing data
email = record.get('email') or 'no-email@example.com'
price = data.get('price') or 0.0

# GOOD — Explicit handling
email = record['email']  # Required
price = record.get('price')  # Nullable is intentional
if price is None:
    price = calculate_default_price(record)

Harm: The or operator makes defaults invisible. If a default is needed, make it explicit and documented.

4. Type Coercion Instead of Validation

# BAD — Silently converts wrong type, hides upstream bug
age = int(record.get('age', 0))
price = float(str(record.get('price', '0.0')))

# GOOD — Let type mismatches surface
age = record['age']
assert isinstance(age, int), f"Expected int, got {type(age)}"

Harm: Type mismatches indicate upstream problems. Coercing them hides the root cause.

5. Compatibility Shims

# BAD — Turns temporary debt into permanent debt
try:
    result = new_api_call(params)
except AttributeError:
    result = old_api_call(params)

# GOOD — Force migration
result = new_api_call(params)

Harm: Breaking changes remain undetected. Technical debt compounds.

6. Unnecessary Null Checks

# BAD — Misleading; type contract guarantees non-null
if user is not None and user.name is not None:
    return user.name

# GOOD — Trust the contract
return user.name

Harm: Readers assume the value can be null. Checks multiply across codebase.

7. Catch-All Exception Handlers

# BAD — Catches KeyboardInterrupt, SystemExit, MemoryError
try:
    process(data)
except:
    pass

# GOOD — Catch specific exceptions or let them propagate
try:
    process(data)
except ValidationError as e:
    raise ValueError(f"Invalid data: {e}") from e

Harm: Catches things no programmer should handle. Masks real problems.

8. Over-Validation at Internal Boundaries

# BAD — Validates what caller already guarantees
def process(data):
    if data is None:
        return None
    if not isinstance(data, dict):
        return None
    if 'id' not in data:
        return None
    return transform(data['id'])

# GOOD — Validate once at boundary, trust internally
def process(data: dict) -> Result:
    """Expects data with 'id' key. Validated at API boundary."""
    return transform(data['id'])

Harm: Validation logic duplicates across call chain. Returns None instead of surfacing contract violations.

9. Fabricated Default Values

# BAD — Corrupts data with fake values
created_at = record.get('created_at', datetime.now())
name = record.get('name', '')
status = record.get('status', 'unknown')

# GOOD — Required fields must be present
created_at = record['created_at']
name = record['name']
status = record.get('status')  # Only if nullable by design

Harm: Historical records get current timestamps. Empty names break downstream logic. 'unknown' status corrupts analytics.

10. Logging Warnings Instead of Raising

# BAD — Warnings are ignored
logger.warning(f"Unexpected state: {state}")
continue

# GOOD — Errors demand attention
raise ValueError(f"Unexpected state: {state}")

Harm: Problems remain undetected until they cascade into larger failures.

When Defensive IS Correct

Defensive programming is appropriate at system boundaries:

  • External input validation — API payloads, form submissions, file uploads
  • User-facing error messages — Graceful UX for invalid user actions
  • Transient failures — Network timeouts, rate limits, temporary resource unavailability
  • Public libraries — Cannot control caller behavior

Internal code should trust contracts and fail fast on violations.

Quick Reference

PatternAnti-PatternCorrect Approach
Exception handlingexcept Exception: passLet it crash or catch specific
Dict accessd.get('required', default)d['required']
Null coalescingx or fake_valueExplicit if None logic
Type coercionint(d.get('x', 0))Let type errors surface
Compatibilitytry: new except: oldMigrate to new
Null checksCheck guaranteed valuesTrust contracts
Catch-allexcept:Specific exceptions
ValidationValidate at every functionValidate at boundary once
DefaultsFabricate required valuesRequire presence
Errorslogger.warning()raise ValueError()

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Browser automation CLI for AI agents. Use when needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. TRIGGER when user requests to "open a website", "fill out a form", "click a button", "take a screenshot", "debug this in browser", "scrape data from a page", "test this web app", "login to a site", "frontend UI/UX aesthetics", "automate browser actions", or any task requiring programmatic web interaction.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

archibate/dotfiles-opencode1082026년 4월 29일 업데이트

ast-grep

무료

Guide for writing ast-grep rules to perform structural code search and analysis. This skill should be used when users need to search codebases using Abstract Syntax Tree (AST) patterns, find specific code structures, or perform complex code queries that go beyond simple text search, or when a simple grep/glob search is insufficient for structural code pattern matching.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

archibate/dotfiles-opencode1082026년 4월 29일 업데이트

Best practices for AI-driven English-to-Chinese translation. This skill should be used when the user asks to "translate to Chinese", "update the Chinese translation", "improve Chinese translation", "fix translation quality", "review Chinese translation", or when translating any English text into Chinese. Also applies when polishing an existing Chinese translation of English content.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

archibate/dotfiles-opencode1082026년 4월 29일 업데이트

This skill should be used when the user asks to "use bilibili API", "download bilibili video", "get bilibili user info", "list bilibili favorites", "send bilibili danmaku", "upload video to bilibili", "monitor bilibili live room", "search bilibili", "get bilibili comments", or needs guidance on the bilibili_api Python library usage, authentication, API endpoints, or workflow patterns.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

archibate/dotfiles-opencode1082026년 4월 29일 업데이트

This skill should be used when sending images, files, or notifications back to the user via messaging platforms (Discord, Feishu, Telegram, etc.) through cc-connect. TRIGGER when agent generates a plot/chart/screenshot and wants to show the user; agent creates a report/PDF/file the user should receive; agent needs to proactively notify the user (e.g. task completed, alert, reminder); user asks to "send image", "show me the chart", "notify me", "send the file", "send to Telegram", "show plot in Discord".

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

archibate/dotfiles-opencode1082026년 4월 29일 업데이트

Interact with local Chrome browser session (only on explicit user approval after being asked to inspect, debug, or interact with a page open in Chrome)

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

archibate/dotfiles-opencode1082026년 4월 29일 업데이트

archibate의 스킬 모두 보기

이 스킬의 문제 신고