Chuyển đến nội dung
Skillpedia
Lập trình chung48k · #6309

ast-visitor-pattern

Skill này làm gì

Nó hướng dẫn agent của bạn cấu trúc một nhóm kiểu liên quan bằng các lớp bất biến và một visitor, để mọi nơi xử lý chúng đều được kiểm tra. Nó dành cho lập trình viên làm TypeScript với các câu lệnh switch ngày càng dài.

Khi nào nên dùng

  • ✓Khi một nhóm biến thể được xử lý ở hai nơi trở lên, chẳng hạn bộ render hoặc bộ serialize.
  • ✓Khi bạn thêm một biến thể mới vào một kiểu đã được switch ở nhiều nơi.
  • ✓Khi một union type đã lớn lên và các câu lệnh switch khó giữ nhất quán.

Liên kết skill

https://github.com/prisma/orm/blob/main/skills-contrib/ast-visitor-pattern/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/prisma/orm/blob/main/skills-contrib/ast-visitor-pattern/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Bạn có thể tái cấu trúc union type này và các câu lệnh switch của nó để trình biên dịch bắt được mọi trường hợp bị thiếu không?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent biến mỗi biến thể thành một lớp bất biến có phương thức accept, và định nghĩa một interface visitor mà mọi nơi tiêu thụ phải triển khai. Khi thêm biến thể mới, trình biên dịch sẽ báo lỗi ở mọi nơi chưa cập nhật visitor.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

AST Class/Visitor Pattern

When a discriminated union has 3+ variants and 2+ dispatch sites (renderers, serializers, classifiers, etc.), replace plain union + switch with frozen subclasses and a visitor interface. This makes adding a new variant a compiler error at every consumer, instead of a silent omission.

Structure

Four pieces, usually in one file — the Mongo DDL set below spreads them over three:

// 1. Abstract base (not exported — consumers use the union type)
abstract class FooNode {
  abstract readonly kind: string;
  abstract accept<R>(visitor: FooVisitor<R>): R;
  protected freeze(): void { Object.freeze(this); }
}

// 2. Visitor interface
export interface FooVisitor<R> {
  bar(node: BarNode): R;
  baz(node: BazNode): R;
}

// 3. Concrete subclasses — readonly fields, freeze() in constructor
export class BarNode extends FooNode {
  readonly kind = 'bar' as const;
  readonly value: string;
  constructor(value: string) {
    super();
    this.value = value;
    this.freeze();
  }
  accept<R>(visitor: FooVisitor<R>): R { return visitor.bar(this); }
}

export class BazNode extends FooNode {
  readonly kind = 'baz' as const;
  readonly count: number;
  constructor(count: number) {
    super();
    this.count = count;
    this.freeze();
  }
  accept<R>(visitor: FooVisitor<R>): R { return visitor.baz(this); }
}

// 4. Union type
export type Foo = BarNode | BazNode;

Consuming

Define a visitor object (or class) per concern:

const renderVisitor: FooVisitor<string> = {
  bar(node) { return node.value; },
  baz(node) { return String(node.count); },
};

function render(node: Foo): string {
  return node.accept(renderVisitor);
}

Always construct instances, never frozen object literals

This holds everywhere a node is built — tests and production construction surfaces (contract-free factories, builders). A factory must return new BarNode(...), never Object.freeze({ kind: 'bar', value: 'x' }). A frozen plain object has no prototype, so instanceof fails, accept() is missing, and a downstream shallow-copy ({ ...node }) silently strips the type back to an anonymous bag; constructor-time invariants are skipped too.

// ✅
const call = new BarNode('x');
export function bar(value: string): BarNode { return new BarNode(value); }

// ❌
const call: Foo = { kind: 'bar', value: 'x' };
export function bar(value: string): Foo { return Object.freeze({ kind: 'bar', value }); }

When NOT to use

  • Single dispatch site → plain union + switch is simpler
  • Fewer than 3 variants with no expected growth → not worth the boilerplate

Codebase examples

  • MongoAstNode base — packages/2-mongo-family/4-query/query-ast/src/ast-node.ts
  • MongoDdlCommandVisitor interface — packages/2-mongo-family/4-query/query-ast/src/ddl-visitors.ts
  • Concrete DDL commands and their union — packages/2-mongo-family/4-query/query-ast/src/ddl-commands.ts
Câu hỏi thường gặp

Khi nào mẫu này đáng dùng?

Skill gợi ý dùng khi một union có ba biến thể trở lên và có hai nơi trở lên switch trên nó.

Ví dụ được viết bằng ngôn ngữ nào?

Ví dụ viết bằng TypeScript, nên mẫu này được viết cho mã TypeScript.

Trình biên dịch kiểm tra điều gì?

Khi thêm biến thể mới, mọi nơi tiêu thụ chưa xử lý nó sẽ báo lỗi, thay vì bị bỏ sót âm thầm.

Chi tiết

Mô tả gốc của tác giả

Use the frozen-class/visitor pattern for discriminated unions that have multiple dispatch sites. Use when creating a new set of variants (commands, IR nodes, factory calls) that will be switched over in 2+ places, or when refactoring an existing union type that has grown multiple switch sites.

repo: prisma/orm

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#6309
Giấy phép
Apache-2.0
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự