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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
Forbes - Security
Forbes - Security
WordPress大学
WordPress大学
P
Proofpoint News Feed
T
Threat Research - Cisco Blogs
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
Spread Privacy
Spread Privacy
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
P
Privacy International News Feed
A
About on SuperTechFans
T
Tailwind CSS Blog
I
InfoQ
S
Securelist
云风的 BLOG
云风的 BLOG
罗磊的独立博客
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
B
Blog RSS Feed
V
Visual Studio Blog
Know Your Adversary
Know Your Adversary
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
腾讯CDC
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
博客园 - 【当耐特】
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
F
Full Disclosure
S
Secure Thoughts
博客园 - 司徒正美
J
Java Code Geeks
Y
Y Combinator Blog
Google Online Security Blog
Google Online Security Blog
GbyAI
GbyAI
N
News and Events Feed by Topic
Help Net Security
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Project Zero
Project Zero
T
Tenable Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tor Project blog
MyScale Blog
MyScale Blog
Scott Helme
Scott Helme
小众软件
小众软件
K
Kaspersky official blog

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
Domain Primitives in Go: One Type Per Real-World Concept
Gabriel Anha · 2026-05-01 · via DEV Community

You're reviewing a pull request. The function signature is this:

func TransferFunds(
    from string,
    to string,
    amount float64,
    currency string,
    note string,
) error

Enter fullscreen mode Exit fullscreen mode

Five arguments. Four of them are strings. The reviewer reads the diff, nods, hits approve. Two weeks later support gets a ticket: a EUR transfer landed in a USD account at the dollar amount of the original request. Somewhere a float64 was treated as cents. Somewhere from and to got swapped because the caller had them in a different order in a struct.

None of those bugs needed to be possible. They became possible the moment the team decided that "string" was a good enough type for an account ID, a currency code, and a free-form note all at once.

Domain primitives fix this. The thesis is short: every real-world concept gets its own Go type. Not a string with validation. Not an int64 with a comment. A named type, a private field, a constructor that validates, and methods that enforce its invariants. Once a value enters the domain through that constructor, every function downstream gets a compile-time guarantee for free.

The broader principle is simple: every concept is a type, no exceptions.

The Cost of "Just Use a String"

A string for a UserID looks economical. One less file, one less constructor, one less type to import. It is also four hidden costs you pay later:

  1. No swap protection. func DeleteAccount(userID, adminID string) — both are strings, so the compiler cannot stop you from calling DeleteAccount(adminID, userID). The wrong account dies.
  2. Validation duplicated everywhere. Every layer that touches the value re-checks it, or trusts the layer above. One of those layers will eventually skip the check.
  3. No domain methods. You cannot put IsExpired() on a string. You end up with a free-standing IsExpired(token string) that nobody can find.
  4. Equality is by value, not by meaning. Two string tokens are equal if their bytes match. Two SessionID tokens should be equal only if they refer to the same session. You might also want canonical formatting (lowercase, trimmed) to be part of equality.

A domain primitive collapses all four problems into one solution: define the type once, validate at the edge, and the compiler protects the rest of the codebase.

The Shape Every Domain Primitive Shares

Five things, every time:

type Email struct {
    value string // unexported — forces use of the constructor
}

func NewEmail(raw string) (Email, error) { /* validate */ }
func (e Email) String() string             { return e.value }
func (e Email) Equals(other Email) bool    { return e.value == other.value }
func (e Email) IsZero() bool               { return e.value == "" }

Enter fullscreen mode Exit fullscreen mode

A struct with one unexported field. A constructor that validates and is the only path to a valid value. A String() method for printing. An Equals method so callers do not reach into the field directly. An IsZero because Go's zero value bypasses the constructor and you need a way to detect that at trust boundaries.

That is the entire pattern. Four concepts that show up in almost every backend show why.

UserID: Stop Swapping Identifiers

The first place domain primitives pay off is identifiers. Every system has at least three or four ID types: UserID, OrderID, ProductID, SessionID. Every one of them is "just a string" until something gets swapped.

package domain

import (
    "errors"

    "github.com/google/uuid"
)

type UserID struct {
    value uuid.UUID
}

func NewUserID(raw string) (UserID, error) {
    parsed, err := uuid.Parse(raw)
    if err != nil {
        return UserID{}, errors.New(
            "user id: not a valid uuid",
        )
    }
    return UserID{value: parsed}, nil
}

func GenerateUserID() UserID {
    return UserID{value: uuid.New()}
}

func (id UserID) String() string {
    return id.value.String()
}

func (id UserID) Equals(other UserID) bool {
    return id.value == other.value
}

Enter fullscreen mode Exit fullscreen mode

Now define OrderID the same way. Both wrap a UUID. Both have the same shape. They are still incompatible at the type level.

func GetUser(id UserID) (*User, error)    { /* ... */ }
func GetOrder(id OrderID) (*Order, error) { /* ... */ }

userID, _ := NewUserID(req.PathValue("id"))
GetOrder(userID) // compile error: cannot use UserID as OrderID

Enter fullscreen mode Exit fullscreen mode

An order ID passed to a user lookup, returning zero rows, the API responding "user not found": that bug cannot exist. The compiler refuses to build the binary.

Email: Validate Once, Trust Forever

Email is the canonical example because everyone has been bitten by it. Some layer accepts an empty string. Another layer accepts a string with no @. A third layer normalises by lowercasing. Three different rules in three different places.

A domain primitive lifts the rule into the type:

package domain

import (
    "errors"
    "fmt"
    "net/mail"
    "strings"
)

type Email struct {
    value string
}

func NewEmail(raw string) (Email, error) {
    raw = strings.TrimSpace(strings.ToLower(raw))
    if raw == "" {
        return Email{}, errors.New("email: empty")
    }
    if _, err := mail.ParseAddress(raw); err != nil {
        return Email{}, fmt.Errorf(
            "email: %q invalid: %w", raw, err,
        )
    }
    return Email{value: raw}, nil
}

func (e Email) String() string { return e.value }

func (e Email) Domain() string {
    at := strings.IndexByte(e.value, '@')
    return e.value[at+1:]
}

func (e Email) MarshalJSON() ([]byte, error) {
    return []byte(`"` + e.value + `"`), nil
}

func (e *Email) UnmarshalJSON(data []byte) error {
    raw := strings.Trim(string(data), `"`)
    parsed, err := NewEmail(raw)
    if err != nil {
        return err
    }
    *e = parsed
    return nil
}

Enter fullscreen mode Exit fullscreen mode

JSON unmarshalling is the boundary you have to think about explicitly. A struct with unexported fields cannot be filled by encoding/json directly, so you write UnmarshalJSON once and every API handler that decodes a request body now validates email formatting for free. The same applies to database/sql's Scan — when you read an email from a row, the same constructor runs.

Email.Domain() is a domain method attached where it belongs. Any handler that needs to know the email's domain calls e.Domain(), not strings.Split(emailString, "@")[1] for the fifteenth time.

Money: Kill Currency Mixing at Compile Time

Money is the type that punishes carelessness the hardest. Storing it as float64 loses cents to floating-point rounding. Storing it as int64 loses currency. Storing currency as a string next to the amount lets two amounts in different currencies be added without complaint.

A real Money type carries both pieces and refuses to mix them:

package domain

import (
    "errors"
    "fmt"
)

type Currency string

const (
    USD Currency = "USD"
    EUR Currency = "EUR"
    GBP Currency = "GBP"
)

func ParseCurrency(raw string) (Currency, error) {
    switch Currency(raw) {
    case USD, EUR, GBP:
        return Currency(raw), nil
    default:
        return "", fmt.Errorf(
            "currency: %q not supported", raw,
        )
    }
}

type Money struct {
    cents    int64
    currency Currency
}

var ErrCurrencyMismatch = errors.New(
    "money: currency mismatch",
)

func NewMoney(cents int64, c Currency) (Money, error) {
    if c == "" {
        return Money{}, errors.New(
            "money: currency required",
        )
    }
    return Money{cents: cents, currency: c}, nil
}

func (m Money) Add(other Money) (Money, error) {
    if m.currency != other.currency {
        return Money{}, ErrCurrencyMismatch
    }
    return Money{
        cents:    m.cents + other.cents,
        currency: m.currency,
    }, nil
}

func (m Money) IsNegative() bool { return m.cents < 0 }

func (m Money) String() string {
    return fmt.Sprintf(
        "%d.%02d %s",
        m.cents/100,
        absInt(m.cents%100),
        m.currency,
    )
}

func absInt(v int64) int64 {
    if v < 0 {
        return -v
    }
    return v
}

Enter fullscreen mode Exit fullscreen mode

a.Add(b) returns an error if currencies do not match. There is no way to write total += amount and silently turn a EUR balance into a corrupted dollar total. Every place that sums money has to handle the mismatch, which is exactly the discomfort that makes the bug visible.

The original TransferFunds signature now reads like this:

func TransferFunds(
    from AccountID,
    to AccountID,
    amount Money,
    note string,
) error

Enter fullscreen mode Exit fullscreen mode

Four parameters instead of five. Each one a different type. from and to cannot be swapped with amount. amount cannot be passed in the wrong currency. The string note is still a string because a free-form note has no rules. That is the one case where a primitive type stays a primitive.

PostalCode: Format Encodes Country

Postal codes look like a string with a regex on top. They are not. The format depends on the country, and the country depends on the address it belongs to. A primitive that refuses to exist in the wrong shape is the one that never gets the rule wrong:

package domain

import (
    "errors"
    "fmt"
    "regexp"
    "strings"
)

type PostalCode struct {
    value   string
    country Country
}

type Country string

const (
    US Country = "US"
    DE Country = "DE"
    UK Country = "UK"
)

var postalPatterns = map[Country]*regexp.Regexp{
    US: regexp.MustCompile(`^\d{5}(-\d{4})?$`),
    DE: regexp.MustCompile(`^\d{5}$`),
    UK: regexp.MustCompile(
        `^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$`,
    ),
}

func NewPostalCode(
    raw string, c Country,
) (PostalCode, error) {
    raw = strings.ToUpper(strings.TrimSpace(raw))
    pattern, ok := postalPatterns[c]
    if !ok {
        return PostalCode{}, fmt.Errorf(
            "postal: country %q unsupported", c,
        )
    }
    if !pattern.MatchString(raw) {
        return PostalCode{}, errors.New(
            "postal: format invalid for country",
        )
    }
    return PostalCode{value: raw, country: c}, nil
}

func (p PostalCode) String() string  { return p.value }
func (p PostalCode) Country() Country { return p.country }

Enter fullscreen mode Exit fullscreen mode

A PostalCode cannot exist without a country. The validation is country-specific by design. Trying to construct a UK postal code with the US format fails at the boundary, before any address row gets written.

The Frontier: Where to Stop

Domain primitives have a cost. Every type is a file, a constructor, a String(), possibly a MarshalJSON. The cost is real. The question is where the line sits.

The line is invariants. If a value has rules (must be non-empty, must match a format, must come from a fixed set, must be comparable to other values of its kind), wrap it. If it does not, leave it alone. A user's bio is just text; making Bio a type buys nothing. A discount percentage is bounded between 0 and 100; making Percentage a type stops a 150% discount from ever getting persisted.

Three signs you need a domain primitive:

  1. You wrote if x == "" { return errors.New("...") } more than once for the same concept. That validation belongs in a constructor.
  2. Two values share an underlying type and could be swapped. userID and adminID both string. weight and height both float64. The compiler should have your back.
  3. You catch yourself reaching for strings.Split or a regex on a value across multiple files. That is a method asking to be born on a type.

The point of the pattern is not maximalism. The point is that the type system is the cheapest place to enforce a rule, because it runs at compile time, in every layer, with no test to write and no drift to manage. Every concept that has a rule and cannot defend itself becomes a class of bug you keep meeting in production.

When the function signature has eight string parameters, the system is telling you something. The fix is not better naming. The fix is more types.


If this was useful

Domain primitives are one of the first patterns Hexagonal Architecture in Go covers, because hexagonal layering only works when the domain layer carries its own invariants. Once your UserID, Email, and Money defend themselves, ports and adapters get cleaner — the application service stops re-validating, the database adapter stops returning raw strings, and the HTTP handler shrinks to a parser. The book walks through the whole stack with real Go code.

If you build with Claude Code or other AI coding tools, Hermes IDE is the editor I'm building for that workflow — domain models like the ones above are exactly the kind of thing it helps you scaffold and keep consistent across a service.

Thinking in Go — the 2-book series on Go programming and hexagonal architecture