๐ŸŒ Global Mirror โ€” Visit original CN site โ†’
Back to skills

Best Practices

ASecurity

Code quality guidelines and best practices for writing clean, maintainable code. Covers naming, structure, error handling, testing, and code review standards. Use when writing code, reviewing, refactoring, or asking "how should I name this", "best practice for", "clean code".

18 stars
0 votes
0 copies
15 views
Added 2/11/2026
developmenttypescriptpythonrustgophpreacttestingrefactoringapidatabase

Works with

api

Security Analysis

A100/100

Scanned 2/12/2026

Install via CLI

$openskills install lee-to/ai-factory
Download Zip
SKILL.md
---
name: ai-factory.best-practices
description: Code quality guidelines and best practices for writing clean, maintainable code. Covers naming, structure, error handling, testing, and code review standards. Use when writing code, reviewing, refactoring, or asking "how should I name this", "best practice for", "clean code".
argument-hint: [naming|structure|errors|testing|review]
allowed-tools: Read Glob Grep
---

# Best Practices Guide

Universal code quality guidelines applicable to any language or framework.

## Quick Reference

- `/best-practices` โ€” Full overview
- `/best-practices naming` โ€” Naming conventions
- `/best-practices structure` โ€” Code organization
- `/best-practices errors` โ€” Error handling
- `/best-practices testing` โ€” Testing practices
- `/best-practices review` โ€” Code review checklist

---

## Naming Conventions

### Variables & Functions
```
โœ… Good                          โŒ Bad
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
getUserById(id)                  getUser(i)
isValidEmail                     checkEmail
maxRetryCount                    max
calculateTotalPrice              calc
handleSubmit                     submit
```

**Rules:**
- Use descriptive names that reveal intent
- Avoid abbreviations (except universally known: `id`, `url`, `api`)
- Boolean variables: `is`, `has`, `can`, `should` prefix
- Functions: verb + noun (`fetchUser`, `validateInput`)
- Constants: SCREAMING_SNAKE_CASE
- Classes/Types: PascalCase
- Variables/functions: camelCase (JS/TS/PHP) or snake_case (Python/Rust)

### Files & Directories
```
โœ… Good                          โŒ Bad
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
user-service.ts                  userService.ts (inconsistent)
UserRepository.ts                user_repository.ts (mixed)
/components/Button/              /Components/button/
/services/auth/                  /Services/Auth/
```

**Rules:**
- One convention per project (kebab-case or PascalCase for files)
- Directories: lowercase with hyphens
- Test files: `*.test.ts` or `*.spec.ts` (consistent)
- Index files: only for re-exports, not logic

---

## Code Structure

### Function Design
```typescript
// โœ… Good: Single responsibility, clear inputs/outputs
function calculateDiscount(price: number, discountPercent: number): number {
  if (discountPercent < 0 || discountPercent > 100) {
    throw new Error('Discount must be between 0 and 100');
  }
  return price * (1 - discountPercent / 100);
}

// โŒ Bad: Multiple responsibilities, side effects
function processOrder(order) {
  validateOrder(order);           // validation
  order.discount = getDiscount(); // mutation
  saveToDatabase(order);          // persistence
  sendEmail(order.user);          // notification
  return order;
}
```

```php
// โœ… Good: PHP with type declarations
function calculateDiscount(float $price, float $discountPercent): float
{
    if ($discountPercent < 0 || $discountPercent > 100) {
        throw new InvalidArgumentException('Discount must be between 0 and 100');
    }
    return $price * (1 - $discountPercent / 100);
}
```

**Rules:**
- Single Responsibility: one function = one job
- Max 20-30 lines per function
- Max 3-4 parameters (use object for more)
- No side effects in pure functions
- Early returns for guard clauses

### Module Organization
```
feature/
โ”œโ”€โ”€ index.ts          # Public exports only
โ”œโ”€โ”€ types.ts          # Types and interfaces
โ”œโ”€โ”€ constants.ts      # Constants
โ”œโ”€โ”€ utils.ts          # Pure utility functions
โ”œโ”€โ”€ hooks.ts          # React hooks (if applicable)
โ”œโ”€โ”€ service.ts        # Business logic
โ””โ”€โ”€ repository.ts     # Data access
```

**Rules:**
- Group by feature, not by type
- Clear public API via index.ts
- Internal modules prefixed with `_` or in `internal/`
- Avoid circular dependencies

---

## Error Handling

### Do's and Don'ts
```typescript
// โœ… Good: Specific errors, meaningful messages
class UserNotFoundError extends Error {
  constructor(userId: string) {
    super(`User not found: ${userId}`);
    this.name = 'UserNotFoundError';
  }
}

async function getUser(id: string): Promise<User> {
  const user = await db.users.find(id);
  if (!user) {
    throw new UserNotFoundError(id);
  }
  return user;
}

// โŒ Bad: Generic errors, swallowed exceptions
async function getUser(id) {
  try {
    return await db.users.find(id);
  } catch (e) {
    console.log(e);  // Swallowed!
    return null;     // Hides the problem
  }
}
```

**Rules:**
- Create specific error classes for domain errors
- Never swallow exceptions silently
- Log errors with context (user ID, request ID, etc.)
- Use error boundaries at system edges
- Return Result types for expected failures (optional)

### Error Messages
```
โœ… Good: "Failed to create user: email 'test@example.com' already exists"
โŒ Bad: "Error occurred"
โŒ Bad: "Something went wrong"
```

---

## Testing Practices

### Test Structure (AAA Pattern)
```typescript
describe('calculateDiscount', () => {
  it('should apply percentage discount to price', () => {
    // Arrange
    const price = 100;
    const discount = 20;

    // Act
    const result = calculateDiscount(price, discount);

    // Assert
    expect(result).toBe(80);
  });

  it('should throw for invalid discount percentage', () => {
    expect(() => calculateDiscount(100, -10)).toThrow();
    expect(() => calculateDiscount(100, 150)).toThrow();
  });
});
```

**Rules:**
- One assertion concept per test
- Descriptive test names: "should [expected behavior] when [condition]"
- Test behavior, not implementation
- Use factories/fixtures for test data
- Avoid testing private methods directly

### Test Coverage Priorities
```
1. Critical business logic      โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ Must have
2. Edge cases and boundaries    โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘ Important
3. Integration points           โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ Important
4. Happy paths                  โ–ˆโ–ˆโ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ Basic
5. UI components                โ–ˆโ–ˆโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ Optional
```

---

## Code Review Checklist

### Before Requesting Review
- [ ] Self-reviewed the diff
- [ ] Tests pass locally
- [ ] No debug code (console.log, debugger)
- [ ] No commented-out code
- [ ] Updated documentation if needed
- [ ] Commit messages are clear

### Reviewer Checklist
- [ ] **Correctness**: Does it do what it claims?
- [ ] **Edge cases**: What could go wrong?
- [ ] **Security**: Any vulnerabilities? (see `/security-checklist`)
- [ ] **Performance**: Any obvious bottlenecks?
- [ ] **Readability**: Can I understand it in 5 minutes?
- [ ] **Tests**: Are critical paths covered?
- [ ] **Consistency**: Follows project conventions?

### Review Comments
```
โœ… Good feedback:
"This could throw if `user` is null. Consider adding a null check
or using optional chaining: `user?.profile?.name`"

โŒ Bad feedback:
"This is wrong"
"I don't like this"
"Why did you do it this way?"
```

---

## Quick Rules Summary

| Area | Rule |
|------|------|
| Naming | Descriptive, consistent, reveals intent |
| Functions | Small, single purpose, no side effects |
| Errors | Specific types, never swallow, log context |
| Tests | AAA pattern, test behavior, descriptive names |
| Reviews | Be specific, suggest solutions, be kind |

Comments (0)

No comments yet. Be the first to comment!

Best Practices (Grade A) - Claude Skill | Skills Directory

Stay up to date

Get the latest news on AI tools and skills delivered to your inbox.