惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
J
Java Code Geeks
博客园_首页
Scott Helme
Scott Helme
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
Security Latest
Security Latest
V
Visual Studio Blog
Cloudbric
Cloudbric
Jina AI
Jina AI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
S
SegmentFault 最新的问题
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
W
WeLiveSecurity
K
Kaspersky official blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hacker News: Ask HN
Hacker News: Ask HN
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
量子位
Google Online Security Blog
Google Online Security Blog
博客园 - Franky
Simon Willison's Weblog
Simon Willison's Weblog
博客园 - 三生石上(FineUI控件)
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
From Gherkin to Source Code Without Losing the Business Language
Douglas Card · 2026-04-28 · via DEV Community

Picture this: you are a software developer building an education platform and you receive from the product owner some requirements written in Business Language (Gherkin). You need to implement these scenarios in Python.

Probably you will start creating models and service modules. You will create some classes to represent the entities described in the scenarios like Student, Course, and Subject. You will add conditionals and loops in the entity classes to control the business logic and restrict paths in the code:

# Enroll a student in a course
if course.status == "active" and student.course == None:
    student.course = course
raise BusinessError("Student already in a course")

Enter fullscreen mode Exit fullscreen mode

Also, you will create a class to represent the persistence layer (database) and methods like list_students, get_course_by_name and create_student to add, delete, update end return data from database.

You, probably, will create facades to group the classes in a logical sequence, add more if’s, else’s and loops to control the code flow.

At the end of the sprint, you have a scenario implemented and tested.

There is nothing wrong with its style of implementation. It is a common process. However, something loses the importance in this process: the business scenario itself.


In this article I’ll showcase a behavior-driven development that converts business languages directly to executable code. The intention is to keep the implementation closer to the business language and promote the code to the source-of-truth.

Gherkin Scenarios for the Education Platform

Going back to the fictional (not much) story. Here are some scenarios an education platform could have:

Feature: Student GPA and approval

  Scenario: Student is approved when GPA is 7 or higher and all subjects are passed
    Given a student named "John" is enrolled in the "Computer Science" course
    And the course has the subjects "Math", "Physics", and "Programming"
    And the student has the following grades:
      | Subject     | Grade |
      | Math        | 7     |
      | Physics     | 8     |
      | Programming | 9     |
    When the system calculates the student's GPA
    Then the GPA should be 8
    And the student status should be "Approved"

Feature: Student enrollment in course subjects

  Scenario: Student cannot enroll in a subject from another course
    Given a student named "Carlos" is enrolled in the "Medicine" course
    And the subject "Algorithms" belongs to the "Computer Science" course
    When the student tries to enroll in the subject "Algorithms"
    Then the enrollment should be rejected
    And the system should show the message "Students can only enroll in subjects from their own course"

Feature: Student enrollment in a course

  Scenario: Student enrolls in an active course
    Given a course named "Architecture" is active
    When a student named "Julia" tries to enroll in the "Architecture" course
    Then the enrollment should be accepted
    And the system should show the message "Student enrolled in course"

Feature: Course cancellation

  Scenario: Students cannot enroll in a canceled course
    Given a course named "Architecture" has been canceled by the general coordinator
    When a student named "Julia" tries to enroll in the "Architecture" course
    Then the enrollment should be rejected
    And the system should show the message "Canceled courses cannot accept new enrollments"

Enter fullscreen mode Exit fullscreen mode

They are pretty, readable, easy to understand, and find inconsistencies. Now a possible implementation as described in the previous story. It was simplified for the sake of this article. Let us look at a more traditional implementation.

# Entities
class Course:
    def __init__(self, course_id, name):
        self.course_id = course_id
        self.name = name
        self.is_canceled = False


class Student:
    def __init__(self, student_id, name):
        self.student_id = student_id
        self.name = name
        self.course = None


# Application
class UniversityService:
    def __init__(self):
        self.courses = {}
        self.students = {}

    def create_course(self, course_id, name):
        self.courses[course_id] = Course(course_id, name)

    def create_student(self, student_id, name):
        self.students[student_id] = Student(student_id, name)

    def cancel_course(self, course_id):
        course = self.courses.get(course_id)

        if course is None:
            raise ValueError("Course not found")

        course.is_canceled = True

    def enroll_student_in_course(self, student_id, course_id):
        student = self.students.get(student_id)
        course = self.courses.get(course_id)

        if student is None:
            raise ValueError("Student not found")

        if course is None:
            raise ValueError("Course not found")

        if course.is_canceled:
            raise ValueError("Canceled courses cannot accept new enrollments")

        student.course = course


# Scenario: Students cannot enroll in a canceled course
service = UniversityService()

service.create_course("C1", "Architecture")
service.create_student("S1", "Julia")
service.cancel_course("C1")

try:
    service.enroll_student_in_course("S1", "C1")
    print("Unexpected result: student enrolled in a canceled course")
except ValueError as e:
    print(e)


Enter fullscreen mode Exit fullscreen mode

It was done in a traditional style. Notice the technical references like service and the preconditions and business logic spread in many ifs in the code. We forgot to represent the system behavior in a simple and explicit way.

The scenario was spread into many pieces and it may be hard to put all of them together when we need to understand the code in the future.

Consider that more features will be integrated into the code and more if/else will be introduced to control the business logic and new flows.

In summary, the scenario cannot be read as it was presented by the business team. It is hard to validate that the system is doing what it should do without proper unit tests and careful code review.

We can try to test its integration with Python Behave to bring the explicit behavior back to the game, but it may be hard to do it without coming up against technical stuff like services.

The system works, but it is hard to prove that it behaves as expected just by reading the code.


At this point, the development team and business one are not talking the same language anymore. There is a translation from business language to production code (technical stuff).
Behavior-driven development


Now, using the framework Guará to represent the scenarios directly in the code. The code now tells the story.

For example, the scenario Student enrollment in a course can be written like this:

from guara.application import Application

eduapp = Application()

(
    eduapp.given(IsActiveCourse, course_id=course_id)
    .and_(IsNotStudentInACouse, student_id=student_id)
    .when(
        EnrollStudentInCourse,
        student_id=student_id,
        course_id=course_id,
    )
    .then(it.IsEqualTo, "Student enrolled in course")
)


Enter fullscreen mode Exit fullscreen mode

The preconditions IsActiveCourse and IsNotStudentInACourse are now explicit and are at the higher level of the code. Not buried in the methods in form of if conditionals. The precondition and action classes have single responsibilities.

from guara.transaction import AbstractTransaction

class IsActiveCourse(AbstractTransaction):
    def do(self, course_id):
        print(f"Checking the status of course {course_id}")
        status = database.courses.get_status(course_id=course_id)
        if status == "Active":
            return True
        raise CourseCanceledException("Course canceled")


class IsNotStudentInACourse(AbstractTransaction):
    def do(self, student_id):
        print(f"Checking if student in a course")
        course = database.student.get_course()
        if course:
            raise StudentException("Student already in a course")


class EnrollStudentInCourse(AbstractTransaction):
    def do(self, student_id, course_id):
        print(f"Enrolling student {student_id} in course {course_id}")
        status = database.enroll_course(course_id, student_id)
        return "Student enrolled in course"

Enter fullscreen mode Exit fullscreen mode

In the end, it is easier to compare the code against the scenario steps and assert they are present in the code.

import argparse
from guara.transaction import Application
from guara import it

eduapp = Application()

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("--action", required=True)
    parser.add_argument("--student-id")
    parser.add_argument("--course-id")

    args = parser.parse_args()

    if args.action == "enroll_course":
        try:
            (
                eduapp.given(HasCourse, course_id=args.course_id)
                .and_(IsActiveCourse, course_id=args.course_id)
                .and_(HasStudent, student_id=args.student_id)
                .and_(IsNotStudentEnrolledInCourse, student_id=args.student_id)
                .when(
                    EnrollStudentInCourse,
                    student_id=args.student_id,
                    course_id=args.course_id,
                )
                .asserts(it.IsTrue)
            )
        except Exception as e:
            print(str(e))
            app.undo()

# Calling the CLI            
python edu.py enroll-course --course-id 10 --student-id 1324

Enter fullscreen mode Exit fullscreen mode

Benefits

  • The production code is now the source of truth
  • It can be compared directly to the business scenarios
  • The responsibilities are encapsulated in dedicated classes
  • It is possible to undo operations easily once the framework is based on the Command Pattern (GoF)
  • It is easy to add more behavior to the code without changing other classes
  • The classes are reusable
  • It hides the technical stuff. They still exist, but now the actions are first-class citizens

Points of attention

  • It is not a one-size-fits-all style. It is necessary to evaluate if the system under development will benefit from this code style
  • Makes more sense when the scenarios are defined in Gherkin language; otherwise, it will be necessary to translate the requirement to code as done in the traditional implementation

Conclusion

The important difference is that the source code still reads almost like the original Gherkin scenario. Instead of hiding business rules inside technical layers, we keep them visible and explicit in the code.