Token导航 LogoToken导航

Agent Skill · 研究检索

clean-code-principles(干净代码原则)

clean-code-principles 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

clean-code-principles 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 69,971。

总安装 214周安装 9GitHub Stars 公开资料未说明下载 75核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:clean-code-principles(干净代码原则)
来源仓库:https://github.com/grahamcrackers/skills
仓库路径:skills/clean-code-principles
安装命令:
npx skills add https://github.com/grahamcrackers/skills --skill clean-code-principles
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/grahamcrackers/skills --skill clean-code-principles

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

clean-code-principles 用于查找、检索和筛选相关信息,支持代码规范相关研究。适用于需要根据关键词或任务场景快速定位候选结果的检索场景。通过 npx skills add 从 GitHub 仓库安装并使用。安装前应确认权限范围、维护状态及是否涉及联网或文件操作。

建议参考原始 README 了解具体实现和使用限制。

来源仓库内路径:skills/clean-code-principles

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/grahamcrackers/skills --skill clean-code-princ…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

clean-code-principles 怎么安装?

在终端执行 npx skills add https://github.com/grahamcrackers/skills --skill clean-code-principles。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

clean-code-principles 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

clean-code-principles 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

clean-code-principles 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

clean-code-principles 用的人多吗?

公开数据是累计安装 214 次,近一周安装 9 次,下载 75 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

clean-code-principles 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
clean-code-principles

干净代码原则 · 本页

214—需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Clean Code Principles

Practical guidelines for writing readable, maintainable code in TypeScript and React.

Naming

Be Descriptive and Specific

Names should reveal intent. A reader should understand what a variable holds or what a function does without reading its implementation.

// Vague
const d = new Date();
const list = getItems();
function process(data: unknown) {}

// Clear
const registrationDate = new Date();
const activeUsers = getActiveUsers();
function validatePaymentInput(input: PaymentInput) {}

Use Consistent Vocabulary

Pick one word per concept and stick with it across the codebase.

// Inconsistent — uses fetch, get, retrieve interchangeably
fetchUsers();
getProducts();
retrieveOrders();

// Consistent
getUsers();
getProducts();
getOrders();

Booleans Should Read as Yes/No Questions

const isLoading = true;
const hasPermission = user.role === "admin";
const canEdit = hasPermission && !isArchived;
const shouldAutoSave = settings.autoSave && isDirty;

Event Handlers

Prefix handlers with handle, prefix callback props with on:

function SearchForm({ onSubmit }: { onSubmit: (query: string) => void }) {
    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();
        onSubmit(query);
    };
    return <form onSubmit={handleSubmit}>...</form>;
}

Avoid Encodings and Abbreviations

// Avoid
const usrLst: IUser[] = [];
const btnRef = useRef<HTMLButtonElement>(null);
const tmpVal = calculate();

// Prefer
const users: User[] = [];
const buttonRef = useRef<HTMLButtonElement>(null);
const discountedPrice = calculate();

Exception: widely understood abbreviations like e for events, i for loop indices, ref for React refs, and ctx for context are fine.

Functions

Keep Functions Small and Focused

Each function should do one thing. If you can describe what it does with "and," it's doing too much.

// Too much — fetches, transforms, and saves
async function syncUserData(userId: string) {
    const response = await api.get(`/users/${userId}`);
    const user = {
        ...response.data,
        fullName: `${response.data.firstName} ${response.data.lastName}`,
        isActive: response.data.status === "active",
    };
    await db.users.upsert(user);
    await cache.invalidate(`user:${userId}`);
}

// Split by responsibility
async function fetchUser(userId: string): Promise<ApiUser> {
    const response = await api.get(`/users/${userId}`);
    return response.data;
}

function toUser(data: ApiUser): User {
    return {
        ...data,
        fullName: `${data.firstName} ${data.lastName}`,
        isActive: data.status === "active",
    };
}

async function syncUser(userId: string) {
    const data = await fetchUser(userId);
    const user = toUser(data);
    await db.users.upsert(user);
    await cache.invalidate(`user:${userId}`);
}

Limit Parameters

More than 3 parameters signals the function is doing too much or needs an options object.

// Too many positional args
function createUser(name: string, email: string, role: string, teamId: string, notify: boolean) {}

// Use an object
function createUser(input: CreateUserInput) {}

Avoid Flag Arguments

A boolean parameter usually means the function does two things. Split it.

// Flag decides behavior
function renderList(items: Item[], isCompact: boolean) {}

// Two functions with clear intent
function renderList(items: Item[]) {}
function renderCompactList(items: Item[]) {}

Prefer Pure Functions

Functions without side effects are easier to test, reason about, and reuse.

// Impure — mutates external state
let total = 0;
function addToTotal(amount: number) {
    total += amount;
}

// Pure — returns a new value
function add(a: number, b: number): number {
    return a + b;
}

Return Early

Reduce nesting by handling edge cases first.

// Deeply nested
function getDiscount(user: User) {
    if (user) {
        if (user.subscription) {
            if (user.subscription.isActive) {
                return user.subscription.discount;
            }
        }
    }
    return 0;
}

// Early returns
function getDiscount(user: User) {
    if (!user?.subscription?.isActive) return 0;
    return user.subscription.discount;
}

Abstraction

Don't Repeat Yourself (Wisely)

Duplication is cheaper than the wrong abstraction. Wait until you see the same pattern 3 times before abstracting. When you do abstract, make sure the shared code represents a genuine concept, not just coincidental similarity.

// Two functions that look similar but serve different purposes — don't merge
function formatUserDisplayName(user: User) {
    return `${user.firstName} ${user.lastName}`;
}

function formatAuthorByline(author: Author) {
    return `${author.firstName} ${author.lastName}`;
}

// When they genuinely share a concept — abstract
function formatFullName(person: { firstName: string; lastName: string }) {
    return `${person.firstName} ${person.lastName}`;
}

Prefer Composition Over Inheritance

Build behavior by combining small, focused pieces.

// Instead of a monolithic component with many props
<Card variant="user" showAvatar showBadge showActions />

// Compose smaller components
<Card>
    <Card.Header>
        <Avatar src={user.avatar} />
        <Badge status={user.status} />
    </Card.Header>
    <Card.Body>{user.bio}</Card.Body>
    <Card.Actions>
        <EditButton />
    </Card.Actions>
</Card>

Keep Abstractions at One Level

Each function should operate at a single level of abstraction. Don't mix high-level orchestration with low-level details.

// Mixed levels
async function onboardUser(input: OnboardInput) {
    const hashedPassword = await bcrypt.hash(input.password, 12);
    const user = await db.users.create({ ...input, password: hashedPassword });
    const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: "7d" });
    await sendgrid.send({
        to: user.email,
        subject: "Welcome!",
        html: `<h1>Hello ${user.name}</h1>`,
    });
    return { user, token };
}

// Single level
async function onboardUser(input: OnboardInput) {
    const user = await createUser(input);
    const token = generateAuthToken(user);
    await sendWelcomeEmail(user);
    return { user, token };
}

Error Handling

Throw Meaningful Errors

// Unhelpful
throw new Error("Invalid input");

// Helpful
throw new Error(`User with email "${email}" already exists. Use a different email or log in.`);

Use Typed Error Classes

class NotFoundError extends Error {
    constructor(resource: string, id: string) {
        super(`${resource} with id "${id}" not found`);
        this.name = "NotFoundError";
    }
}

class ValidationError extends Error {
    constructor(
        public readonly field: string,
        message: string,
    ) {
        super(message);
        this.name = "ValidationError";
    }
}

Don't Swallow Errors

// Silent failure — hides bugs
try {
    await saveData(data);
} catch {
    // do nothing
}

// Handle or propagate
try {
    await saveData(data);
} catch (error) {
    logger.error("Failed to save data", { error, data });
    throw error;
}

Use Result Types for Expected Failures

For operations that can fail as part of normal flow, return results instead of throwing:

type Result<T, E = Error> = { success: true; data: T } | { success: false; error: E };

function parseConfig(raw: string): Result<Config> {
    try {
        const parsed = JSON.parse(raw);
        return { success: true, data: configSchema.parse(parsed) };
    } catch (error) {
        return { success: false, error: new Error("Invalid config format") };
    }
}

Comments

Code Should Be Self-Documenting

If you need a comment to explain what code does, the code should be rewritten to be clearer.

// Bad — comment restates the code
// Check if user is active
if (user.status === "active") {
}

// Good — no comment needed
const isActive = user.status === "active";
if (isActive) {
}

Comment Why, Not What

Comments should explain intent, trade-offs, or constraints that the code cannot convey.

// Debounce to 300ms because the search API rate-limits at 10 req/s
const debouncedSearch = useDebouncedCallback(search, 300);

// Must match the order defined in the payment provider's webhook spec
const WEBHOOK_EVENTS = ["payment.created", "payment.updated", "payment.failed"] as const;

Delete Commented-Out Code

Version control exists. Don't leave dead code behind.

Code Smells

Large Files

If a file exceeds ~300 lines, look for opportunities to extract. Components, hooks, utilities, and types can often be split.

Deep Nesting

More than 2–3 levels of nesting hurts readability. Flatten with early returns, extracted functions, or guard clauses.

Long Parameter Lists

More than 3 parameters signals the need for an options object or decomposition.

Feature Envy

A function that accesses another object's data more than its own should probably live on (or closer to) that object.

Magic Numbers and Strings

Extract to named constants:

// Magic
if (password.length < 8) {
}
if (retries > 3) {
}

// Named
const MIN_PASSWORD_LENGTH = 8;
const MAX_RETRIES = 3;

if (password.length < MIN_PASSWORD_LENGTH) {
}
if (retries > MAX_RETRIES) {
}

Primitive Obsession

Use types and branded types instead of raw primitives for domain concepts:

// Primitives everywhere — easy to mix up
function createOrder(userId: string, productId: string, quantity: number) {}

// Domain types
type UserId = string & { readonly __brand: "UserId" };
type ProductId = string & { readonly __brand: "ProductId" };

function createOrder(userId: UserId, productId: ProductId, quantity: number) {}

React-Specific Clean Code

Components Should Do One Thing

If a component handles data fetching, business logic, and rendering, split it:

// Data layer
function UserProfile({ userId }: { userId: string }) {
    const { data: user } = useUser(userId);
    if (!user) return <UserProfileSkeleton />;
    return <UserProfileView user={user} />;
}

// Presentation layer
function UserProfileView({ user }: { user: User }) {
    return (
        <div>
            <Avatar src={user.avatar} />
            <h2>{user.name}</h2>
        </div>
    );
}

Custom Hooks for Reusable Logic

Extract shared logic into hooks — not shared state, shared logic:

function useToggle(initial = false) {
    const [value, setValue] = useState(initial);
    const toggle = useCallback(() => setValue((v) => !v), []);
    const setTrue = useCallback(() => setValue(true), []);
    const setFalse = useCallback(() => setValue(false), []);
    return { value, toggle, setTrue, setFalse } as const;
}

Avoid Prop Drilling

If props pass through 3+ levels, use composition (children/slots), Context, or a state library.

Colocate Related Code

Keep components, hooks, types, and tests close to where they're used. Don't scatter related code across the file tree.

Design Patterns

CategoryDescriptionReference
GoF Patterns (TypeScript)Classic 22 design patterns with TypeScript examplesRefactoring Guru
React PatternsCompound components, render props, hooks, providers, slots, and morereact-patterns

GoF Patterns (TypeScript)

Classic design patterns with TypeScript implementations. Full catalog and examples at Refactoring Guru — Design Patterns in TypeScript.

Creational Patterns

PatternPurposeReference
Factory MethodCreate objects without specifying exact classpattern-factory-method
Abstract FactoryProduce families of related objectspattern-abstract-factory
BuilderConstruct complex objects step by steppattern-builder
SingletonEnsure a class has only one instancepattern-singleton
PrototypeCopy existing objects without class dependencypattern-prototype

Structural Patterns

PatternPurposeReference
AdapterMake incompatible interfaces work togetherpattern-adapter
DecoratorAttach new behaviors via wrapper objectspattern-decorator
FacadeSimplified interface to a complex subsystempattern-facade
ProxyPlaceholder that controls access to another objectpattern-proxy
CompositeCompose objects into tree structurespattern-composite
BridgeSplit abstraction from implementationpattern-bridge
FlyweightShare state between many similar objectspattern-flyweight

Behavioral Patterns

PatternPurposeReference
StrategySwap algorithms at runtimepattern-strategy
ObserverNotify subscribers of state changespattern-observer
CommandTurn requests into stand-alone objectspattern-command
StateAlter behavior when internal state changespattern-state
Chain of ResponsibilityPass requests along a handler chainpattern-chain-of-responsibility
MediatorReduce direct dependencies between objectspattern-mediator
IteratorTraverse a collection without exposing internalspattern-iterator
Template MethodDefine algorithm skeleton, let subclasses override stepspattern-template-method
VisitorSeparate algorithms from the objects they operate onpattern-visitor
MementoSave and restore object statepattern-memento

Most Useful GoF Patterns in Frontend/React

  • Strategy — swappable validation, sorting, or formatting logic
  • Observer — event emitters, pub/sub, store subscriptions
  • Adapter — wrapping 3rd party APIs to your interface
  • Facade — simplified API client or service layer
  • Builder — constructing complex query objects, form schemas, or configs
  • Decorator — higher-order components, middleware, extending behavior
  • State — XState machines, status-driven UI
  • Command — undo/redo, action queues, optimistic updates
  • Composite — recursive tree rendering (menus, file explorers, org charts)

React-Specific Patterns

Patterns born from React's component model that don't exist in the GoF catalog. See react-patterns for full examples.

PatternPurpose
Compound ComponentsMultiple components sharing implicit state (<Tabs>, <Tabs.Panel>)
Render PropsPass a function as prop to delegate rendering
Custom HookExtract reusable stateful logic into use* functions
ProviderContext-based dependency injection across the tree
Container / PresentationalSeparate data fetching from pure UI rendering
Controlled / UncontrolledWho owns the state — parent or component?
Polymorphic Componentsas / asChild prop for flexible element rendering
Slot PatternPass components as named props for layout composition
State ReducerLet consumers customize internal state transitions
Forwarded RefsExpose imperative API to parent via useImperativeHandle
Higher-Order ComponentsWrap a component with cross-cutting behavior
Error BoundaryDeclarative error catching in the component tree
Optimistic UpdatesUpdate UI before server confirms, rollback on failure
PortalRender outside the DOM hierarchy (modals, tooltips)

Key Principles

  1. Readability over cleverness — code is read far more than it is written.
  2. Delete code you don't need — less code means fewer bugs and easier maintenance.
  3. Make the right thing easy and the wrong thing hard — design APIs that guide correct usage.
  4. Leave the code better than you found it — the Boy Scout Rule applies to every change.
  5. Optimize for change — code will be modified. Structure it to make future changes safe and easy.

References

平台分布

Codex

35.93%
按下载量换算27

Claude

30.24%
按下载量换算23

Cursor

18.23%
按下载量换算14

Gemini CLI

8.75%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills