Definition
A Domain-Specific Language (DSL) is a programming or specification language that is tailored to a specific problem domain.
Unlike general-purpose languages (e.g., Python, Java, C++), a DSL is optimized for expressiveness and efficiency within its niche.
Types of DSLs
- External DSLs → Standalone languages with their own syntax, parser, and tooling.
- Example: SQL, HTML, CSS.
- Internal DSLs (Embedded DSLs) → DSLs built inside a general-purpose language, reusing its syntax and runtime.
- Example: LINQ in C#, RSpec in Ruby.
Examples
🗄 SQL (Structured Query Language) – External DSL
SELECT name, age
FROM users
WHERE age > 30;- SQL is a DSL for database querying and manipulation.
- Highly expressive in the database domain, but useless outside it.
🎨 CSS – External DSL
body {
background-color: black;
color: white;
}- CSS is a DSL for styling web pages.
- Optimized for design, not general programming.
🐍 RSpec (Ruby) – Internal DSL
describe Calculator do
it "adds numbers" do
expect(Calculator.add(2, 3)).to eq(5)
end
end- RSpec is an internal DSL in Ruby for writing readable tests.
- Expresses test logic in a human-like way.
🟨 LINQ (C#) – Internal DSL
var result = from user in users
where user.Age > 30
select user.Name;- LINQ is an embedded DSL in C# for querying data collections.
- It borrows ideas from SQL but integrates into the language.
Benefits
- High expressiveness in a narrow domain.
- Easier for domain experts (not just programmers) to use.
- Reduces boilerplate code.
Drawbacks
- Limited outside the target domain.
- Requires learning an extra language/syntax.
- External DSLs need parsers and tooling support.
Related Concepts
- Paradigms
- Metaprogramming (DSLs often built with it)
- SQL
- Regex (another example of a DSL)