Логотип Nw Fp Domain Modeling

Nw Fp Domain Modeling

Організація
nWave-ai
nw-fp-domain-modeling

Domain modeling with algebraic data types, smart constructors, and type-level error handling

Огляд

ВидавецьnWave-ai
РепозиторійnWave
Назва навичкиnw-fp-domain-modeling
Зірки
616
Форки
65
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: nWave-ai. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Nw Fp Domain Modeling у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/nWave-ai/nWave/tree/main/nWave/skills/nw-fp-domain-modeling
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/nWave-ai/nWave.git /tmp/nWave
mkdir -p .claude/skills
cp -r /tmp/nWave/nWave/skills/nw-fp-domain-modeling .claude/skills/nw-fp-domain-modeling
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Nw Fp Domain Modeling в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Nw Fp Domain Modeling, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Nw Fp Domain Modeling не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

FP Domain Modeling

Domain modeling with types. Make illegal states unrepresentable, workflows as pipelines, error handling at the type level.

Cross-references: fp-principles | fp-hexagonal-architecture | fp-algebra-driven-design


1. The Two Building Blocks

[STARTER]

All domain types compose from two operations:

  • AND (Record Types): Value has ALL of these fields. Order requires CustomerInfo AND ShippingAddress AND OrderLines.
  • OR (Choice Types): Value is ONE OF these alternatives. ProductCode is either WidgetCode OR GizmoCode.

Combined recursively, these express virtually any domain structure.


2. Domain Wrappers for Primitives

[STARTER]

Never use primitives directly in the domain model. Each domain concept gets its own wrapper type.

What: Wrap primitives so the compiler distinguishes CustomerId from OrderId. When: Every primitive with domain meaning. Why: Prevents accidental mixing (compiler rejects comparing CustomerId with OrderId). Each wrapper carries its own validation rules. The type name IS the documentation.


3. Validated Construction (Smart Constructors)

[STARTER]

Raw constructor is private. A create function validates input and returns a Result type, making validation failure explicit.

Pattern: UnitQuantity must be between 1 and 1000. Its create function rejects values outside that range. A companion value function provides read access to the inner primitive.

When: Every domain wrapper with validation rules. Why: Once constructed, a value is guaranteed valid. No defensive checks deeper in the code.


4. Making Illegal States Unrepresentable

[STARTER]

The central design guideline. Instead of flags and runtime checks, model the domain so invalid states cannot be constructed.

Replace Flags with Distinct Types

Instead of { EmailAddress; IsVerified: bool }, create separate VerifiedEmailAddress and UnverifiedEmailAddress types. Functions requiring verification take VerifiedEmailAddress, making misuse a compile error.

Replace Optional Fields with Choice Types

Instead of { Email: option; Address: option } (where both could be None), create: EmailOnly | AddressOnly | EmailAndAddress. The "at least one required" rule becomes structurally enforced.

NonEmptyList for "At Least One" Rules

Define a type guaranteeing at least one element. Order with OrderLines: NonEmptyList<OrderLine> cannot have zero lines.


5. Workflows as Functions

[STARTER]

Every business workflow is a single function: Command in, Events out.

PlaceOrderWorkflow : PlaceOrderCommand -> AsyncResult<PlaceOrderEvent list>

Pipeline Composition

Workflows decompose into steps, each transforming one document type into the next:

UnvalidatedOrder -> ValidatedOrder -> PricedOrder -> Events

Each step is stateless, pure, has single input/output type, and is independently testable. The workflow assembles by piping steps together.

Why: Pipeline makes the business process visible. Each step name is a domain concept.


6. Document Lifecycle as State Types

[INTERMEDIATE]

Rather than one Order type with flags, create separate types for each lifecycle stage:

  • UnvalidatedOrder (raw input, all fields strings)
  • ValidatedOrder (all fields checked)
  • PricedOrder (prices calculated)

A top-level Order choice type unifies all states. New states (e.g., Refunded) added without breaking existing code.

When: Domain entities with distinct lifecycle stages where different data is available at each stage.


7. State Machines with Types

[INTERMEDIATE]

When an entity has distinct states with different data and different allowed operations, model each state as a separate type.

ShoppingCart = EmptyCart | ActiveCart of ActiveCartData | PaidCart of PaidCartData

Transition functions take the choice type, pattern-match on current state, return new state.

Benefits: All states explicit | each state has own data | invalid transitions prevented by types | pattern matching warnings reveal unhandled edge cases.


8. Error-Track Pipelines (Railway Pattern)

[INTERMEDIATE]

Each function returns a Result type. Pipeline short-circuits on first failure.

rawInput
  |> validateOrder           -- Result<ValidOrder, Error>
  |> bind calculateTotal     -- Result<PricedOrder, Error>
  |> bind checkInventory     -- Result<ConfirmedOrder, Error>
  |> bind chargePayment      -- Result<PaidOrder, Error>
  |> map generateReceipt     -- Result<Receipt, Error>

Key combinators:

  • map: Transform success value (one-track into two-track)
  • bind: Chain a function that itself returns Result
  • mapError: Transform error value
  • tee: Perform side effect without changing value (logging)

Error Classification

CategoryExamplesStrategy
Domain ErrorsValidation failure, out of stockModel as types, return via Result
PanicsOut of memory, null referenceThrow exceptions, catch at top level
Infrastructure ErrorsNetwork timeout, auth failureCase-by-case

Unifying Error Types

Each step may have its own error type. Define a common error choice type and use mapError to lift step errors before composing.

Collecting All Errors (Applicative Validation)

[ADVANCED]

Standard bind short-circuits on first error. For validation where you want ALL errors, use Applicative style -- runs all validations and accumulates errors into a list. See fp-principles section 5.

When: Form validation | batch input checking | any place user needs all errors at once.


9. Modeling Dependencies

[INTERMEDIATE]

Each workflow step declares exactly the functions it needs as parameters:

CheckProductCodeExists : ProductCode -> bool
GetProductPrice        : ProductCode -> Price

Convention: Dependencies first in parameter list, primary input last. Enables partial application (functional DI).

Public vs. internal: Top-level workflow hides dependencies from callers. Internal steps make them explicit.

See fp-hexagonal-architecture section 5 for full DI decision tree.


10. Persistence Ignorance

[INTERMEDIATE]

Domain model has no awareness of databases. Two distinct type hierarchies:

  • Domain types: Rich, nested, use choice types, validated wrappers. Not serialization-friendly.
  • DTO types: Flat, primitives, nullable, arrays. Designed for serialization.

Conversion Pattern

  • fromDomain: Domain -> DTO. Always succeeds.
  • toDomain: DTO -> Result<Domain, Error>. May fail (validation happens here).

Serialization as Pipeline Steps

JSON -> deserialize -> DTO -> toDomain -> [WORKFLOW] -> fromDomain -> DTO -> serialize -> JSON

Domain workflow never sees JSON or DTOs directly.


11. Bounded Contexts

[ADVANCED]

Each context has its own dialect of domain language. Contexts communicate only through events and DTOs. Design for autonomy.

Trust boundaries: Input gate validates and converts incoming DTOs to domain types. Output gate converts domain types to DTOs, deliberately dropping private information.

Inter-context relationships: Shared Kernel (shared design) | Customer/Supplier (downstream defines contract) | Anti-Corruption Layer (translator preventing external model from corrupting internal domain).


Decision Tree: How to Model This Domain Concept?

Is it a simple value with validation rules?
  YES --> Domain Wrapper + Smart Constructor
  NO -->
    Does it represent one of several alternatives?
      YES --> Choice Type (sum type)
      NO -->
        Does it group several values together?
          YES --> Record Type (product type)
          NO -->
            Does it have distinct lifecycle stages?
              YES --> State Machine with Types (section 7)
              NO -->
                Is it an operation that transforms data through stages?
                  YES --> Workflow Pipeline (section 5)
                  NO --> Evaluate whether it needs modeling at all

12. Key Design Heuristics

  1. Start from events and workflows, not data structures
  2. Let the domain expert drive naming -- their vocabulary, not technical jargon
  3. Use types to enforce business rules at compile time -- every rule in the type system needs no unit test
  4. Document effects in signatures -- Result for errors | Async for I/O | Option for missing data
  5. Separate domain types from serialization types -- domain is pure; serialization is infrastructure
  6. Prefer explicit over implicit -- every input and dependency is a function parameter

Naming Patterns

  • Types as nouns: Order | ProductCode | CustomerInfo
  • Workflows as verbs: ValidateOrder | PriceOrder | PlaceOrder
  • Events in past tense: OrderPlaced | OrderShipped
  • Commands in imperative: PlaceOrder | ShipOrder | CancelOrder
  • Lifecycle prefixes: UnvalidatedOrder | ValidatedOrder | PricedOrder

Поширені запитання

Що робить навичка ШІ Nw Fp Domain Modeling?

Domain modeling with algebraic data types, smart constructors, and type-level error handling

Навіщо використовувати Nw Fp Domain Modeling у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Nw Fp Domain Modeling — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Nw Fp Domain Modeling у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/nWave-ai/nWave/tree/main/nWave/skills/nw-fp-domain-modeling. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Nw Fp Domain Modeling?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Nw Fp Domain Modeling?

Зі скількома забажаєте. У TypingMind ви можете використовувати Nw Fp Domain Modeling із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Nw Fp Domain Modeling?

Так. На GitHub цю навичку публікує nWave-ai за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇