Domain-Driven Design: DDD is a process that aligns your code with the reality of your problem domain. As your product evolves, adding new features becomes as easy as it was in the good old days of greenfield development. Although DDD understands the need for software patterns, principles, methodologies, and frameworks, it values developers and domain experts working together to understand domain concepts, policies, and logic equally. With a greater knowledge of the problem domain and a synergy with the business, developers are more likely to build software that is more readable and easier to adapt for future enhancement.
~ Scott Millett and Nick Tune (Patterns, Principles, and Practices of Domain-Driven Design — Wrox Publishers)
See that Tower of Babel in the picture above? Okay, so the Babel Fish was one thing—especially for you all fans of Douglas Adams’ book The Hitchhikers Guide To The Galaxy—and the Tower of Babel quite another, with the latter being the one we’re talking about here (Let me guess: The first thing that came to your mind at the mention of the Tower of Babel was the clamor arising from throngs of people in a collective din, clamoring past one other as they all speak in their own distinct languages, past others’ monologues in their languages!) 🎪
But before we get sucked into the Babel vortex—look, it could have been a whole different
vortex that we as a society could’ve gotten pulled into (actually, already is, the inexorable digital vortex, that is)—let’s all of us take a big, deep breath 🐳
My regular readers are of course well aware that it’s only the rarest of occasion and time when I dedicate an essay or two to an individual; this is such an occasion, and this is such a time. With that, I dedicate this essay to Githesh Ramamurthy who is one of the clearest-eyed leaders, embodying what it means to lead by example: He leads with integrity, intelligence, wit, passion, and grace. Githesh is a mentor, benefactor, and friend ☕
Whenever you read these words—and I know that you’ve always carved time out of your super-busy schedule to read what I offer on this blog—please know that your encouragement, plus the priceless lessons that I’ve learned from you, Githesh, will serve me well for a lifetime, especially so at this juncture as I prepare for the quest to help change the world of the Internet of Things (IoT) as we know it today! 🔮
Preamble (By Way Of A Dialogue) ⛱
—Reader: Hey Akram, so whatever this DDD (Domain-Driven Design) thing is anyway, we’re willing to give it a listen. But what—more properly, “who”—in the world is this “Dogma” that you mention in the same breath as the title of this essay: “Domain-Driven Design (DDD) Defies Dogma“? 🐶—Akram: Um, so the “Dogma” part of the story goes something like this: Being the inveterate cat-lover that you all know me as, I nevertheless once took pity on and gave shelter to a dog whose Ma was somewhat indisposed. So this dog’s Ma, as I was saying… 😳—Reader: Yo, stop. Stop right there! Heaven help us, Akram, lest you take it upon yourself to start spinning yarns again. (Dude, we are still licking our wounds after being exposed to your balderdash—that wasn’t so long ago either—having to do with your recursive take on Reveling In The Glory Of Software (On A Stormy Night!)) 👺—Akram: May I inform your gentle ears that the name—Programming Digressions but of course—of our blog site may have something to do with digressing. But hey, we will digress no more! Instead, we’ll dive headfirst into the coolness of DDD. Cool? 😎—Reader: We’ll believe that when we see it. But yeah, go ahead… 🚧
1. Outside, Looking In 🔭
Would you rather be outside, looking in—like the little girl peering through the glass window at the intriguing rodents in a section of the zoo—or instead partake in the grand design, taking a cue from Mother Nature? If you answered yes, and if you’re up for it, let’s you and I follow the road on a quest to find out a particularly powerful software design approach that should not be allowed to languish anymore… 🚕
But first, FWIW, allow me to—and this is especially for those of you who are already looking for me to make things snappy—introduce three sparkling books (including the seminal one which started it all) which capture the aforementioned software design approach that we will be grappling with over the course of this essay:
- Implementing Domain-Driven Design — Addison-Wesley Professional (by Vaughn Vernon)
- Patterns, Principles, and Practices of Domain-Driven Design — Wrox Publishers (by Scott Millett and Nick Tune)
- Domain-Driven Design: Tackling Complexity in the Heart of Software — Addison-Wesley Professional (by Eric Evans)
Each one of the books in the list above is stellar in its own right; ignore it at your own peril (just sayin’.) Curiously enough—referring here to the fine book by Vaughn Vernon—there is a lot of cowboy humor liberally sprinkled throughout the pages of his book, Implementing Domain-Driven Design. Overall, though, it’s a book worth reading: So if riding horses isn’t exactly your thing, please don’t let that blemish your view of a superb book! 🐎
FWIW, I’m going to quickly add that the same author (Vaughn Vernon) went on to write an even more awesome book called. More details—even more than you might care for!—on exactly that can be found in an essay elsewhere: Best Reactive Programming Books.
With that… Whoa, what do we have here but a cowboy—and a petrified one at that—surrounded by crisp prairie grass, looking intently at the paradoxical downtown buildings over yonder… 🌾
Something really, really anachronistic is going on here, methinks ⏳
2. Doing DDD—Until The Cows Come Home! 🐄
Here, then, is the real deal (cowboy humor and all) when you are ready to dive into the implementation details of Domain-Driven Design (DDD). But I hear you asking, Yo, how does this all defy dogma? 🐶
And to which I can only reply—at this time anyway—with the admonishment to please, Hold your horses! Everything comes in its own good time, and for especially those who wait!
As my life goes on I believe
Somehow something’s changed
Something deep inside
Ooh a part of me
There’s a strange new light in my eyes
Things I’ve never known
Changin’ my life
I’ve been searchin’
To find an answer
Take a long time
~ Chicago (Lyrics from (I’ve Been) Searchin’ So Long)
Dogmatism aside, imagine this: Would you rather learn things through rote memorization or via discovery? Where would we be today—as a society whose fabric has been woven through vast infrastructures of inter-networking— had we settled for the de jure standard (the OSI layered model) instead of the far superior de facto standard (TCP/IP networking)? 📬
3. Who Is The Best Designer Of Them All? 📐
Wait a second, Akram, are we going hunting for mushrooms—or toadstools or whatever in the world those three bright-red spotted things growing on stalks are—just as we had settled down with a mug of coffee in hand?! 🍄
Sigh, me and my grand designs: All I was trying to do there was to bring to the forefront of your mind the organically evolving designs sprinkled by Mother Nature across the length and breadth of the natural landscapes around us…
4. Organically Evolving (Software) Designs 🍒
All the same—my grand and outlandish schemes notwithstanding—the oh-so organic evolution outgrowth of those toadstools provides us with a perfect segue into the wherewithal of DDD! And here we are going to hear from the horse’s mouth (Okay, so Eric Evans is a fine human being, and an excellent one at that; I am merely using the proverbial dictum about the apocryphal horse’s mouth.) Yep, Evans is the guy who started it all: DDD as we know it today was ushered into the world through his creative agency. 🏆
And you don’t have to take my word for it—listen to some luminaries of our industry gushing about his work:
If you don’t think you are getting value from your investment in object-oriented programming, this book will tell you what you’ve forgotten to do.
~ Ward Cunningham
This book belongs on the shelf of every thoughtful software developer.
~ Kent Beck
To those rave reviews I’ll add Evans’ succinct round-up of the gestalt of DDD:
I have spent the past decade developing complex systems in several business and technical domains. In my work, I have tried best practices in design and development process as they have emerged from the leaders in object-oriented development. Some of my projects were very successful; a few failed. A feature common to the successes was a rich domain model that evolved through iterations of design and became part of the fabric of the project.
This book provides a framework for making design decisions and a technical vocabulary for discussing domain design. It is a synthesis of widely accepted best practices along with my own insights and experiences. Software development teams facing complex domains can use this framework to approach domain-driven design systematically.
Yep, right there in the pic below is my copy of Evans’ book, surreptitiously propped up against a hefty tome that you should also check out sometime, probably sooner than later, especially if you’re into AI that sort of thing. It’s a rather tastefully designed book: Planning Algorithms (Cambridge University Press) by Steven M. LaValle 👻
5. Ships Laden With (Docker) Containers 🚢
Wait a second, what in the world is that container-laden ship doing here? Docker containers anyone? Anyone?! (Just sayin’, just sayin’ because I’d rather stay rooted in the physical realization of building systems versus some ivory tower stuff, and I’m not even talking about Eiffel the tower or yo, for that matter, Eiffel the programming language!) 🗼
But I digress ⛷
6. The Crimson-braided Book 📕
I love this book, tastefully crimson-braided, standing upright, bolstered at the back by the same book (Planning Algorithms from the Cambridge University Press) that we ran into earlier, of course: Patterns, Principles, and Practices of Domain-Driven Design by Scott Millett and Nick Tune is in a league of its own when it comes to imparting the wisdom in the DDD territory.
This is one of those rare, stellar software books where it’s evident that great care and attention was lavished in preparing it. Profusely illustrated, clearly articulated, replete with marvelous end-of-chapter summaries, this book is a keeper. I’m a Go/Java/Scala programmer, and have been working in the Big Data area for a while, and would have preferred the code examples to be in either of these languages. But I must confess that the C# code is pristine enough in its quality that it it’s easy to follow along ⛵
The content and crystal-clear presentation is abundantly evident throughout, though I feel compelled to point out two stand-out chapters that are not to be missed:
- Chapter 21: Repositories — Repositories mediate between the domain model and the underlying data model. They ensure that the domain model is kept separate from any infrastructure concerns.
- Chapter 24: CQRS: An Architecture of a Bounded Context — CQRS is a design pattern that creates two models where there once was one. Instead of a single model to handle the two different contexts of reads and writes, two explicit models are created to handle commands or serve queries for reports.
All-in-all, a terrific and delightful book, which is why I think of it as one of the two definitive DDD books, the other one being, of course, the seminal volume by Eric Evans himself (the classic book entitled Domain-Driven Design: Tackling Complexity in the Heart of Software)! 💘
7. Representations Are Ubiquitous. And Yes, Representations Do Matter 🎭
OK, Akram, isn’t it about time that you stopped rambling—we know all too well that you are a sucker for (great) books and stuff—and instead gave us the scoop on the guts of DDD for crying out loud? So it’s Akram here, saying merely this much in my defense that the deal goes like this: While DDD is not going to solve weighty issues which humanity faces—the mosaic in the picture below with love and harmony and peace suffused all over is an ideal to which we should all strive nonetheless—anytime soon, it’s only fair to mention that the way it (DDD) entered my lexicon will necessarily have us take a trip back to the time. That’s when I was working as a senior software engineer for Boston Scientific (not in Boston, mind you, but in the good old Twin Cities in my beloved Minnesota) and I noticed a copy of Evans’ groundbreaking book sitting on the desk of one of my coworkers… 📚
My (now-erstwhile) coworker began talking about this thing called a Ubiquitous Language and stuff like that. It made some sense at that time, and I actually headed over to the local Barnes & Noble that afternoon and got myself a copy of the book; the booksellers there, of course, all knew me by first name, and on seeing me enter the bookstore, realized full well that I must have found yet another excuse for buying yet another book (But they weren’t complaining, at least as best as I could tell.)
The bottom line is this: Representation does matter—Would you rather work with concise JSON-encoded representations of data or with their far more verbose kin, those XML-encoded representations? Would you rather do arithmetic using the lean and efficient Arabic numerals or their laborious kin, the Roman numerals? Yep, I thought you would agree 🌂
8. Fast-forwarding By 10 Years 🚂
That was 10 years ago. Let’s fast-forward to 2018—and one more time recycling a pic that appeared above moment ago—and you have the best book published on the subject of DDD: Patterns, Principles, and Practices of Domain-Driven Design by Scott Millett and Nick Tune can serve as a model for the best that there is in the presentation of technical material! 🏰
9. Principled Design Must Be Informed By A Ubiquitous Language 🙋
Ah yes, so I was going to give you the lowdown on the essence of DDD. It’s a mindset of principled design which expects of us—the technology types—to level with the domain experts and treat them as equal partners in an approach to the design and crafting of software that is informed by a shared language (Yep, you guessed it: We’re talking about the Ubiquitous Language here!) 👍
To take the bird’s eye view, we—collectively the domain experts (the SMEs) and the technology types—should remove the artificially-erected barriers in our communication and instead work hand-in-hand to accomplish more in less time 👐
10. Oh, The Fun We’re Going To Have! 👧
Oh my, and and I would tell you about the fun we’re going to have along the way! Pure, unadulterated joy is not far off. Not far at all, in fact, provided that we jettison off the arcane approaches of yesteryear… 🚛
11. Did Someone Say… Refactor? 🎯
Wait, did somebody say something about refactoring those lumbering engines like those which appear in the pic below? Oh my, I’d rather stick to refactoring my code, with the help, of course, of DDD tactics and strategies. After all, DDD is squarely about brainstorming that’s informed all the while by collaborative learning 🎪
Actually, I’m going to take one step back—from my mention above of refactoring code—and talk some about refactoring design itself. I mean, are you able to sit down with paper and pencil (or stand in front of a whiteboard for that matter) and come up with a useful model right away? If you can, then you’re likely in the same league as Leonardo da Vinci, and I ceremoniously—insert one drum-roll here—refer you to the following two essays:
Meanwhile, for us mere mortals, as we grapple with initial design models in the quest to refactor and evolve those models, it would serve us well if only we appreciated more that the model and the language (used to describe any given model) are not static entities; if not attended to properly, the the model and the language can easily devolve into a Big Ball Of Mud. Hey, nobody wants that! 🐐
So the lesson to draw here is: As software practitioners, not only should we tend to mercilessly refactoring our code, we should pay at least as much attention—if not more—to refactoring our software design.
12. Then There Was The Repository 🎁
Speaking of DDD tactics and strategies, allow me to introduce another DDD concept—a centrally important one at that—which deals with the notion of a Repository. See those steely-faced gents carved into Mount Rushmore as in the picture below? There you go. And look, I’m not trying to be cute here: Evan’s himself—in the picture which adorns the beginning of the central chapter dealing with Repositories—presents the image of a steely faced librarian zealously guarding a bookshelf worth of books 💂
Crucially, he notes:
The goal of domain-driven design is to create better software by focusing on a model of the domain rather than the technology. By the time a developer has constructed an SQL query, passed it to a query service in the infrastructure layer, obtained a result set of table rows, pulled the necessary information out, and passed it to a constructor or FACTORY, the model focus is gone. It becomes natural to think of the objects as containers for the data that the queries provide, and the whole design shifts toward a data-processing style. The details of the technology vary, but the problem remains that the client is dealing with technology, rather than model concepts.
~ Eric Evans (in Domain-Driven Design: Tackling Complexity in the Heart of Software — Addison-Wesley)
To cut a long story short—woohoo, no digressions for a change—pay special attention to the crucial role that repositories play in the practice of DDD 👀
13. I Want To Fly Like An Eagle (Or, Failing That, Like A Seagull) 🐬
Once you got that down—plus a few salient concepts such as Bounded Context, Domain Event, and Aggregate— you will surely feel the unbearable lightness of unencumbered, yet disciplined, design. Indeed, you are bound to identify with the seagull soaring above the ocean waves as in the picture below 🌊
I want to fly like an eagle
To the sea
Fly like an eagle
Let my spirit carry me
I want to fly like an eagle
Till I’m free
Fly through the revolution
~ The Steve Miller Band (Lyrics from Fly Like An Eagle)
Into the future
Time keeps on slippin’, slippin’, slippin’
Into the future
~ Also by The Steve Miller Band (Lyrics from Fly Like An Eagle)
All good? Ready to proceed and meet even more interesting characters in our meandering DDD journey? 🎡
14. Of Meandering Neanderthals 🗿
Hoh, hoh, hoh, did somebody just say something about “…meandering journeys”? Okay, this is a bit too much to resist, and I simply can’t bring myself to close out this essay without sharing some wisdom—something that could demonstrably have been garnered only by someone deep into the cavernous and meandering landscape of distributed software systems design—which is, oddly enough, by way of a riddle that spontaneously arose in my mind during the past 24 hours. It goes like this 🙊
Question: What do you call a Neanderthal who is prone to meandering?
Answer: A Meanderthal, but of course!
So there. Now you tell me if the connection (Nexus?) of this parable-laden wisdom to the meandering landscape of distributed software systems design isn’t as clear as the day? Yes, yes?! 💤
Whoa, is that a Meanderthal—tastefully attired in that oh-so demure costume or something—in the pic below or what? I mean, wow, for one thing, it’s sure got a bevy of enthralled kids for its audience! 👧 👦
15. Lightsaber-wielding Goslings Sure Can Derail The Practice Of DDD 🔨
But no sooner had we soothed our nerves than we took a few steps in the star-board direction and came across a fierce creature as in the picture below! Exactly, didn’t I tell you? Here be monsters!! All that this gosling—and no, it’s not related in any way to mild-mannered James Gosling, the original and primary designer of the Java programming language—is missing is a Jedi lightsaber, and we are out of here, like, pronto! 🔪
Look, here’s the deal: To practice DDD with any level of focus, we need uninterrupted quanta of concentration. We’d rather not be dealing with Jedi lightsaber-wielding goslings if we are to get anywhere with designing software that is going to power the new era that is dawning… 🌞
16. Our Ships Sail Into The Harbor 🚣
Finally, we witness how the ships have sailed onto the shore, or at least some boats have! See those trawlers and fishermen hauling in their nets after a hard day’s work of the disciplined practice of DDD? Yep, it’s Entities and Aggregates all the way down…
Dare I say that our friends the turtles may wish to have a word or two with us in this regard… 🐢
17. Bright, Colorful Designs ⛄
Last, but certainly not least, you may find yourself perking up at the site of the motley crew, ragtag band of mailboxes lining a lazy street…
Honestly, answer me this: If people would only get a little creative in choosing colors for their mailboxes, wouldn’t life itself become all that more colorful? 📪 📫 📬 📭 📮
18. Let’s Not Forget About CQRS! 🐘
Don’t you forget about me
Don’t, don’t, don’t, don’t…
Don’t you forget about me
~ Simple Minds (Lyrics from Don’t You (Forget About Me))
As we wind down this essay, it behooves us to remain mindful of yet another player in the DDD solution space: CQRS (Command Query Responsibility Segregation). I strongly encourage you to check out the marvelous narrative on CQRS—truly one of the standout sections—in the remarkable book named Patterns, Principles, and Practices of Domain-Driven Design (Wrox Publishers, by Scott Millett and Nick Tune) 🚀
In particular, they introduce the reader to the notion of CQRS without any fuss by elegantly clarifying that CQRS
…is a simple pattern that you can apply to a bounded context. It separates the domain model into two models: a read model and a write model (sometimes called a transactional model).
The reason for the separation is to enable a model to serve the needs of a single context without compromise. The two contexts in question are reporting on the state of the domain and performing business tasks, also known as the read and write sides. Using a single model for bounded contexts that have complex presentation needs and rich domain logic often results in that model becoming overly complex and devoid of integrity, generating confusion for domain experts and a maintenance nightmare for developers. By applying the CQRS pattern, a model is split in two, enabling each model to be optimized to serve each context more effectively.
If you are anything at all like me, you’re probably eager to fire up your favorite IDE—doesn’t matter which though for me it would be IntelliJ IDEA—and bang out some code to put this CQRS thingamajig into action! YMMV, but when we all succeed, all of us here in programming digressions, we may well have on our hands something like this densely packed scenario such as the one in the picture below ⛹
I mean, where do I even begin with the richness of it all: The legion of IoT sensors in that demure house ceaselessly emitting signals, the embedded micro-controllers attached to the handful of eucalyptus trees standing tall nearby (and ready to transmit perhaps their eucalyptus oil-levels in real-time), or perhaps that sharp S-shaped band in the adjacent road where we be driving our Ferraris (feeling safe in the knowledge that intelligent road-signs will communicate to approaching vehicles and alert them to programmatically reduce their speed)? 🚕 🚓 🚗 🚙 🚌 🚛 🚚 🚓 🚒
(Akram, stop being lazy and just find and insert right here a link to the published conference paper or two that were based on your MS dissertation related to autonomously-intelligent vehicles using AI algorithms, including the trusty back-prop!) 👽
19. Aspiring To Sublime Designs 🌹
Hey, no Ferraris for us now; not right away, anyway. Meanwhile, let’s take in the penultimate picture or two below, that of the feathers of peacock. Are you, like me, also thinking to the timeless and inimitably graceful design that is the handiwork of Mother Nature? We—all of us technology types—can only aspire to design software that is a fraction as tasteful and graceful: Truly, the journey itself is the destination 🚥 🚲 🚦
20. Raise Your Hand If You’re Still Awake… 😴
One If By Land, Two If By Sea.
~ Henry W. Longfellow (his eponymous poem, Paul Revere’s Ride)
Hang on, what kind of T-shirt is that, hanging on for dear life, clinging to a clothes hanger—which itself is hanging on for its life to a desultory doorknob in my sanguine study—with the lovely logo of the reactive summit which I attended in Austin not so long ago. But here’s the real deal: See that book, stoutly standing upright—Michael J. Casey’s and Paul Vigna’s fine book entitled The Truth Machine: The Blockchain and the Future of Everything—with my T-shirt in the background? And you may well be asking yourself, muttering under your breath no doubt, “Why has Akram wedged a Blockchain book in the guts of an essay that purportedly on DDD?” I wouldn’t blame you one bit if you did 💼
Then again, I simply have to make sure—so I make unannounced checks using the element of surprise—that my dear readers are still awake. And I kid you not: People have been known to fall asleep smack in the middle of reading my essays, and continue reading while sound asleep (that being the reading analog, of course, of sleepwalking!) 😴
In the remote case that anyone is awake and—even more remotely still—they wish to look up my write-up on Blockchain, I can gleefully point you in the direction: Blockchain Adventures!
21. It’s Now Or Never 🎸
After all has been said and done—here we tacitly acknowledge that a whole lot more has been said than done—we’ve reached the horizon of our journey: We are standing in front of a bridge in the countryside, a bridge that beckons us to venture outside our comfort zone. Tree-lined or not, easy or hard, straight or crooked, we simply have to cross that bridge.
Recall the image of the Tower of Babel which appears to atop this essay: Yes, far too much time has passed, far too many disconnects have taken place in the industry—technologists speaking one language and our counterparts the domain experts speaking another—that we can no longer afford to wring our hands in despair as we ruefully size up the situation in realizing that a lot of water has flowed under the bridge… ⛩
It’s still not too late. But it is imperative that we cross the chasm. To put it in starker terms, it’s now or never.