Skip to content

Instantly share code, notes, and snippets.

@lukegalea
Created November 16, 2022 21:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lukegalea/a6920d934394deb4de9f47aab1807e35 to your computer and use it in GitHub Desktop.
Save lukegalea/a6920d934394deb4de9f47aab1807e35 to your computer and use it in GitHub Desktop.
code_to_diagram.md

Code to Diagram: A Developer’s Guide to Coding Beautiful Diagrams

Many software developers spend a lot of their day staring at a text editor. But, we quickly learn that a wall of ASCII characters isn't the best way to learn or visualize complex information.

Maintaining visual artifacts, like an architecture or entity relationship diagram, can have big benefits for you and your team, but comes with the cost of maintaining yet another document.

As systems change, the diagrams that document them must change too. Expecting regular revisions and updates should be the norm. Version-controlling image files can quickly become unmanageable, though. Even if you get past the hurdle of versioning, creating new diagrams or redeveloping existing ones is tedious manual work that requires learning new tools. This is why “text-to-diagram” tools, or diagrams as code, are gaining popularity in the industry. A text-to-diagram workflow involves creating diagrams from text instructions or a piece of code, so developers can continue using the same tools they use to write software to also produce diagrams and documentation.

So, how can you make better documentation? It comes down to programmatically creating and maintaining your diagrams rather than hand drawing them. Here's how we approach it at 7shifts.

Why Are Diagrams Important?

Visual communication has become the digital communication mode of choice within many corporations. Diagrams, in particular, are preferred to text when it comes to presenting dense information to an audience.

The human brain is structured in a way that favors visual processing of information and pattern recognition. This phenomenon, known as the picture superiority effect, argues that humans are more likely to remember pictures and images than words alone.

In today’s digital environment, users are constantly overwhelmed by text and image information. A study of the volume of information web users actually consume found that, on average, users only read about 20 percent of the text on a typical web page. Most users tend to prefer looking at diagrams, photos, and imagery over text.

Diagrams are a good way to showcase complex systems at a glance. It's not only easier to digest but it also contributes to longer retention.

Using GUIs for Diagrams

Graphical user interfaces (GUIs) are one common way software engineers create diagrams. You've likely used a drag-and-drop GUI tool like Visio or Google Draw at some point. Although there are many GUI tools available, they have some drawbacks. For instance:

  • Manually laying out diagrams using a graphical interface can be time-consuming, especially when describing a complex system.
  • Modifying and updating your diagrams can quickly become cumbersome. Adding new components to your codebase? If you need to modify your architectural diagram to reflect the changes, you may have to move every item in the diagram to create space. Or, you may even need to redraw the diagram from scratch.

Why Use Code to Create Diagrams?

Creating diagrams with code means using text notation (“code”) to describe the desired visual. An automatic rendering tool then creates a corresponding diagram from the text description.

While maintaining a typical image diagram, you might deal with the following challenges:

  • Image versioning and diffing between versions
  • Re-laying out an existing diagram to accommodate new content
  • Tool-specific file formats that make importing and exporting into other tools difficult

These challenges are easily addressed by creating your diagrams with code. You can use a general-purpose language like JavaScript or Python to render diagrams. But this low-level approach can be even more time-consuming than using GUI tools. Instead, many domain-specific languages (DSLs) exist to make the process faster and easier.

Diagram DSLs are generally declarative; you specify the desired outcome rather than the steps required to produce it. For diagrams, that means describing the needed elements and their relationships so the tool can create your diagram for you by handling layout and other concerns.

You’re probably already familiar with some declarative DSLs like HTML, CSS or SQL. Note how an HTML document can specify a

, rows, and columns without being concerned with how to render it on screen. Similarly, a SQL query can indicate that a resultset should be arranged in ORDER BY date without needing to specify how to perform the sort itself.

Declarative DSL tools permit you to define shapes, layout diagrams, or even define UML diagrams. They can also be implemented as an external DSL that uses an independent interpreter, in another host language as a library, or even automated and built into your build pipeline. Regardless of the implementation approach, DSLs let you focus on the diagram you want rather than on how to draw it.

Should You Use DSLs Instead of GUIs?

DSLs offer certain advantages over GUIs for creating software engineering diagrams.

Maintainability

Maintaining code and technical documents is an essential part of software engineering. Teams rely on the ability to search, reuse, and change text as needed. Imagine that you have a PNG file containing your system architectural diagram located inside one of your repos, and you need to add a microservice to your application. Updating this image would need some picture manipulation or GUI skills and would be time-consuming. Using a DSL, the diagram will live in your repo as a searchable, editable, and reusable text-based file. You can edit the file and add the new microservice to your drawing and commit to source control, potentially triggering an automated build step to regenerate the rendered image.

Versioning

The ability to track changes and compare two versions of a document in a version control system is often undervalued for technical diagrams. GUI-generated drawings are usually in formats that make it impossible to compare versions and track changes. Conversely, a coded diagram in a DSL can be version-controlled and diffed with whatever system your team uses.

Machine-Readable Generation

Keeping diagrams in a machine-readable format for easy rendering can make a huge difference in maintainability. Generating diagrams from a GUI involves arranging and connecting shapes. This makes either you or the GUI tool the source of the resulting image. For graphs rendered from code, the textual file provides a source in a structured format that can be independently managed in a single location.

Easier Visuals

Many GUI tools claim an easy learning curve. But where do most software developers prefer to focus? It's usually on writing code, not spending time artistically crafting a visualization. Using a DSL brings diagramming to the textual world you’re already familiar with.

DSL Tools for Creating Beautiful Diagrams

There are multiple DSLs available for coding visually appealing diagrams. Here's some of the best options we've come across:

PlantUML

PlantUML is an open source, text-based tool for quickly creating diagrams from simple text syntax. The 100 percent plain text definition of PlantUML specifies the type of diagram to be created and the elements that will make up the diagram. As the name implies, PlantUML was created to make UML diagrams. However, you can use it to make nearly any diagram you need. We’ve highlighted some of the common ones below:

PlantUML has its own online rendering server for creating diagrams, which you can easily download and install to your local machine. It also integrates with popular code editors like Visual Studio Code and Eclipse.

Here’s an example of how you can create a simple diagram using PlantUML:

@startuml Simple Entity-Relationship Diagram
Table01 ||..|| Table02
Table01 }|--|| Table03
Table01 ||--|{ Table04
Table05 }o--o| Table01
@enduml

The code above creates a simple entity-relationship (ER) diagram based on the syntax specified in the documentation. The first line is the opening statement for the renderer, lines 2 to 5 specify the relationships between tables in a database, and the last line closes the syntax.

You can run the syntax in an online editor. The code renders the diagram below:

Simple entity-relationship diagram

dbdiagram.io

A simple, popular tool for creating database entity-relationship diagrams is dbdiagram.io. It allows you to quickly code your data model diagram using the custom language. The tool has additional features to help you perform other tasks like generating SQL statements, integrating with SQL databases, and online sharing.

The following lines of code show the data model for a job hiring platform:

ENUM user_type {
  recruiter
  job_seeker
}

ENUM application_status {
  pending
  in_consideration
  failed
}

Table user_info {
  id [uuid] pk
  first_name varchar
  last_name varchar
  email varchar unique
  phone_number varchar
}

Table company {
  id [uuid] pk
  name varchar
  recruiter_id  varchar [ref: >  user_info.id]
  address varchar
  business_type varchar
}

Table job_openings {
  id [uuid] pk
  company_id  varchar [ref: >  company.id]
  requirements varchar
  description varchar
  created_by varchar [ref: >  user_info.id]
  created_at timestamptz
}

Table applications {
  id [uuid] pk
  job_id  varchar [ref: >  job_openings.id]
  applicant_id varchar [ref: >  user_info.id]
  created_at timestamptz
  updated_at timestamptz
}

You can render the diagram by using the online editor to create your model. The above code renders as the following:

Job hiring platform data model

Mermaid

Mermaid is a tool that helps you make a variety of complex diagrams. The syntax is simple and intuitive enough for developers of nearly any level, and you can use it to create chart types such as flowcharts, Gantt charts, and pie charts. Mermaid can be used in different ways, including with a live editor, browser extension, and CLI. It also integrates with GitHub and various code editors.

The example below shows how Mermaid creates a simple sequence diagram:

sequenceDiagram
    critical Establish a connection to the DB
        Backend-->DB: connect
    option Network timed out
        Backend-->Backend: Log error
    option Incorrect Credentials
        Backend-->Backend: Log different error
    end

The first line specifies the type of diagram to be rendered, and the subsequent lines describe the component element. The diagram highlights the handling of several conditions and errors in a network connection.

The rendered image is below:

Sequence diagram

Graphviz

Graphviz is probably the most widely recognized tool on this list. The open source tool uses a graph description language known as DOT and provides software libraries for your application to use its functionalities.

Below is an example of a simple process diagram in Graphviz:

graph G {
	fontname="Helvetica,Arial,sans-serif"
	node [fontname="Helvetica,Arial,sans-serif"]
	layout=neato
	kernel -- zombie;
	kernel -- sleep;
	kernel -- runmem;
	sleep -- runmem;
	run -- intr;
	intr -- runbl;
	runbl -- run;
	run -- kernel;
}

You can render the code in the online playground, which produces the following diagram:

Graphviz process diagram

Conclusion

Coding your diagrams helps you create visually appealing work with minimal effort. Using a diagram DSL is a great way to provide easily understandable visual content for internal and external stakeholders and ensure that your team has all the information they need without resorting to time-consuming hand drawing.

7shifts makes team management software designed for restaurants. We help managers and operators spend less time and effort scheduling their staff, reduce their monthly labor costs and improve team communication. The result is simplified team management, one shift at a time. At 7shifts we use diagram DSLs quite a bit internally, including Graphviz to maintain our org chart as well as tracking our hiring plans and team movement. We also love Mermaid sequence diagrams for documenting interfaces with our partners’ APIs.

Interested in joining us in our mission to simplify team management and improve performance for restaurants everywhere? Check out our open roles!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment