Never Return Null Again

null is probably the worst mistake in programming languages history and has spread in all modern languages since its invention in 1965. Many years later, Tony Hoare, the inventor of the null reference, even apologies for his mistake:

I call it my billion-dollar mistake. … My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. …

Image for post
Image for post

Aggregates are the heart of your system. They hold domain logic and are responsible for emitting events that will
eventually make your data consistent across multiples data projections and bounded contexts. Because aggregates are so
important, it is crucial to keep them small and easy to understand, but how to do this when the domain gets bigger and

In this article, I will show you a way to reduce complexity from your aggregates and make them scale better.

Write-side domain overview

Before getting started, let review how commands are executed and turned into events.

After receiving the command sent by the user, the command handler invokes the repository to load the aggregate state in memory. Then, the command is executed on the aggregate which emits either domain events or failures. Finally, those events or failures are persisted using the repository. …

Image for post
Image for post

What is a guard clause?

A guard clause is a technique derived from the fail-fast method whose purpose is to validate a condition and immediately stop the code execution if the condition is not met by throwing a meaningful error instead of leaving the program to throw a deeper and less meaningful error. Let me show you an example:

In the previous example, the if block act as a guard clause by protecting the GetUser method against any null userName arguments. Like that, we are free to write the rest of the method without having to worry about checking if userName is null.

Why using guard clauses?

Guard clauses simplify code by removing useless nested branching conditions, by returning meaningful errors. …


Maxime Gélinas

Senior software developer, independent consultant and blogger

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store