Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

pact-coding-standards

БесплатноЗапускает вложенные скриптыНе проверен

Clean code principles, error handling patterns, and coding standards for PACT Code phase. Use when: implementing features, refactoring code, reviewing code…

Synaptic-Labs-AIот Synaptic-Labs-AI★ 73 звезды на GitHub18 установок в других каталогах

Об этом скилле

PACT Coding Standards

Clean code principles for the Code phase of PACT. This skill provides essential coding guidelines and links to detailed patterns for implementation.

Core Principles

1. Single Responsibility Principle

Each function, class, or module should have exactly one reason to change.

// BAD: Multiple responsibilities
class UserManager {
  createUser(data) { }
  validateEmail(email) { }
  sendWelcomeEmail(user) { }
  generateReport() { }
  updateUserPreferences(userId, prefs) { }
}

// GOOD: Single responsibility each
class UserService {
  createUser(data) { }
  updateUser(userId, data) { }
}

class EmailValidator {
  validate(email) { }
}

class NotificationService {
  sendWelcomeEmail(user) { }
}

class UserReportGenerator {
  generate(criteria) { }
}

2. DRY (Don't Repeat Yourself)

Extract duplicated logic into reusable functions.

// BAD: Duplicated validation logic
function createUser(data) {
  if (!data.email || !data.email.includes('@')) {
    throw new Error('Invalid email');
  }
  // ...
}

function updateUser(id, data) {
  if (data.email && !data.email.includes('@')) {
    throw new Error('Invalid email');
  }
  // ...
}

// GOOD: Extracted validation
function validateEmail(email) {
  if (!email || !email.includes('@')) {
    throw new ValidationError('Invalid email format');
  }
}

function createUser(data) {
  validateEmail(data.email);
  // ...
}

function updateUser(id, data) {
  if (data.email) {
    validateEmail(data.email);
  }
  // ...
}

3. KISS (Keep It Simple, Stupid)

Choose the simplest solution that works.

// BAD: Over-engineered
class ConfigurationFactoryBuilderManager {
  static getInstance() {
    return new ConfigurationFactoryBuilder()
      .withDefaults()
      .withEnvironment()
      .build()
      .getConfiguration();
  }
}

// GOOD: Simple and direct
const config = {
  port: process.env.PORT || 3000,
  dbUrl: process.env.DATABASE_URL,
  debug: process.env.NODE_ENV !== 'production'
};

4. Defensive Programming

Validate inputs, handle edge cases, and fail gracefully.

function processOrder(order) {
  // Guard clauses
  if (!order) {
    throw new ValidationError('Order is required');
  }

  if (!order.items || order.items.length === 0) {
    throw new ValidationError('Order must have at least one item');
  }

  if (order.total < 0) {
    throw new ValidationError('Order total cannot be negative');
  }

  // Safe property access
  const customerEmail = order.customer?.email ?? '[email protected]';

  // Proceed with valid data
  return {
    id: generateOrderId(),
    items: order.items.map(item => ({
      ...item,
      price: Math.max(0, item.price)  // Ensure non-negative
    })),
    total: order.total,
    customerEmail
  };
}

Naming Conventions

Functions

// Use verb + noun pattern
function getUser(id) { }           // Retrieval
function createOrder(data) { }     // Creation
function updateProfile(id, data) { } // Mutation
function deleteComment(id) { }     // Deletion
function validateEmail(email) { }  // Validation
function calculateTotal(items) { } // Calculation
function formatDate(date) { }      // Transformation
function isActive(user) { }        // Boolean check
function hasPermission(user, action) { } // Boolean check
function canEdit(user, resource) { }     // Boolean check

Variables

// Descriptive nouns
const userCount = 42;               // Not: n, count, uc
const activeUsers = users.filter(); // Not: arr, filtered
const maxRetryAttempts = 3;         // Not: max, retries

// Boolean variables
const isActive = true;              // is/has/can/should prefix
const hasPermission = false;
const canEdit = user.role === 'admin';
const shouldRetry = attempts < maxRetryAttempts;

// Collections are plural
const users = [];                   // Not: userList, userArray
const orderItems = [];              // Not: items (too generic)

// Maps/objects describe content
const userById = {};                // Not: userMap
const priceByProductId = {};        // Describes key-value relationship

Constants

// SCREAMING_SNAKE_CASE for true constants
const MAX_RETRY_ATTEMPTS = 3;
const DEFAULT_PAGE_SIZE = 20;
const API_BASE_URL = 'https://api.example.com';

// Configuration objects
const CONFIG = Object.freeze({
  database: {
    host: process.env.DB_HOST,
    port: parseInt(process.env.DB_PORT, 10)
  }
});

Classes

// PascalCase, noun-based
class UserRepository { }     // Not: UsersRepo, UserRepo
class OrderService { }       // Not: OrdersService
class EmailValidator { }     // Not: ValidateEmail
class PaymentGateway { }     // Not: PaymentGatewayService

// Interface names (TypeScript)
interface Cacheable { }      // Adjective for capabilities
interface UserRepository { } // Noun for contracts

Error Handling

Fail Fast, Recover Gracefully


Полный SKILL.md на GitHub

Установить pact-coding-standards в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/clean-code-principles.mdreferences/error-handling-patterns.mdscripts/check_unused_imports.pyscripts/lint-check.sh

FAQ

Что делает скилл pact-coding-standards?

Clean code principles, error handling patterns, and coding standards for PACT Code phase. Use when: implementing features, refactoring code, reviewing code quality, establishing coding conventions, or handling errors and exceptions. Triggers on: code quality, clean code, refactoring, error handling, logging patterns, naming conventions, code review, code phase.

Как установить скилл pact-coding-standards?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл pact-coding-standards запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить pact-coding-standards с