On of the defining characteristics of an Entity is that it has identity. From the Blue Book:
“Some objects are not defined primarily by their attributes. They represent a thread of identity that runs through time and often across distinct representations… An object defined primarily by its identity is called an ENTITY” (Evans, 91)
There are different ways of representing identity. In our CRUD world, we might use a Guid
or an int
that’s stored as a primary key in a SQL table. In DDD implementations, you might see a different pattern - using Value Objects as identifiers for Entities. What’s the point in doing that?
more...
This is just a post to let any of my RSS feed readers know about my new book: Event Sourcing and CQRS with .NET Core and SQL Server.
I’ll be sharing a lot more info via my mailing list including discount codes and launch dates, so make sure you sign up below so you don’t miss out!
more...
How should events be applied to child Entities when the Aggregate Root ultimately handles incoming commands? For example, constructing an Entity that is within the Aggregate Root boundary. Where do you call the constructor so that the constructor obeys the invariants being protected by the Entity?
more...
What’s the harm in putting Value Objects in your Events? Say we have the following event:
public class PlannedNewRoastDay : Message
{
public readonly Guid Id;
public readonly string RoastDate;
public PlannedNewRoastDay(Guid id, string roastDate)
{
Id = id;
RoastDate = roastDate;
}
}
more...
The purpose and implementation of EventStorming doesn’t only exist inside of Domain-Driven Design. Although the name “EventStorming” does tie itself to DDD, it has foundations in process improvement that have nothing to do with DDD and these are not new.
Parallels with business process improvement and LEAN
One technique that I’ve personally seen is business process improvement exercises used in Manufacturing to discover bottlenecks. Here, the same issue applies - Domain Experts aren’t fully aware of the bottlenecks outside of their processes. They live in a silo. While one process works well in their division - say the Accounting Department, the interaction with their division that includes this process is potentially a bottleneck for an outside division, like Sales.
more...
If you need a hand with your project, I am available to provide some assistance with various parts of your .NET projects.
more...
Take the following use case:
- I have an Employee aggregate
- I want to create a new Employee
- I wrote
Employee.Create(...)
…but Aggregates don’t create themselves (Don’t Create Aggregate Roots), especially when it’s a clear use case where someone like an Admin is responsible for creating new Employees.
We’re suppose to create a factory for situations like this. This way, the factory can ensure invariants are enforced on the creation of the Aggregate, just like the Aggregate enforces invariants on any other state changes.
But, when I created a static factory Employee.Create(...)
and intend for Employee to be an Event Sourced Aggregate, when/where/how do I send my EmployeeCreated
event so that it gets saved to the Event Store?
more...
Have you ever been met with deaf ears when you tell your team there are benefits to thinking about architecture differently? What about when you bring up buzzwords like “Event Sourcing” or “Domain-Driven…”?
I have, which is why I write about it…
more...
I have an Order that can be split into multiple Shipments. A Customer orders Quantity X of Product Y, represented as a single OrderLine with Quantity = X. In order to optimize shipping costs, Quantity X of Product Y is split into Z number of Shipments….
more...
A while back I was looking for an example of a Process Manager written in C# with a decent commentary on what they’re all about. Unfortunately, I couldn’t find what I was looking for.
more...
This post will conclude our story of a Vertical Slice of an application build to help First Pop Coffee Company be more successful with its Roast Planning. We are far from finished, as I know that the pain in actually implementing these architectural principles is stronger than I can describe with a single Bounded Context.
more...
We’ve covered how we get data into our Read Model via our special Read Model Projections that use Entity Framework to insert View Model objects into a read-optimized SQL Server table. The table stores View Model objects in it, reducing the impedence mismatch we would run into if we didn’t have a separate Read Model. But how do we actually use the Read Model SQL Server?
more...
I said that our Read Model Projections are special kinds of Event Handlers that are registered to the Bus. What makes them unique? Their role is to simply update the Read Model persistence mechanism. This persistence mechanism is optimized for Reads. It might be a denormalized SQL Server table, Redis, OLAP Cube, Neo4J, etc.
more...
So far, we’ve covered developing a Write Model for our Roast Planning Bounded Context for First Pop Coffee Company. We’ve also talked about how the Bus acts as a “spinal cord” for messages being passed throughout this Bounded Context. The Bus transports Commands and Events to Handlers that know what to do with them.
We spent the last post talking about how we publish Events through the Bus to one or more Event Handlers. Events are our primary mechanism for achieving consistency outside of consistency boundaries. In a scenario where we’ve chosen to apply CQRS, they are how we make our Read Model consistent with our Write Model… eventually.
more...
When an Aggregate Root publishes an Event, what do we do with it? Looking back at why Domain Events are so important - they are how we achieve consistency with parties that are outside of transactional consistency boundaries.
more...
Before we cover Event publishing from the Bus, let’s write a test to make sure the Send<T>(T command)
method does what it should, i.e. allow us to send a Command into the Bus to have the appropriate Command Handlers call their Handle
methods with the Command as parameter.
more...
Last time, we set the stage for composing the Bus so that we can tell Messages where to go when we emit them. We saw how Greg Young built the FakeBus
class with a Message Routing component that’s basically a map of where a Message type (Command or Event) should be routed to which Handlers.
more...
We’ve been working in the area just outside of our Domain Model in terms of building Command Handlers and coordinating activities on the Domain in these Command Handlers. How do Commands make it to our Command Handlers? What if multiple parties are interested in an Aggregate’s state change Event? How does the Read Model find out about Events that are happening in our Write Model?
more...
Saving Aggregate state is fun and all, but we can’t ONLY do that. There’s that one important piece of our Use Case(s) that we are forgetting… Nick actually using the app. Nick needs to make decisions based on the state of the Aggregates in the system. Remember Brandolini’s “Picture that Explains Everything”…
more...
In the last post, we started to write tests in a way that would result in a readable specification. Borrowing from Greg Young and Mark Nijhof, we created a base class called Specification
that allows us to test our Event Sourced Aggregate Roots in a Given-When-Then format.
more...
I’ve mentioned tests twice now and not acted on them yet… Since we now have enough infrastructure in place to attempt to exercise a “Slice” down through our Write Model, let’s give it a try.
Let’s look back at our EventStormed “Start Creating Roast Schedule” Command:
more...
We are going to use Greg Young’s In-Memory Event Store from his SimpleCQRS project to demonstrate persisting an Event Sourced Aggregate. I’ll talk more about other Event Stores in future blog posts. Here are a few:
more...
We know that the creation of a RoastSchedule
Aggregate means persisting it. This is where the Repository pattern comes into play. Since we are going to use Event Sourcing, our concrete RoastSchedule
Repository will look slightly different from the traditional Collection-Oriented and Persistence-Oriented Repositories discussed by Vaughn Vernon in Implementing Domain-Driven Design. Our generic Repository Interface will, however, look very similar to a Persistence-Oriented Repository in that it requires a call to Save()
to actually push objects down to storage.
more...
The key responsibility of the Application Service is to orchestrate the activities that can be performed with the Domain Model. It is common that a single Application Service is defined for a single Use Case (Greg Young).
more...
So after completing either one extensive Design Level EventStorming session, or multiple small sessions applied to each Bounded Context, the Team feels ready to implement a working prototype of the the Domain Model to show to Nick and get feedback on their attempt to codify the Ubiquitous Language that they have learned together.
more...
Now that the team has looked closer at the Bounded Contexts, it’s time to initiate a Design Level EventStorming session so the team can start writing code.
We’re going to look at a single Bounded Context that they determined as a candidate for deep investigation and Domain Modeling from the analysis above.
They decide to go right for the Core - Roast Planning. As Nick said before, this is Core for his business. He wants to be able to plan his roast schedule and make the roasted coffee from his plan the only product available for customers to buy. The Team decides to do an initial Design Level EventStorming Session for this Bounded Context.
more...
The Team goes back and asks Nick (*and themselves) what the Complexity/Cost is associated with implementing a custom, automated system around a Bounded Context…
more...
The value of EventStorming is the active engagement that you achieve with the Domain Experts. In this case Nick and the Team are actively engaged in learning as much as they can, as quickly as possible about Nick’s Domain: A Roast-to-Order Coffee Business.
But what do we do with this Artifact after we’re done with getting the Big Picture of the Domain? How is this progressing towards the Team writing code and developing a prototype? This is where Nick and the Team have another EventStorming Session known as the Design Level EventStorming.
more...
Nick and the Team have put up enough Domain Events on the Big Picture Surface to start thinking about the Commands that cause these Events. As you might expect, having sufficient space is going to be important since many of the Events are triggered by some type of Command (some by other Events).
Here is a legend representing the additional stickies going up on the surface:
As a starting point reference, here’s what the Surface looks like.
more...
As Nick and the Team continue, they discover that within the two Bounded Contexts that have emerged through the exercise - there are various concepts of Inventory. A purple stickie goes up: “What are the different kinds of ‘Inventory’ we are dealing with?”
more...
Once Nick describes the important Domain Events that he envisions for managing his own Inventory and Roast Schedule concepts, we start to focus on the Customer Experience of buying roasted coffee from him.
Nick and the Team imagine the Roast Schedule as a centerpiece of the site; the first thing that the Existing Customer/Potential Customer sees when they access firstpopcoffee.com.
more...
The Team helping Nick get his website going begins with an EventStorming session. This is so that both the software Team and Nick can get their heads wrapped around the Core Domain and make sure they are writing the right code. It’s essential that Nick uses 3rd party for the code the Team shouldn’t be writing because he has a limited budget.
more...
The Domain First Pop Coffee Company is a business specializing in roast-to-order coffee. Roast-to-order, in this case, means that the company has scheduled roast days where he roasts a set number of lbs of coffee based solely on the supply and the amount that he can roast in that single roast session. He doesn’t have the resources to roast and sell large quantities of roasted coffee beans, but he wants to grow and scale as demand increases.
more...
You ever take over a codebase where the previous developer liked to ignore exceptions? You ever have to track down a production issue while the useful stack traces from those swallowed exceptions disappeared into the abyss?…
more...
When it’s time to start writing code to implement your Domain Model that you’ve so carefully collaborated with the Domain Experts on, you might find yourself asking questions about communication.
- “How do I communicate between Bounded Contexts?”
- “How do I let Aggregate A know about changes to Aggregate B?”
- “What information belongs in this Event so Bounded Context A can know enough about Aggregate C in Bounded Context E to do X?“
Valid questions, no doubt. Ones you would expect to answer with a very clear, technical solution. However, ask other DDD experts and you’ll probably get answers around one theme…
more...
Learning Domain-Driven Design is a tough and rewarding adventure…
You only have so much time and money to dedicate to reading a 500+ book on Domain-Driven Design. The decision of where to start your learning commitment can be paralyzing.
more...
Has bad architecture forced your team to write smelly code? There are plenty of symptoms:
- global state everywhere…
- flow of data completely non-obvious…
- parameters to methods constantly mutated…
- super, super fragile code…
- methods being overloaded several times…
- huge, 8000-line classes…
- etc.
But are these symptoms just the devolution caused by poor up-front modeling decisions made 5+ years ago? I’ve talked about these symptoms, but I haven’t talked a lot about their root causes. Is it really anyone’s actual fault, or is it natural?
more...
Are you somewhere that doesn’t promote good coding practices like code reviews, unit testing, pair programming, etc…? Do you know someone who is? The result is situations like the ones I’ve posted about recently - shitty legacy code, 500 line methods with 20 parameters, and no way to wrap your head around it.
more...
…I don’t really know how the system works… what do I do?!
Yup, I’ve been there too. My last couple posts talked about how much it sucks to be working with code that sucks. But what if you don’t really mind working with code that sucks, you just feel like you suck at working with it? Worse yet, you actually suck at working with it?
more...
We know spaghetti code is bad. We teach ourselves how to avoid writing it. But of course, there’s that gravitational force that pulls it from orbit and sends it falling into our laps…
more...
I didn’t think so… me neither.
”…nope, I’ve got a legacy codebase with nothing but 700-line methods, inconsistent formatting, raw code duplication, no comments, no documentation, hundreds of stored procedures, and no tests…“
more...
I don’t have to tell you that every project is different. Should you test setters and getters? What about a method that writes to a file? Do you test methods that call other methods if those methods are already tested? What do you do about exceptions? There’s no point in testing if you’re testing incorrectly… right?
more...
Legacy code and integrations can seem black box when you see them for the first time. You’re expected to get familiar quickly. No matter how much time you’re given to get familiar with your new project, you could always use more time.
more...
Just getting started with automated unit testing? Study all you want, but you’ll eventually walk into a code situation that you weren’t well-prepared for.
For example, you inherit some nasty code and your boss wants you to cover 50% of it with tests. You know code smells create test smells and you’re worried…
more...
Do you like spending time in the debugger? Personally, I don’t. A lot has to happen to see debugger information, therefore it loads slowly. There are ways to make the debugger faster, but there’s another reason why I don’t like it. Its information is ephemeral. It doesn’t last forever. It is available when I hit the breakpoint and then disappears when I hit “continue”.
more...
You’re just getting into Domain Driven Design (DDD), Command Query Responsibility Separation (CQRS), and Event Sourcing (ES) and most of the overall principles are clear… but as soon as you start using them in your own domain - everything becomes a decision-making nightmare…
more...
Every once in a while, a seemingly simple coding problem can throw a chicken-or-egg situation at you. You’ve built complex software in mere hours, how can a for
loop throw you off like this…!?!?
more...
There are some crazy questions out there to test your knowledge of CS theory that can leave you stumped. It could come from an interviewer who is trying to weed out hobbyists or a student that you’re mentoring who has a tough professor.
more...
Delegates… being a developer/engineer/tinkerer, you naturally want to “get” them. You may kind of get them, but not feel like you can explain them to someone else.
One reason is the practicality of delegates isn’t always clear. Why couldn’t you just directly call a method on an object instead of using a delegate?
more...
When you’re just getting into testing and your app has a lot of time-dependent logic - you might feel like you’ve picked the wrong app to start testing with.
more...
Sometimes a public JSON API responds in a format that you can’t control. For example, nested objects instead of an array:
{
"companies": {
"abc" : "Abc Company",
"def" : "Def Company"
}
}
more...
Welcome back to Weekly Keyboard Shortcuts with your host, Slowness McMousington.
Ever feel like there’s a productivity boost right at your fingertips and you’re not using it? Ever watch someone puke code onto the page like some kind of Hollywood-hacker? If you’re slow and jealous like me, you want to start building your repertoire of Visual Studio/ReSharper keyboard shortcuts now.
more...
Welcome to the latest in my Weekly Keyboard Shortcut series! Last time, we looked at ReSharper’s Expand/Shrink Selection. This week, we’re going to look at another navigation shortcut.
more...
Have you ever run into a problem that you couldn’t describe well enough to even ask about it?
“I want to change a specific type to another type when I instantiate a class to make it more general and reusable…”
“Is this even possible?“
more...
If you’re new to my Weekly Keyboard Shortcut series - it’s hard to find the time to stop and be aware of what you’re doing in your Visual Studio/ReSharper workflow. It’s actually hard to stop and be aware in a lot of situations, but that’s a whole other topic…
more...
Last week kicked off a regular series I’m doing on keyboard shortcuts.
It’s hard to find the time to uproot your workflow and tweak some piece of it that could be optimized. When you do decide to take some time to focus on how you use tools like Visual Studio and ReSharper, it’s hard to find where to start.
My goal is to try to pick out a single shortcut that you can focus on at a time.
more...
I know there are some really good Visual Studio and ReSharper shortcuts right in front of my face, but I don’t have time to stop and practice them.
Of course, there are huge collections out there like Mad’s Kristensen’s Visual Studio Shortcuts and Jetbrains’ ReSharper Documentation, but again - I don’t have time to pour over these collections to learn a few basic shortcuts.
more...
When you’re just getting started with C#, you can get overwhelmed by the benefits and drawbacks of the different ORMs and approaches people take.
Say you have a lot of SQL under your belt. Entity Framework Code-First sounds great, but you’re not sure how to get comfortable with it.
You want to start small by reading and writing to an existing database. All you want to do is map a simple model to an existing table.
more...
One reason Erlang is considered a fault-tolerant language is its support for the Actor Model in its standard library…
more...
There must be a simple way to convert one DateTime
to another DateTime
using only a GMT/UTC Offset integer… right?
more...
Indexers are used to simplify access to a collection that is encapsulated in a class you’re designing…
more...
It can be tempting to use try/catch
to check data integrity. This can degrade performance, especially if you’re throwing a lot of exceptions.
more...
Implicit and explicit numeric casts are usually pretty straightforward:
more...
Need to perform a LINQ query with a calculated value that relies on the result of another calculated value?
more...
Sending IQueryable<T>
to higher layers can be a touchy subject…
- “there is nothing more frustrating (or more expensive to maintain) than a data layer leaking up the stack”
- ”…literally no case where EF + Repository that exposes IQueryable makes sense”
- “EF-generated anything should never leave the data layer”
- *“it’s bad for unit testing”*
With CQRS, it is acceptable - and even beneficial to expose IQueryable<T>
within the Query Stack.
more...
Last time, we talked about DTO Assembly as a separate concern from Aggregate persistence. This means we don’t want to return DTOs from Repositories.
Instead, we put dedicated Application Services in our Application Layer to handle requests from the Presentation Layer. We used DTO Assemblers to map our Aggregates to DTOs inside these Application Services.
more...
Imagine you have a nicely designed Domain Layer that uses Repositories to handle getting Domain Entities from your database with an ORM, e.g. Entity Framework, into an MVC view or a Web API controller.
Problem is, the Presentation Layer needs objects of a different shape than your Domain Layer Aggregates.
By different shape, I mean that this layer might need data combined from multiple Aggregates, or only portions of an Aggregate.
more...
You might write a simple void method that takes some arguments, validates those arguments, then makes a call to insert that data into a database.
To unit test the validation step, you might go ahead and mock the database, injecting it into your class with constructor DI of some sort.
more...
If you’re like me, you just do as the .NET FCL (Framework Class Library) documentation tells you and use a using
statement to properly dispose SqlConnection
or FileStream
.
Even though the CLR (Common Language Runtime) has a sophisticated garbage collector, memory leaks can and do happen.
more...
All the features of the .NET CLR (Common Language Runtime) must have some practical use… right? Then what’s the point in the dynamic
primitive type?
more...
You might have a good idea about how you’d implement an architecture that utilizes a service bus with asynchronous messaging, but how do you manage the application once it’s live?
more...
There’s been a lot of mention lately about architecting solutions using Azure Service Bus and other equivalent technologies like RabbitMQ and MSMQ.
It’s easy to see clear benefits and use cases for asynchronous messaging using both queues and topics/subscriptions. But… where do you start? It’d be nice to have a good sample application to see how this type of project is structured that isn’t just two consoles talking to each other.
more...
When unit testing, you may need to compare attribute equality instead of the default reference equality of two object instances. It might not be feasible to manually compare EVERY field with expected values in another object.
more...
Working with Entity Framework Code First takes a lot of the guesswork out of entity relationship modeling in your SQL database. But, if you’re like me, you need to have some awareness of how Entity Framework has designed your database schema.
more...
Sometimes it’s hard to choose which programming fundamental you should start focusing on next. You might feel pressure to gain a firm grasp on OOP principles before moving on to design patterns or unit testing.
Say, however, you have a loose understanding of OOP principles and you want to work on your biggest deficit, which is unit testing. Is it OK to go against the logical progression of learning more advanced OOP topics before unit testing?
more...
Making something “just work” and “good enough” was ok when you were a junior developer. But now that you’re in a more senior role, it’s easy for your mind to freeze when it’s time to sit down and code. You feel like you’re over-thinking your code because you know:
more...
As a high-performing software professional, there may be times in your career where your mind freezes as you try to anticipate every disaster that might happen. It may start to take you longer to deliver your high-quality code.
Younger “rock stars” spit out code while you think/worry about design, maintainability, dependency management, modularity etc. Management seems to only see one thing: speed and your lack of it.
more...
You’ve been given a tight deadline. You just read Domain Driven Design by Eric Evans. *“The business NEEDS to put effort into code quality!”* you say.
more...
“How do I follow best practices when re-architecting my legacy project?”
It’s not uncommon to have a project built with ASP Classic or VB6 lurking around in your enterprise.
more...
Even before I started web development, more experienced devs told me they struggled with not being able to stay current in their field.
more...
You build your project one more time, run your unit tests, run your integration tests, look over your commit log, hold your breath, hover your finger over the mouse button while you do that last mental check, take a deep breath… and click
more...
I’ve been working with a database called Unidata for almost 3 years now. I refer to it as the “O.G. NoSQL” database because it is the oldest NoSQL database that I know of. It’s referred to as a Multi-Valued Database and it became popular when it was released as part of the Pick Operating System
more...
A lot of the impetus for me posting more regularly, moving off of Medium, and trying to focus my content comes from an email course I recently subscribed to by John Sonmez at SimpleProgrammer. I first found out about John through his Pluralsight course The Go Programming Language and, since then, have made sure to listen to his guest interviews on .NET Rocks and JavaScript Jabber. He also has a really good book out called Soft Skills. Also a couple podcasts including Entreprogrammers.
more...
Recap
Part 2 of this series demonstrated the usage of SerilogMetrics with Ninject.Extensions.Interception to make a simple drop-in, AOP-style metric logging interceptor over any (virtual) method in my application. It’s with this interceptor that I want to demonstrate interception via an [Attribute]
rather than traditional Ninject binding syntax.
more...
Recap
Part 1 of this series was me attempting to use Ninject.Extensions.Interception in combination with Serilog to do AOP logging for times when fine-grained logging isn’t necessary across larger vertical slices of my application.
more...
The Problem
I have a project with a lot of places where I want to “cross-cut” the concern of logging into. This is also called “AOP” - Aspect Oriented Programming. AOP claims to “increase modularity by allowing the separation of cross-cutting concerns… by adding additional behavior to existing code (an advice) without modifying the code itself”. By managing dependencies differently, I’ve found myself moving into the anti-pattern of constructor over-injection. Adding an ILogger interface as a new dependency for multiple classes is going to be a burden. This experiment is to see if I can avoid making my constructors too heavy, while broadly covering my code with basic logging.
more...
I first approached this because I thought it was ridiculous how our current mega-Plugins that handle all of our integrations were impossible to debug. I needed a way to separate the logic from the instantiation of the plugins inside of CRM. CRM introduces a ton of constraints as far as being able to code cleanly and take advantage of patterns that make the code maintainable and debuggable.
more...