Skip to main content

Posts

Showing posts with the label Design Patterns

Implementing the decorator pattern using System. Reflection.DispatchProxy

If you are new to the decorator pattern, let me start with a short explanation: Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. A common use case for decorators is to implement Aspect Oriented Programming (AOP) which allows you to implement cross-cutting concerns like logging, caching, … There are multiple ways to implement this pattern, you can manually implement it, use your DI container , use a source generator to write the boilerplate code or use a dynamic proxy that wraps call to the original class. It’s this last approach I want to focus on in this blog post. You could use the great  Castle.DynamicProxy library but for simpler use cases, there is a built-in alternative through the System.Reflection.DispatchProxy class. Let’s have a look at a small code example on how to use this class. First we need to create a Decorator class that ...

Applying the smart constructor pattern in C#

In Domain-Driven Design (DDD), domain invariants are fundamental principles or rules that must always hold true within a specific domain. These invariants define constraints or conditions that govern the behavior and state of the entities, value objects, and aggregates within the domain. They emphasize the Always-valid rule: Your domain model should always be in a valid state. By using invariants, your domain model guarantees that it cannot represent illegal states. These invariants define the domain class: that class is what it is because of them. Therefore, you can’t possibly violate these invariants. If you do so, the domain class would simply cease being the thing you expect it to be; it’d become something else. As Greg Young explains it: A unicorn without a horn is a horse, not a unicorn. There are multiple ways to protect those invariants. Using value objects and taking advantage of the type system are a great help here. However not all invariants can be enf...

Build your UI as a finite state machine

As an architect I’m regularly involved in code reviews. One of the lessons I learned from reviewing so many codebases is that most codebases start quite well-defined and clean. It is only after an accumulating set of changes that the code evolves to a mess and turns into spaghetti. One of the parts of every system that is impacted the most by changes is the user interfaces. What started as a simple set of UI components evolves quite fast to an always growing set of changing conditions that impact the UI state. An example: an original requirement stating that a ‘Save’ button is disabled until all required fields are entered in a form evolves to a combination of AND all required fields are filled in AND a user has a certain role AND there is no application error AND we are not loading some data AND… What typically also starts to happen is that the same conditions start to come back in multiple places. Your UI becomes harder and harder to test and you get more complex bugs that are ...

Applying the decorator pattern in .NET Core using Castle.DynamicProxy

In this post I want to explain what the decorator pattern is, why it is useful and how you can implement it in a generic way using Castle.DynamicProxy. What is the Decorator pattern? Before we dive into the technical details, let us start with a recap about what the decorator pattern actually is: Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors. There are a lot of use cases where the decorator pattern can help, in this blog post I focus on one of them; using a decorator to handle cross cutting concerns(caching, error handling, logging, …) without polluting your original object. I’ll show you an example where I introduce caching at the repository interface level. How to integrate the decorator pattern in a generic way? You don’t need a special library or anything to implement the decorator pattern in C#. However I would like to write it in a gener...

Visug XL 2022 - Microservices The last mile

Last Friday I did a presentation at Visug XL . If you missed my presentation or are interested in the slides, I've made them available for download here . No idea what my talk was about? Here is the abstract: There it is! After months of struggling your well decomposed microservices architecture finally sees the light. Nicely separated services with their own datastore, well defined service boundaries, clear API contracts, … . A software architect dream is coming true. But now you need to start working on the frontend and gone is all your clean separation! In this session we’ll walk the last mile and evaluate multiple ways on how to bring information from multiple (micro) services together so that they can be consumed by the frontend. ViewModel composition, gateway aggregation, Backend for Frontends, GraphQL Federation and other options are compared and pro’s and con’s of each technique will be discussed.  

Tips from NDC Oslo 2019 - Polly.NET policy wrapping

I do like Polly.NET , the “resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner”(quoted from the website ). One of the nice things you can do in Polly is combining multiple policies to achieve more complex functionality: This works but requires some ugly nesting. A better approach I learned at NDC was through PolicyWrap: More information here: https://github.com/App-vNext/Polly/wiki/PolicyWrap

Cloud Design Patterns infographic

I shared some great resources regarding Cloud related design patterns before: Free e-book: Cloud Design Patterns: Prescriptive Architecture Guidance for Cloud Applications Video: Cloud Scalability Patterns Here is another one to add to the list: Cloud Design Patterns Infographic : An interactive infographic that depicts common problems in designing cloud-hosted applications and shares design patterns to solve them.

DDD Europe 2016–Videos

If you couldn’t be at the first DDD Europe conference, I have good news. The videos are online so you can see for yourself what you had to miss… And even beter news, a second edition is announced for 2017 in Amsterdam: http://dddeurope.com/2017/

A language for Architecture by JD Meier

Last week I stumbled over the following blog post in my news feed; “A Language for Architecture” by JD Meier . This post is redelivery of an old article that JD Meier wrote for the Architecture Journal. It brought back some old memories… Anyway, although the categories described are rather outdated, I do still believe that the approach that JD Meier describes is good starting point to help you think about  your architecture. “Building software applications involves a lot of important decisions. By organizing these decisions as a language and a set of mental models, we can simplify organizing and sharing information. By mapping out the architecture space, we can organize and share knowledge more effectively. By using this map as a backdrop, we can also overlay principles, patterns, technologies, and key solutions assets in meaningful and relevant ways. Rather than a sea of information, we can quickly browse hot spots for relevant solutions.” Go read it: https://blogs.m...

CQRS+Event Sourcing Blog series

As I’m working on a project where are using Event Sourcing, I try to read all material I can find about the topic. One great resource is the blog series by William Verdolini about CQRS + Event Sourcing. An overview of the content: Intro CQRS+ES Architecture Inversion of Control 3.1 Command Handling via DI 3.2 Service Locator 3.3 Typed Factory 4. Workers Validation Logic Set Validation Have I understood? Some concerns Event Store NEventStore Aggregate Snapshots Identity Mapping Legacy Migration Event Upconversion Async matters UI Notification with SignalR OWIN + SignalR + Castle.Windsor NEventStore PollingClient Don’t forget to have a look at the associated code as well: https://github.com/williamverdolini/CQRS-ES-Todos/

NEventStore PollingClient does nothing

For my next project we’ll use Event Sourcing. Therefore I’m spending some free time in looking at NEventStore , a persistence agnostic Event Store for .NET. One of the features of NEventStore is a built-in PollingClient allowing you to poll the Event Store for the latest commits. However when I tried to test the PollingClient nothing happened?! Here is the code I was using: No exception was thrown, however when I browsed through the Output window in Visual Studio I noticed the following message: A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in NEventStore.dll It seems that the PollingClient immediatelly tries to deserialize the committed events, as I didn’t include a reference to the assembly containing the Events, the deserializer (silently) fails. To fix it, the only thing I had to do was adding a reference to my Events assembly.

Angular 1.5 - Stateless components

Angular 1.5 brings us ‘Components’, a special kind of directive that uses a simpler configuration. It is a first step towards Angular 2.0 where directives and controllers no longer exist and are replaced by a component-based model. Advantages and disadvantages of components From the Angular documentation : Advantages of Components: simpler configuration than plain directives promote sane defaults and best practices optimized for component-based architecture writing component directives will make it easier to upgrade to Angular 2 When not to use Components: for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable when you need advanced directive definition options like priority, terminal, multi-element when you want a directive that is triggered by an attribute or CSS class, rather than an element Most important to remember is that components ha...

Arc42–Resources for software architects

As an architect, part of my job, lies in design, communication and documentation. Documents, (UML)diagrams and white board pictures(my favorite !) are necessary parts of defining and describing a system & application architecture. Last week I heard a podcast where they were talking about arc42, a template for documenting of software architectures: Here is a sample of documentation created with it: https://rawgit.com/aim42/htmlSanityCheck/master/build/html5/hsc_arc42.html More information: http://arc42.org/ https://github.com/arc42 http://arc42.github.io/

Avoid the use of task.Result

With the introduction of async/await, asynchronous programming in .NET  becomes a breeze. However with great power, comes great responsability. I see a lot of programmers starting enthousiastic with the Task Parallel Library and the async/await syntax but a few days later, they start to report strange bugs and issues with their code(or even worse the end-user start to report this). Almost all the time it is because developers didn’t fully understand what’s going on behind the scenes and when we dig into the code, there is almost all the time the following code(or similar): var httpClient = new HttpClient(); var t = httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead); return t.ContinueWith(t1 => t1. Result .Content.Headers.ToString()); If you use the code above in a Console application, it should not be a problem. However if you try to do the same thing inside an ASP.NET(MVC) application you’re into trouble...

Domain Driven Design in 15 minutes

Domain Driven Design is new to you? Or you have heared about it and want to learn more? And you don’t have much time? The guys from DZone created a new DZone RefCard about Domain Driven Design. In one big article they walk through the main concepts. Just enough to get you excited !

Entity Framework Async: The source IQueryable doesn't implement IDbAsyncEnumerable<>

While investigating an Entity Framework issue, I stumbled over the following exception The source IQueryable doesn't implement IDbAsyncEnumerable<VLM.PlattelandsLoket.Domain.Views.Codes.CodeValueView>. Only sources that implement IDbAsyncEnumerable can be used for Entity Framework asynchronous operations. For more details see http://go.microsoft.com/fwlink/?LinkId=287068 . What’s causing this error? Entity Framework 6 introduced async support through a set of extension methods. These extension methods are defined on IQueryable and IEnumerable but actually expect an IDbAsyncEnumerable implementation behind the scenes  to work. When you try to use one of these extension methods on a LINQ query that isn’t an Entity Framework query, you end up with the error message above. I have to say I’m not a big fan of this approach, it sounds like a ‘leaky abstraction’ to me. What do you think? Code smell or not?

If you have too many dependencies it’s time for something else

I’m a big fan of the Inversion of Control(IoC) pattern and how Dependency Injection(DI) frameworks can help you implement this pattern.  IoC was really a gamechanger to me and had a lot of impact on the way I build and architect my applications. Note: As I’m doing more and more functional programming, the need to use a DI framework is going away, but that’s something to discuss in another blog post Unfortunately something I see a lot in applications that use a DI framework is something I call “dependencies diarrhoea”. Let’s have a look at an example ASP.NET MVC controller to illustrate the problem: So what’s the problem here? Without even looking at the full implementation, it should be clear that this class is violating the ‘Single Responsibility Principle’ and is doing too much in one class. This not only makes it harder to reason about this class, but also makes it a lot harder to test. There is no fun in mocking out lots of dependencies just to test a small piece ...

Akka.NET–Cheat sheet

As a newbie in Akka.NET , all help is welcome. So I’m glad that Jason Roberts took the time to create a 3 page cheat sheet PDF as a quick reference guide. Thanks Jason!

Generating unique identifiers across a set of server nodes

Distributed systems come with their own set of problems. One of these problems is the generation of unique identifiers across multiple nodes. You can rely on the database to generate a sequential guid, but this hinders scalability and makes your systems error-prone. While browsing through the MassTransit code base, I noticed they were using a separate NuGet package called NewId . NewId is a unique id generator with 2 important characteristics: Unique Id generation at a specific server can happen without interaction with other servers Id’s should be ordered(important for database optimization) It’s inspired by (the retired) Twitter Snowflake and Boundary Flake implementations. Certainly useful if you need to build scalable solutions…

CQRS Sample Application

CQRS is a really useful pattern, but it’s hard to find good examples out there. Jimmy Bogard took the time to rewrite the Microsoft Contoso University Sample app using a CQRS approach. Although not complex enough to show you the full power of CQRS, it gives you a good insight in the mechanics involved. Certainly worth checking out…