# Codewriter Skill

> Code Writer Expert

- Skill: `sirhamza/codewriter-skill` (Agent Skill)
- Install (CLI): `npx skillmds@latest add sirhamza/codewriter-skill`
- Raw SKILL.md: https://api.skillmd.com/api/skills/sirhamza/codewriter-skill/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: SirHamza (https://skillmd.com/u/sirhamza)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/sirhamza/codewriter-skill

---

# Code Writer Expert

## Overview
Advanced expertise in writing clean, production-ready, idiomatic code across multiple languages and paradigms. Specialized in designing well-structured functions, classes, modules, and systems with a focus on correctness, readability, testability, performance, and security.

Use this skill with `/codewriter-skill` to get expert code writing, refactoring, design, or generation for any language or framework.

---

## 1. Code Writing Principles

- **Clarity first**: code is read far more than it is written — optimize for the reader
- **Single Responsibility**: each function/class does one thing and does it well
- **DRY (Don't Repeat Yourself)**: extract duplication into named abstractions
- **YAGNI**: only write code that is needed now — no speculative generality
- **Fail fast**: validate inputs early, surface errors explicitly, never swallow exceptions
- **Minimal surface area**: expose only what callers need, keep internals private
- **Immutability preference**: prefer immutable data structures and pure functions
- **Explicit over implicit**: readable names, clear types, no magic numbers/strings

---

## 2. Naming Conventions

| Construct | Convention | Example |
|---|---|---|
| Variables | descriptive nouns | `userCount`, `isLoading` |
| Functions | verb phrases | `fetchUser()`, `parseConfig()` |
| Booleans | is/has/can prefix | `isValid`, `hasPermission` |
| Constants | SCREAMING_SNAKE | `MAX_RETRIES`, `DEFAULT_TIMEOUT` |
| Classes | PascalCase nouns | `UserRepository`, `PaymentService` |
| Interfaces | PascalCase (no I prefix) | `Repository`, `EventEmitter` |
| Files | kebab-case or snake_case | `user-service.ts`, `auth_utils.py` |
| Tests | describe what + when + expected | `returns_error_when_email_is_empty` |

---

## 3. Function Design

- **Keep functions short**: aim for < 20 lines; if longer, extract sub-functions
- **Max 3 parameters**: beyond that, use an options object/struct/dataclass
- **No side effects in pure functions**: separate computation from I/O
- **Early returns**: reduce nesting by returning/throwing early on invalid conditions
- **Guard clauses**: validate preconditions at the top before main logic
- **One level of abstraction per function**: don't mix high-level orchestration with low-level details
- **Command-Query Separation**: functions either do something OR return something, not both
- **Avoid flag parameters**: split into two functions instead of `doThing(flag: bool)`

```python
# Bad
def process(data, dry_run=False):
    result = compute(data)
    if not dry_run:
        save(result)
    return result

# Good
def compute_result(data): ...
def save_result(result): ...
```

---

## 4. Class & Module Design

- **SOLID principles**:
  - *S* — Single Responsibility
  - *O* — Open/Closed (extend via composition, not modification)
  - *L* — Liskov Substitution (subtypes are substitutable)
  - *I* — Interface Segregation (small, focused interfaces)
  - *D* — Dependency Inversion (depend on abstractions)
- **Composition over inheritance**: prefer has-a over is-a relationships
- **Dependency injection**: pass dependencies in; don't instantiate them inside
- **Factory functions/classes**: encapsulate complex construction logic
- **Repository pattern**: abstract data access behind an interface
- **Service layer**: encapsulate business logic separately from controllers/routes

---

## 5. Error Handling

- **Never swallow errors silently**: always log or re-raise
- **Use domain errors**: define typed error classes (not just `Error("something failed")`)
- **Result types**: use `Result<T, E>` or `Either` patterns for expected failures
- **Exception vs error return**: exceptions for unexpected failures; return errors for expected ones
- **Error messages**: include what went wrong, where, and what the caller can do

```typescript
// TypeScript Result pattern
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

function parseId(raw: string): Result<number, string> {
  const n = parseInt(raw, 10);
  if (isNaN(n)) return { ok: false, error: `Invalid ID: "${raw}"` };
  return { ok: true, value: n };
}
```

---

## 6. Language-Specific Best Practices

### TypeScript / JavaScript
- Strict mode: `"strict": true` in tsconfig
- Prefer `const` → `let` → never `var`
- Optional chaining `?.` and nullish coalescing `??` over explicit null checks
- `async/await` over raw Promises and callback chains
- Use `unknown` over `any`; narrow types explicitly
- Zod / Valibot for runtime validation at boundaries

### Python
- Type annotations on all public functions/methods
- Dataclasses or Pydantic models over plain dicts
- `pathlib.Path` over `os.path` string manipulation
- Context managers for resource management
- `__slots__` for performance-critical classes
- `logging` module over print statements

### Go
- Errors as values: always handle `err != nil`
- Interfaces implicitly satisfied — keep them small (1-3 methods)
- Goroutines + channels for concurrency; use `context.Context` for cancellation
- `defer` for cleanup, not just error handling
- Table-driven tests with `t.Run`

### Rust
- Ownership and borrowing — prefer references over clones
- `Result<T, E>` and `Option<T>` over panics at boundaries
- `thiserror` for library errors, `anyhow` for application errors
- Iterators over manual loops
- `#[derive(Debug, Clone, PartialEq)]` on data structs

### Java / Kotlin
- Immutable data with `record` (Java 16+) or `data class` (Kotlin)
- Builder pattern for objects with many optional fields
- `Optional<T>` for nullable return values (Java); `?` types (Kotlin)
- Stream API / sequences for collection processing
- Constructor injection for dependencies

---

## 7. Code Structure Patterns

### Repository Pattern
```typescript
interface UserRepository {
  findById(id: string): Promise<User | null>;
  save(user: User): Promise<void>;
  delete(id: string): Promise<void>;
}

class PostgresUserRepository implements UserRepository { ... }
class InMemoryUserRepository implements UserRepository { ... } // for tests
```

### Service Layer
```python
class OrderService:
    def __init__(self, orders: OrderRepository, payments: PaymentGateway):
        self._orders = orders
        self._payments = payments

    def place_order(self, cart: Cart, payment: PaymentDetails) -> Order:
        order = Order.from_cart(cart)
        self._payments.charge(payment, order.total)
        self._orders.save(order)
        return order
```

### Builder Pattern
```typescript
class QueryBuilder {
  private _table = "";
  private _conditions: string[] = [];
  private _limit?: number;

  table(name: string) { this._table = name; return this; }
  where(condition: string) { this._conditions.push(condition); return this; }
  limit(n: number) { this._limit = n; return this; }
  build(): string { ... }
}
```

---

## 8. Testing-Friendly Code

- **Dependency injection**: makes unit testing easy — swap real deps for mocks
- **Pure functions**: no mocking needed — input → output is deterministic
- **Small functions**: easy to test in isolation
- **Avoid global state**: global mutable state makes tests order-dependent
- **Interfaces at boundaries**: mock at interface boundaries, not concrete implementations
- **Seams**: design code to have natural injection points for test doubles
- **Test naming**: `<unit>_<scenario>_<expected>` — e.g., `login_with_wrong_password_returns_401`

---

## 9. Performance-Aware Code Writing

- Avoid premature optimization — profile first, optimize after
- Prefer O(n) over O(n²) by using sets/maps for lookups
- Lazy evaluation: generators, iterators, streams over eagerly-loaded collections
- Batch DB queries instead of N+1 loops
- Cache pure function results with memoization
- Avoid allocations in hot paths (object pooling, pre-allocated buffers)
- Use streaming for large file/data processing

---

## 10. Security-Aware Code Writing

- **Input validation**: validate at every system boundary — never trust external data
- **Parameterized queries**: never concatenate user input into SQL
- **Output encoding**: escape HTML/JS output to prevent XSS
- **Secrets in env vars**: never hardcode tokens, passwords, or keys
- **Least privilege**: request only the permissions your code actually needs
- **Safe deserialization**: validate schemas before unmarshalling untrusted JSON/YAML
- **Path traversal prevention**: sanitize file paths; use allowlists
- **Timing-safe comparisons**: use constant-time comparison for secrets/tokens

---

## 11. Code Review Checklist

- [ ] Does the code do what the ticket/spec says?
- [ ] Are edge cases handled (empty, null, large input, concurrency)?
- [ ] Are errors handled and surfaced appropriately?
- [ ] Are names descriptive and consistent with existing conventions?
- [ ] Is there unnecessary complexity or duplication?
- [ ] Are there tests, and do they cover the important paths?
- [ ] Are there any security issues (injection, exposure, auth bypass)?
- [ ] Does it perform acceptably under expected load?
- [ ] Are public APIs documented?
- [ ] Are there any TODO/FIXME that should be issues instead?

---

## 12. Refactoring Techniques

- **Extract Function**: pull repeated or complex logic into a named function
- **Inline Function**: remove unnecessary indirection when function body is self-evident
- **Extract Variable**: name complex expressions for readability
- **Replace Magic Number**: introduce a named constant
- **Introduce Parameter Object**: group related parameters into a struct/object
- **Replace Conditional with Polymorphism**: use strategy/factory instead of large if/switch
- **Decompose Conditional**: extract complex boolean logic into named predicate functions
- **Replace Temp with Query**: replace variables computed once with functions

---

## Core Competency Summary

- Write clean, idiomatic, production-ready code in Python, TypeScript, Go, Rust, Java, and more
- Design functions, classes, and modules following SOLID principles
- Apply naming conventions, error handling, and guard clause patterns consistently
- Structure code for testability via dependency injection and pure functions
- Write security-aware code at every boundary
- Recognize and apply structural patterns: Repository, Service, Builder, Strategy
- Perform disciplined refactoring using established techniques
- Write code that passes review: correct, clear, tested, and performant

