Logo Clean Code

Clean Code

Tổ chức
cosmicstack-labs
clean-code

Principles and practices for writing readable, maintainable, and testable code

Tổng quan

Nhà phát hànhcosmicstack-labs
Kho mãmercury-agent-skills
Tên kỹ năngclean-code
Sao
485
Bản fork
63
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được cosmicstack-labs công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Clean Code trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/development/clean-code
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/cosmicstack-labs/mercury-agent-skills.git /tmp/mercury-agent-skills
mkdir -p .claude/skills
cp -r /tmp/mercury-agent-skills/categories/development/clean-code .claude/skills/clean-code
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Clean Code trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Clean Code ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Clean Code không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Clean Code

Write code that humans can read, understand, and change with confidence.

Core Principles

1. Mean What You Say — Say What You Mean

Code is communication. Every name, structure, and abstraction should reveal intent. If you need a comment to explain what the code does, the code is failing at communication.

2. Small Things, Done Well

Small functions, small classes, small files. Each unit of code should have one clear responsibility and do it well. Composability beats complexity.

3. The Boy Scout Rule

Leave the code cleaner than you found it. Every commit should improve the codebase incrementally — even if it's just renaming one variable or extracting one function.

4. Testability == Design Quality

If code is hard to test, it has a design problem. Testable code is modular, decoupled, and honest about its dependencies.


Clean Code Scoring Rubric

Use this rubric to evaluate code quality on a scale of 1-5 for each dimension:

Dimension1 (Poor)3 (Adequate)5 (Excellent)
NamingSingle-letter vars, ambiguous abbreviationsDescriptive but occasionally redundantReveals intent, consistent, searchable
Function SizeMonolithic 500+ line functions50-100 line functions with mixed concerns<20 lines, one clear level of abstraction
CommentsOutdated or redundant commentsComments explain what not whyMinimal comments, code is self-documenting
Error HandlingSilent catches, magic error codesBasic try/catch, some error typesRich error types, graceful degradation
TestingNo tests or brittle testsTests exist but tightly coupled to implementationTests specify behavior, not implementation
DuplicationCopy-paste everywhereSome reuse, some DRY violationsDRY with well-abstracted patterns

Target: 4+ in every dimension for production-grade code.


Actionable Guidance

Naming

Rules:

  • Boolean variables: Use positive names (isActive, hasPermission, shouldRetry). Avoid negated names like isNotDisabled.
  • Functions/methods: Verbs or verb phrases (calculateTotal(), validateInput(), fetchUser()).
  • Classes/types: Nouns or noun phrases (UserAccount, PaymentProcessor, HttpClient).
  • Constants: UPPER_SNAKE_CASE (MAX_RETRY_COUNT, DEFAULT_TIMEOUT_MS).
python
# Bad
def proc(d):
    r = []
    for i in d:
        if i.get('a') == True:
            r.append(i.get('n'))
    return r

# Good
def extract_active_user_names(users):
    active_users = [user for user in users if user['is_active']]
    return [user['name'] for user in active_users]

Searchable names: Avoid single-letter variables except in trivial loops. Use names that can be found with grep.

Functions

Rules:

  • One level of abstraction per function: A function should mix high-level logic (e.g., "fetch data") with mid-level logic (e.g., "parse CSV line") or low-level (e.g., "trim whitespace") — never all three.
  • 3-4 parameters max: More than 4 suggests the function does too much. Bundle related params into objects.
  • No side effects: Prefer pure functions. If a function must mutate state, make it obvious (name it setX(), updateY()).
  • DRY but not at cost of clarity: Extract duplication into shared helpers, but don't create overly abstracted indirection for code that appears only twice.
javascript
// Bad: Mixed abstraction levels
function processOrder(order) {
  const tax = order.total * 0.08;                       // Low-level calc
  order.totalWithTax = order.total + tax;                // Mutation
  fs.writeFileSync(`orders/${order.id}.json`, JSON.stringify(order)); // Side effect
  sendEmailNotification(order.userEmail, 'Order processed'); // Side effect
  return order.totalWithTax;
}

// Good: Clear single responsibility
function calculateTotalWithTax(total, taxRate) {
  return total + (total * taxRate);
}

Comments

When to comment:

  • Tricky business logic: Why a specific algorithm was chosen
  • Non-obvious tradeoffs: Why you chose A over B
  • Legal/copyright: Required attribution
  • Warnings: // FIXME: This endpoint is rate-limited to 100 req/min

When NOT to comment:

  • Stating the obvious (// Increment counter)
  • Commenting-out dead code — delete it. Git remembers.
  • Writing a novel — if you need paragraphs, your code needs refactoring.

Error Handling

Patterns:

python
# Prefer specific exception types
def get_user(user_id):
    try:
        return database.fetch_user(user_id)
    except DatabaseConnectionError:
        logger.error(f"Database unavailable when fetching user {user_id}")
        raise ServiceUnavailableError("User service temporarily unavailable")
    except UserNotFoundError:
        logger.info(f"User {user_id} not found")
        return None  # Expected case, not exceptional

Guidelines:

  • Fail fast: Validate inputs at boundaries. Don't let bad data propagate.
  • Return typed errors: Use Result[T, E] types (Rust, Swift) or Either (functional languages) instead of exceptions for expected failures.
  • Never swallow exceptions: Empty catch blocks are a code smell. At minimum, log and re-raise.
  • Use error codes sparingly: HTTP status codes make sense at API boundaries. Inside your application, use typed errors.

Testing

The Testing Trophy (not pyramid):

     E2E Tests  (few)
    Integration (some)
   Unit Tests   (many)
  Static Analysis (all code)

Guidelines:

  • Test behavior, not implementation. Your tests should pass after a refactor if the behavior didn't change.
  • One assertion concept per test. Use multiple it() blocks rather than multiple asserts in one.
  • Use realistic test data. "foo" and 123 don't catch edge cases.
  • For AI-generated code: always verify with tests. The AI writes the code, you write the tests.
python
# Bad: Tests implementation details
def test_get_user():
    mock_db = MagicMock()
    service = UserService(mock_db)
    result = service._fetch_and_transform_user(42)  # Testing private method
    assert mock_db.execute.called_once_with("SELECT * FROM users WHERE id=42")

# Good: Tests behavior
def test_get_user_returns_user_when_found():
    user_repo = InMemoryUserRepository([User(id=42, name="Alice")])
    service = UserService(user_repo)
    result = service.get_user(42)
    assert result.name == "Alice"

def test_get_user_returns_none_when_not_found():
    user_repo = InMemoryUserRepository([])
    service = UserService(user_repo)
    result = service.get_user(99)
    assert result is None

Code Smells to Hunt

SmellSymptomFix
Long Method>20 lines doing multiple thingsExtract methods, compose
Switch/TypesSwitch on type enum, then dispatchPolymorphism or strategy pattern
Feature EnvyMethod uses more of another class's data than its ownMove method to the right class
Shotgun SurgeryOne change requires edits in many filesConsolidate related logic
Data ClumpsSame 3-4 fields appear together repeatedlyExtract into a value object
Primitive ObsessionUsing strings/ints where types belongCreate domain types
Inappropriate IntimacyClass knows too much about another's internalsReduce coupling, use interfaces

Common Mistakes

  1. Over-optimizing for performance before clarity: 99% of code doesn't need micro-optimization. Write clear code first, profile, then optimize the hot paths.
  2. Over-engineering: YAGNI (You Ain't Gonna Need It). Don't add abstractions for hypothetical future needs.
  3. Perfect as enemy of good: Clean code is a journey, not a destination. Incremental improvement beats paralysis.
  4. Ignoring the team's conventions: Consistency within a codebase matters more than personal preference for a particular style.
  5. Applying rules blindly: All rules have exceptions. goto in C error handling is fine. Single-letter variables in math-heavy code are fine. Context matters.

Câu hỏi thường gặp

Kỹ năng AI Clean Code làm được gì?

Principles and practices for writing readable, maintainable, and testable code

Vì sao nên dùng Clean Code trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Clean Code là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Clean Code trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/development/clean-code. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Clean Code?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Clean Code với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Clean Code với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Clean Code có miễn phí không?

Có. Kỹ năng này được cosmicstack-labs phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇