The post has been translated automatically. Original language: Russian
This is the second post in a series about Spec-Driven Development. First, we've figured out what SDD is and why it's needed. In the third section, we will discuss the pros, cons and when the approach should not be applied.
In the first part, we found out that SDD makes the specification the main document of the project. Now let's see how it looks in practice.
Four stages of the process
Different tools name the stages differently, but the logic is similar everywhere.:
- Specify (Specification). We describe the behavior of the system, user scenarios, limitations, and acceptance criteria. No technical details, just what and why.
- The Plan. We select the stack, architecture, integration, and data format, that is, we determine how to implement it.
- Tasks (Tasks). We break down the plan into small verifiable tasks, each of which can be implemented and tested separately.
- Implementation. The developer or AI agent performs tasks one at a time, checking the specification.
Between the stages, the person checks the result and makes edits. The value of the approach lies precisely in these control points: it is cheaper to catch an error in the requirements at the second stage than at the fourth.
What the specification looks like: example
Let's take a small function, password reset by email. The training fragment of the specification may look like this:
Function: reset password by email
Goal: the user can restore access to the account without contacting support.
Scenarios:
- The user enters an email and receives an email with a reset link.
- The user follows the link and sets a new password.
- If the email is not found, the system does not inform the user about it, so as not to disclose the list of registered addresses.
Limitations:
- The link is valid for a limited time and can only be used once.
- The new password must comply with the project's password complexity policy.
Acceptance criteria:
- A used or expired link shows a clear error message.
- After changing the password, all active user sessions are terminated.
Please note: there is not a word about the database, programming language or framework. This is the work of the Plan stage.
How to write a good specification
- Describe the behavior, not the implementation. ""The link is valid once" is better than "storing the token in table X".
- Make the criteria testable. If a criterion cannot be verified by a test or manual verification, it is too vague.
- Explicitly write the limitations and exceptions. It is at the boundary cases that both humans and AI break down most often.
- Record what is not included in the task. This protects the volume from spreading.
- Keep the specification small. One function, one document. This makes it easier to review and update it.
Where to start
- Choose a small but real function.
- Describe it in the markdown file according to the sample above.
- Ask the AI assistant to draw up a technical plan based on the specification and check it carefully.
- Break the plan into tasks and implement them one at a time, checking with tests.
- Keep the specification in the repository next to the code and update it whenever requirements change.
There are ready-made tools, such as the GitHub Spec Kit and Kiro from AWS, but you can also start using regular markdown files.
Result
SDD in the work boils down to a simple cycle: describe, plan, break down, implement, and check between the steps. In the final post, we'll look at what the approach does, what we risk, and in which cases it's redundant.
Try to use this example to describe any small function from your project. Was it possible to fit into one page?
Это второй пост серии о Spec-Driven Development. В первом :мы разобрали, что такое SDD и зачем он нужен. В третьем обсудим плюсы, минусы и когда подход не стоит применять.
В первой части мы выяснили, что SDD делает главным документом проекта спецификацию. Теперь посмотрим, как это выглядит на практике.
Четыре этапа процесса
Разные инструменты называют этапы по-разному, но логика везде похожая:
- Specify (Спецификация). Описываем поведение системы, пользовательские сценарии, ограничения и критерии приёмки. Никаких технических деталей, только что и зачем.
- Plan (План). Выбираем стек, архитектуру, интеграции и формат данных, то есть определяем как реализовать.
- Tasks (Задачи). Разбиваем план на небольшие проверяемые задачи, каждую из которых можно реализовать и протестировать отдельно.
- Implement (Реализация). Разработчик или AI-агент выполняет задачи по очереди, сверяясь со спецификацией.
Между этапами человек проверяет результат и вносит правки. Ценность подхода как раз в этих точках контроля: ошибку в требованиях дешевле поймать на втором этапе, чем на четвёртом.
Как выглядит спецификация: пример
Возьмём небольшую функцию, сброс пароля по email. Учебный фрагмент спецификации может выглядеть так:
Функция: сброс пароля по email
Цель: пользователь может восстановить доступ к аккаунту без обращения в поддержку.
Сценарии:
- Пользователь вводит email и получает письмо со ссылкой для сброса.
- Пользователь переходит по ссылке и задаёт новый пароль.
- Если email не найден, система не сообщает об этом пользователю, чтобы не раскрывать список зарегистрированных адресов.
Ограничения:
- Ссылка действует ограниченное время и может быть использована только один раз.
- Новый пароль должен соответствовать политике сложности паролей проекта.
Критерии приёмки:
- Использованная или просроченная ссылка показывает понятное сообщение об ошибке.
- После смены пароля все активные сессии пользователя завершаются.
Обратите внимание: здесь нет ни слова о базе данных, языке программирования или фреймворке. Это работа этапа Plan.
Как написать хорошую спецификацию
- Описывайте поведение, а не реализацию. «Ссылка действует один раз» лучше, чем «храним токен в таблице X».
- Делайте критерии проверяемыми. Если критерий нельзя проверить тестом или ручной проверкой, он слишком расплывчатый.
- Явно пишите ограничения и исключения. Именно на граничных случаях чаще всего ломаются и люди, и AI.
- Фиксируйте, что не входит в задачу. Это защищает от расползания объёма.
- Держите спецификацию небольшой. Одна функция, один документ. Так его проще ревьюить и обновлять.
С чего начать
- Выберите небольшую, но реальную функцию.
- Опишите её в markdown-файле по образцу выше.
- Попросите AI-ассистента составить технический план на основе спецификации и внимательно его проверьте.
- Разбейте план на задачи и реализуйте их по одной, проверяя тестами.
- Храните спецификацию в репозитории рядом с кодом и обновляйте её при каждом изменении требований.
Существуют готовые инструменты, например GitHub Spec Kit и Kiro от AWS, но начать можно и на обычных markdown-файлах.
Итог
SDD в работе сводится к простому циклу: описать, спланировать, разбить, реализовать, а между шагами проверять. В заключительном посте разберём, что подход даёт, чем рискуем и в каких случаях он избыточен.
Попробуйте описать по этому образцу любую маленькую функцию из своего проекта. Получилось ли уложиться в одну страницу?