Most developers have drawn a class diagram on a whiteboard at some point. But when it comes to writing UML as code versionable, repeatable, and quick to generate many teams still rely on drag-and-drop tools that slow them down. UML diagram code examples give developers a way to model software architecture directly in text, commit diagrams alongside source code, and keep documentation in sync without switching contexts. If you're building a system and need to communicate structure, behavior, or workflows to your team, writing UML in code is one of the fastest ways to do it.

What does it actually mean to write UML as code?

UML (Unified Modeling Language) diagram code uses a text-based syntax to describe diagrams like class diagrams, sequence diagrams, state machines, and use case diagrams. Instead of dragging boxes on a canvas, you write short, declarative statements that a rendering tool converts into a visual diagram. Tools like PlantUML, Mermaid, and Structurizr support this workflow. The code lives in your repository, diffs cleanly in pull requests, and regenerates the diagram whenever the source changes.

This approach works especially well for developers who think in code first. You define a class, its attributes, its relationships and the tool handles layout. No alignment headaches, no pixel-pushing.

Why would a developer use UML code instead of a visual editor?

Visual editors are fine for quick sketches. But for teams working across time zones or integrating diagrams into CI/CD pipelines, text-based UML solves real problems:

  • Version control: Diagrams live as .puml or .mmd files, so you can track changes, review diffs, and roll back just like application code.
  • Speed: Writing a class diagram in PlantUML is often faster than dragging 15 boxes and connecting them manually.
  • Consistency: Code-generated diagrams follow the same layout rules every time. No one's personal style skews the output.
  • Collaboration: Remote teams can collaborate on diagramming with shared code files instead of passing around static image exports.

What are the most common UML diagram types developers write as code?

Class diagrams

Class diagrams show the structure of a system classes, their properties, methods, and how they relate. Here's a basic PlantUML example:

@startuml
class User {
 - id: int
 - name: string
 - email: string
 + login(): void
 + logout(): void
}

class Order {
 - orderId: int
 - total: float
 - status: string
 + calculateTotal(): float
 + cancel(): void
}

User "1" --> "" Order : places
@enduml

This defines two classes with private and public members and a one-to-many relationship. A renderer produces a clean, labeled diagram from this text.

Sequence diagrams

Sequence diagrams show how objects interact over time useful for modeling API calls, authentication flows, or message passing. A Mermaid example:

sequenceDiagram
 participant Client
 participant API
 participant Database

 Client->>API: POST /login
 API->>Database: Query user credentials
 Database-->>API: User record
 API-->>Client: JWT token

This is readable, versionable, and takes about 30 seconds to write. If your team is evaluating different tools for this kind of work, comparing diagramming tools and their code capabilities can help you pick the right one.

State machine diagrams

State diagrams model how an object transitions between states. This is useful for order processing, user sessions, or any system with lifecycle management:

@startuml
[] --> Draft
Draft --> Submitted : submit()
Submitted --> Approved : approve()
Submitted --> Rejected : reject()
Approved --> Shipped : ship()
Shipped --> Delivered : deliver()
Delivered --> []
Rejected --> []
@enduml

Each arrow represents a valid transition triggered by an action. The diagram makes it immediately clear which state changes are allowed and which aren't.

Use case diagrams

Use case diagrams map user interactions to system functionality. They're simple but effective for early-stage requirement discussions:

@startuml
left to right direction
actor Customer
actor Admin

Customer --> (Browse Products)
Customer --> (Place Order)
Customer --> (View Order History)
Admin --> (Manage Inventory)
Admin --> (Process Refunds)
@enduml

How do you pick between PlantUML, Mermaid, and other tools?

Each tool has tradeoffs. PlantUML supports the widest range of diagram types and has been around longer. Mermaid is built into GitHub, GitLab, and many documentation platforms, making it easy to embed in markdown files. Structurizr targets architecture models with a domain-specific language.

A few things to consider:

  • Where will the diagram live? If it's in a GitHub README, Mermaid is the simplest choice. If it's in a dedicated design doc, PlantUML offers more diagram types.
  • Do you need offline rendering? PlantUML runs locally with Java. Mermaid typically needs a JavaScript runtime or a hosted renderer.
  • What diagram types do you need? PlantUML handles activity, component, deployment, and object diagrams in addition to the basics. Mermaid covers the most common types but has fewer advanced options.

What mistakes do developers make when writing UML as code?

There are patterns that trip people up especially when they're new to text-based diagramming:

  1. Overcomplicating the diagram: Cramming every class and relationship into one diagram makes it unreadable. Split large systems into multiple focused diagrams.
  2. Ignoring naming conventions: Using inconsistent names across diagrams creates confusion when someone else reads the code. Keep class and method names aligned with your actual codebase.
  3. Forgetting directionality: Using an undirected relationship when a directed one is needed (or vice versa) changes the meaning. A --> arrow in PlantUML means something specific compared to --.
  4. Not validating rendering: Writing diagram code without previewing it can lead to broken layouts. Always render before committing.
  5. Skipping stereotypes and notes: Annotations like <<interface>> or note right of add clarity that pure boxes and arrows miss.

How do you integrate UML diagram code into your development workflow?

The real value shows up when diagrams become part of how your team works not a one-off activity:

  • In pull requests: When you change a class or API endpoint, update the corresponding diagram code in the same PR. Reviewers see both the implementation and the architectural impact.
  • In CI/CD pipelines: Tools like PlantUML can render diagrams as part of your build process. Export SVGs or PNGs automatically and publish them to a documentation site.
  • In markdown docs: Mermaid diagrams render directly in GitHub and GitLab markdown files, so architecture docs stay visual without requiring separate image files.

For teams distributed across locations, having diagrams that live in code and render on demand means everyone sees the same model without chasing down the latest export.

Can you generate UML diagrams from existing code?

Yes reverse engineering UML from code is possible with several tools. PlantUML has plugins for IDEs like IntelliJ and VS Code that generate class diagrams from Java, C#, or TypeScript source files. Tools like pyreverse produce UML from Python codebases. The generated diagram code can serve as a starting point that you clean up and version.

This works well for legacy systems where no documentation exists. Generate the diagram, review it for accuracy, commit it, and maintain it going forward. It's far more practical than trying to diagram a large system from scratch.

Quick checklist: writing your first UML diagram as code

  • Pick a tool (PlantUML for broad support, Mermaid for markdown-first workflows).
  • Start with one diagram type class or sequence diagrams are the most common.
  • Write the diagram code in a .puml or .mmd file next to your source code.
  • Render it locally or in your editor before committing.
  • Add it to your repo and include it in your next pull request for review.
  • Keep the diagram updated when the code it models changes.
  • Split complex systems into multiple small diagrams instead of one large one.

Next step: Pick one module or feature in your current project. Write a class diagram or sequence diagram for it in PlantUML or Mermaid this week. Commit it alongside the code. You'll quickly see whether the workflow fits your team and it takes less time than you'd expect.