Przejdź do treści
Biblioteka skilli
Programowanie · Przegląd i audyt

universal-patterns

/universal-patterns

Podpowiada organizację kodu, obsługę błędów, przepływ danych, nazewnictwo i antywzorce w dowolnym języku programowania.

Repozytorium
magus ↗
Licencja
MIT
Ostatnia zmiana repozytorium
26.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 26.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Podpowiada organizację kodu, obsługę błędów, przepływ danych, nazewnictwo i antywzorce w dowolnym języku programowania.

Oryginalny opis (EN)

Code organization, error handling, data flow, naming and anti-patterns in any language. Use while writing or reviewing everyday code. Do not use to choose a system shape or a design pattern — read the architecture skill instead.

Jak działa

  1. Overview
  2. The deep catalog lives next door — read it for any real design decision
  3. Code Organization Principles
  4. Error Handling Patterns
  5. Data Flow Patterns
  6. Naming Conventions
  7. Code Quality Checklist
  8. Anti-Patterns to Avoid
  9. Performance Principles
  10. Security Principles
Sekcje z nagłówków SKILL.md, w oryginale · 319 linii, 1 346 słów
Podgląd SKILL.md
---
name: universal-patterns
description: "Code organization, error handling, data flow, naming and anti-patterns in any language. Use while writing or reviewing everyday code. Do not use to choose a system shape or a design pattern — read the architecture skill instead."
user-invocable: false
---

# Universal Development Patterns

## Overview

Language-agnostic development patterns and best practices applicable across all technology stacks.

## The deep catalog lives next door — read it for any real design decision

**This file is the quick reference.** It carries enough to keep everyday code honest. It is
deliberately shallow on architecture, and it contains **none** of the 22 GoF design
patterns.

For anything beyond a reminder — choosing a style, comparing two, or picking a design
pattern — **read the `architecture` skill's index**, then follow where it routes you:

```
<dev-plugin-root>/skills/architecture/SKILL.md
```

Locate it relative to this plugin's root, which covers both the installed-cache and
local-source layouts:

```bash
ls "${CLAUDE_PLUGIN_ROOT}/skills/architecture/SKILL.md" 2>/dev/null \
  || ls "$(dirname "$(dirname "$(pwd)")")"/plugins/dev/skills/architecture/SKILL.md 2>/dev/null
```

That index routes in two steps: **altitude first** (is this about system shape or class
collaboration), then the specific file. What it covers, none of which is below:

| Tier | Files | Contents |
|---|---|---|
| Architectural styles | `references/styles/*.md` | layered, hexagonal (ports and adapters), clean, modular monolith, microservices, event-driven, CQRS + event sourcing |
| GoF categories | `references/{creational,structural,behavioral}.md` | the shared framing for each family |
| GoF patterns | `references/patterns/*.md` | all 22, with TypeScript, trade-offs, and when not to use each |
| Selection | `references/selection.md` | how to choose, overuse smells, and where TypeScript already gives you the pattern free |

Answer architecture questions from those files: they carry the trade-offs and failure
modes that decide whether a choice is right.

## Code Organization Principles

### Single Responsibility

Each module/function should do ONE thing well.

```
// BAD: Multiple responsibilities
function processUser(user) {
  validateUser(user);
  saveToDatabase(user);
  sendEmail(user);
  logAnalytics(user);
}

// GOOD: Single responsibility
function validateUser(user) { /* validation only */ }
function saveUser(user) { /* persistence only */ }
function notifyUser(user) { /* notification only */ }
```

### Dependency Injection

Inject dependencies rather than creating them internally.

```
// BAD: Hard dependency
class UserService {
  constructor() {
    this.db = new Database(); // Hard-coded
  }
}

// GOOD: Injected dependency
class UserService {
  constructor(db) {
    this.db = db; // Injected
  }
}
```

### Interface Segregation

Prefer many specific interfaces over one general interface.

```
// BAD: Fat interface
interface Worker {
  work();
  eat();
  sleep();
}

// GOOD: Segregated interfaces
interface Workable { work(); }
interface Eatable { eat(); }
interface Sleepable { sleep(); }
```

## Error Handling Patterns

### Fail Fast

Validate inputs early and fail immediately on invalid data.

```
function processOrder(order) {
  // Validate early
  if (!order) throw new Error('Order required');
  if (!order.items?.length) throw new Error('Order must have items');
  if (!order.customerId) throw new Error('Customer ID required');

  // Process only after validation passes
  return executeOrder(order);
}
```

### Error Boundaries

Contain errors at appropriate boundaries.

```
// API boundary - catch and format errors
async function apiHandler(req, res) {
  try {
    const result = await processRequest(req);
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(error.statusCode || 500).json({
      success: false,
      error: error.message
    });
  }
}
```

### Result Types (Where Supported)

Use Result/Either types instead of exceptions for expected failures.

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

function parseConfig(input: string): Result<Config, ParseError> {
  try {
    return { ok: true, value: JSON.parse(input) };
  } catch (e) {
    return { ok: false, error: new ParseError(e.message) };
  }
}
```

## Data Flow Patterns

### Unidirectional Data Flow

Data flows in one direction through the application.

```
Action → Dispatcher → Store → View → Action
```

### Event-Driven Architecture

Decouple components through events.

```
// Publisher
eventBus.emit('user.created', { userId: '123' });

// Subscriber
eventBus.on('user.created', async (event) => {
  await sendWelcomeEmail(event.userId);
});
```

### Command Query Separation (CQS)

Separate commands (mutations) from queries (reads).

```
// Query - returns data, no side effects
function getUser(id) { return db.users.find(id); }

// Command - mutates data, returns void/status
function updateUser(id, data) { db.users.update(id, data); }
```

## Naming Conventions

### Functions

| Type | Convention | Examples |
|------|------------|----------|
| Actions | verb + noun | `createUser`, `deleteOrder`, `validateInput` |
| Queries | get/find/is/has + noun | `getUser`, `findOrders`, `isValid`, `hasPermission` |
| Handlers | handle + event | `handleClick`, `handleSubmit`, `handleError` |
| Callbacks | on + event | `onSuccess`, `onError`, `onChange` |

### Variables

| Type | Convention | Examples |
|------|------------|----------|
| Booleans | is/has/can/should | `isActive`, `hasAccess`, `canEdit`, `shouldRefresh` |
| Collections | plural | `users`, `orders`, `items` |
| Counts | count/num/total | `userCount`, `numItems`, `totalPrice` |

### Files

| Type | Convention | Examples |
|------|------------|----------|
| Components | PascalCase | `UserProfile.tsx`, `OrderList.vue` |
| Utilities | camelCase/kebab | `formatDate.ts`, `string-utils.ts` |
| Constants | SCREAMING_SNAKE | `API_ENDPOINTS.ts`, `ERROR_CODES.ts` |
| Tests | name.test/spec | `user.test.ts`, `order.spec.ts` |

## Code Quality Checklist

Before committing code, verify:

- [ ] Single responsibility - each function does one thing
- [ ] Clear naming - intent is obvious from names
- [ ] Error handling - failures are handled gracefully
- [ ] No magic numbers - constants are named and documented
- [ ] DRY - no unnecessary duplication (but don't over-abstract)
- [ ] Tests - critical paths are tested
- [ ] Documentation - complex logic is explained

## Anti-Patterns to Avoid

### God Objects
Objects that know too much or do too much. Split into focused components.

### Premature Optimization
Don't optimize before measuring. Write clear code first, optimize proven bottlenecks.

### Stringly Typed
Using strings where enums/types would be safer. Use type systems.

### Copy-Paste Programming
Duplicating code instead of abstracting. But: prefer duplication over wrong abstraction.

### Boolean Parameters
Functions with boolean flags that change behavior. Split into explicit functions.

```
// BAD
function process(data, isAdmin) { /* behaves differently based on flag */ }

// GOOD
function processUserData(data) { /* user logic */ }
function processAdminData(data) { /* admin logic */ }
```

## Performance Principles

1. **Measure First**: Profile before optimizing
2. **Lazy Loading**: Load resources only when needed
3. **Caching**: Cache expensive computations and API calls
4. **Pagination**: Don't load everything at once
5. **Batch Operations**: Combine multiple operations when possible
6. **Async/Parallel**: Use concurrency for independent operations

## Security Principles

1. **Input Validation**: Never trust user input
2. **Output Encoding**: Encode data for its context (HTML, SQL, etc.)
3. **Least Privilege**: Request minimum permissions needed
4. **Defense in Depth**: Multiple layers of security
5. **Fail Secure**: Default to denying access on errors
6. **Secrets Management**: Never hardcode secrets, use environment variables

## Language-Specific Knowledge Bases (cross-plugin)

These universal patterns are language-agnostic. When the task targets a specific
language, a companion plugin may ship a **curated, production-grade knowledge base**
for it. Prefer that knowledge over generic patterns when it exists.

### Go — the `go` plugin's knowledge base

If the task involves Go, check whether the `go@magus` plugin is installed alongside
this one and read its knowledge base. It is bundled as plain files next to the `dev`
plugin, so locate it relative to this plugin's root (`${CLAUDE_PLUGIN_ROOT}`), which
covers both install topologies:

```bash
# Both layouts: installed cache (…/cache/magus/go/<version>/) and local source
# (…/plugins/go/). Run from inside an agent that knows ${CLAUDE_PLUGIN_ROOT}:
ls "${CLAUDE_PLUGIN_ROOT}/../go/knowledge/roles" 2>/dev/null \
  || ls "${CLAUDE_PLUGIN_ROOT}"/../../go/*/knowledge/roles 2>/dev/null
```

**If found**, read the files matching your role and task before writing Go:
- `knowledge/roles/<role>/best-practices.md` — role guidance (`developer`,
  `architect`, `tester`, `code-reviewer`)
- `knowledge/roles/<role>/implementation-references.md` — index into the references
- `knowledge/references/*.md` — production-code patterns (error handling, concurrency,
  interface design, context usage, testing, http-api, etc.)
- `knowledge/uber-go-style-guide.md`, `knowledge/100-go-mistakes.md`,
  `knowledge/go-proverbs.md` — style and pitfalls

Apply this Go knowledge in preference to the generic patterns above. The role names
map to dev agents: developer→`dev:developer`, architect→`dev:architect`,
tester→`dev:qa-engineer`, code-reviewer→`dev:reviewer`.

**If NOT found** and the task is Go-heavy, tell the user once, then proceed with the
generic patterns:

> 💡 A curated Go knowledge base (Uber style guide, 100 Go Mistakes, production
> patterns) is available in the `go` plugin. Install it for higher-quality Go work:
> `/plugin install go@magus`

Do not block on this — it is an enhancement, not a requirement.

---

*Universal patterns applicable to all technology stacks*

Wersje

W bazie nie ma innych skilli o nazwie universal-patterns.

Migawka bazy z 13.11.2026 · wersja paczki 39b2e82d9056 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100programming
    Opisuje zasady pisania kodu niezależnie od języka: organizację, nazewnictwo, modelowanie danych, obsługę błędów, bezpieczeństwo i testy.
  • 95pact-coding-standards
    Podpowiada zasady czystego kodu, obsługę błędów, logowanie i nazewnictwo w fazie kodowania PACT oraz przy przeglądzie kodu.
  • 100golang-patterns
    Stosuje wzorce projektowe i dobre praktyki Go: opcje funkcyjne, małe interfejsy, wstrzykiwanie zależności, wzorce współbieżności, obsługę błędów i organizację pakietów.
  • 100anti-patterns
    Wskazuje i refaktoryzuje antywzorce w kodzie Elixir podczas przeglądu kodu i poprawy jakości.
  • 100audit-code-quality
    Wykrywa i naprawia antywzorce w całym repozytorium oraz dryf spójności (nazewnictwo, organizacja, powtarzalne smells).
  • 90cpp-patterns
    Podpowiada nowoczesne wzorce C++: RAII, własność, obsługę błędów i projekt API, dla czytelnego i bezpiecznego kodu.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.