Cache-Aside Pattern in .NET Core

Introduction

Often the time comes when we need to focus on optimizing the performance of our application. There are many ways to do this and one way is cache some data. In this post I will describe briefly the Cache-Aside Pattern and its simple implementation in .NET Core.

Cache-Aside Pattern

This pattern is very simple and straightforward. When we need specific data, we first try to get it from the cache. If the data is not in the cache, we get it from the source, add it to the cache and return it. Thanks to this, in the next query the data will be get from the cache. When adding to the cache, we need to determine how long the data should be stored in the cache. Below is an algorithm diagram:

First implementation

Implementation of this pattern in .NET Core is just as easy as its theoretical part. Firstly, we need register IMemoryCache interface:

Afterwards, we need add Microsoft.Extensions.Caching.Memory NuGet package.

And that’s all. Assuming that we want to cache basic information about our users, the implementation of the pattern looks as follows:

First of all, we are injecting .NET Core framework IMemoryCache interface implementation. Then in line 18 we check whether the data is in the cache. If it is not in the cache, we get it from the source (i.e. database), add to cache and return.

Code smells

This way of implementation you can find on MSDN site. I could finish this post at this point, but I must admit that there are a few things that I do not like about this code.

First of all, I think the interface IMemoryCache is not abstract enough. It suggests that the data is kept in application memory but the client code should not care where it is stored. Moreover, if we want to keep the cache in the database in the future, the name of this interface will not be correct.

Secondly, client code should not be responsible for logic of the naming cache key. It is Single Responsibility Principle violation. It should only provide data to create this key name.

Lastly, client code should not care about cache expiration. It should be configured in other place – application configuration.

In next section I will show how we can eliminate these 3 code smells.

Improved implementation

The first and most important step is to define a new, more abstract interface: ICacheStore

Then we need to define interface for our cache key classes:

This interface has CacheKey string property which is used during resolving cache key in our MemoryCacheStore implementation:

Finally, we need to configure IoC container to resolve MemoryCacheStore instance as ICacheStore together with expiration configuration taken from application configuration:

This is how new implementation looks like:

After this set up we can finally use this implementation in our client code. For each new object that we want to store in cache we need:

1) Add expiration configuration

2) Class that defines the cache key

Finally, the new client code looks like this:

In the code above we use more abstract ICacheStore interface, don’t care about creation of cache key and expiration configuration. It is more elegant solution and less error-prone.

Summary

In this post I described Cache-Aside Pattern and its primary implementation in .NET Core. I proposed also augmented design to achieve more elegant solution with a small amount of work. Happy caching! 🙂

UPDATE 2019-26-02: I updated my sample codebase so if you would like to see full, working example – check my GitHub repository.

Company, don’t waste your programmers time

Introduction

In this post I would like to raise the subject of wasting programmers time which can be easily saved. What’s more, it is said time is money so we can save both! This post is especially for management people (managers, directors, CTOs) but developers should also think about whether they use their potential one hundred percent.

These days it is very hard to hire good-skilled and experienced programmer because there are few of them (comparing the demand on the market) and they cost a lot. So when the company finally manages to hire a programmer, what he can do to use this valuable resource effectively for the benefit of both sides (win-win rule)?

1. Provide him with the right equipment

There is nothing more annoying than a situation where you can’t honestly carry out your duties not because of you. I will mention only a few examples:
– slow, unstable or even not working internet connection.
– not working, not efficient computer.
– small, old, low resolution monitor.
– broken accessories like mouse, keyboard.

Nowadays, IT equipment compared to people’s earnings is very, very cheap. So one of the best thing company can do is investing in high performance hardware. Programmers need this, especially today when we need a lot of applications which have high requirements (not to mention all containerization and virtualization). I think high performance computer with at least 16GB RAM, 256-500GB SSD, i7 CPU and two FULL HD monitors should be a standard hardware for programmer. Trust me, this investment will return very quickly.

2. Provide him with the right tools

This is another misunderstanding for me. There are a lot of amazing applications which can boost people productivity, so why people do not use them? From ignorance, lack of money, maybe both?

I will give you an example of the best .NET extension tool – Resharper. This is plugin for Visual Studio which makes programming easier and more automatic in some cases. In my opinion it can save from 10% to 20% percent of programming time. At the time when I am writing this post it costs 299 euro (lifetime subscription without upgrades). You know the rate for the programmer’s hour so calculation of ROI I will left up to you. 😉

3. Provide him with the right environment

Does your work environment look like this?
The Ford assembly line in 1913. Source.

Work can be divided into two types: algorithmic and heuristic. An algorithmic work is one that is governed by procedures, schemes, standards and repeatability. You know what you need to do, how and with what. For example: work on the assembly line or the work of a cashier in a supermarket is just algorithmic. At the other end of the spectrum there is a heuristic work, one during which there is no clearly defined path, only you have to experiment, demonstrate your imagination and creativity to come up with a solution to a problem.

It’s not hard to guess what type of work is programming. So why companies try to put their employees in environments in which they are ineffective, for example big open spaces? I think something have gone wrong recently. They want to save on space but this is only illusory saving. People who mainly use their mind during their work need:
– quiet.
– peace.
– enough space at the desk.
– daylight.
– own place.
– coffee machine. 😉

If they don’t have the conditions I mentioned above, they will have a problem with concentration, creativity and effectiveness. Summarizing they will be less productive so work will take them a lot more time.

4. Create a development process

Every programmer should know:
– what are his tasks and what are the priorities.
– for what he is responsible, accountable, what should he consult and what to inform. See RACI matrix.
– what he can do and what can not.
– the Big Picture of current project.

Without well-defined process developers will not know these things (certainly not everything). None of the them should wonder what to do now, who to assign the task to or who to consult. It should be defined clear and understandable workflow.

On the other hand, development process should be automated as much as possible. From the management perspective, you should use project management software and try to eliminate ineffective communication channels like emails. For technical reasons, you should use continuous integration/deployment/delivery practices because machines are much better in repetitive tasks (and they cost less as I mentioned earlier), while people should focus on creative and difficult to automate tasks.

5. Organize only useful meetings

A lot of time can be lost at meetings. Meetings are usually too long, they have too many participants and there are often off-topics that are not related to our work. I am not suggesting abandoning meetings now but organizing them in a thoughtful way, i.e. meeting should:
– have a reason.
– be as short as possible.
– have earlier prepared agenda.
– only have interested participants who will give value to this meeting.
– start and end on time.

So remember, one useless half-hour meeting per day with 4 participants and on Thursday whole man-day is lost. Think about it the next time you organize a meeting.

6. Let the programmer to rest

The one of the famous personal development coach, Stephen Covey, described in his book The 7 Habits of Highly Effective People the formula for effectiveness:

Effectiveness lies in the balance – what I call the P/PC Balance. P stands for production of desired results, the golden eggs. PC stands for production capability, the ability or asset that produces the golden eggs.

From this quote follows: you can produce more either by work more or work better/smarter but you have to keep balance. If person is tired because of constant overtimes his production capability (PC) will be very low as well as his efficiency. So it is better in this situation let him to rest to charge the batteries.

7. Give him opportunity to grow

We can constantly improve our production capability through learning and training. But when programmer can do it? Does it always have to be time out of work?

I think it should not be like this. This industry is growing so fast that if programmer want to be up to date he should train himself AND his efforts should be supported by his company. Supporting can be in different ways: sending to courses, buying books, organizing workshops, giving time to research and develop new things. It should be something, I think it is fair for both parties.

Summary

In conclusion, if you, company, don’t want to waste your programmer’s time at all, you must provide him with good hardware and tools, create appropriate supporting environment and development process and you must take care of his development and rest. Are there a lot of requirements? Of course! 🙂 But you do not have to do it right away, you can do it gradually. This is an investment but changes will be noticed quickly.

Start today, not tomorrow.

10 common broken rules of clean code

Introduction

From time to time I am asked to do code review of an application. I like doing this, because it is always learning experience. I can see how others program, what problems they have and how they solve them. Except that I can see code written in various conditions and by people with different skills and experience. I prepared a list of 10 popular “clean code” broken rules which I often encounter during this code reviews and I would like to share this list with you.

Note: If you don’t know what clean code means, I recommend to read Robert C. Martin Clean Code book.

1. Bad and inconsistent naming

Naming is very often neglected (especially by less experienced developers) but it shouldn’t. Good naming sometimes is difficult but it is needed for a good level of code redability and maintainability.

2. Too much comments

Comments from line 1, 4, 7, 18 are not needed, becasue code speaks for itself. Comment block from lines 14-16 are not needed too, this code should be removed – our source control will remember everything:).

Comments are needed only in two cases:
– commenting public API.
– when programmer uses some kind of hack and there is no other way to explain this.

In other cases comments are unnecessary and should be avoided. You should use refactor technique called Extract Method instead.

3. Duplication

The same code occurring more than once. If it is not intended, it should be refactored by moving that code to separate class and/or method. See Don’t Repeat Yourself (DRY) principle.

4. Sloppy formatting

Similar to bad naming. It doesn’t affect execution of our code but it affects readability. Some people will say that is minor issue but I will say it is not. What do you think about book which is not formatted good? What do you think about author and editor of this book? In programming we should have the same rules because we are professionals, aren’t we?

5. Too big classes/methods

Classes and methods should be as small as possible. They should have “only one reason to change” as Single Responsibility Principle says. Common code smells are:
– too much lines of codes
– too many dependencies (constructors/methods parameters)
– code in class concerning different entities, use cases.

6. Bad exceptions handling

We should always catch the most specific exception ( DivideByZeroException for example above). Moreover, we should be careful when we try rethrow given exception, because we can lost whole stack trace information. Below corrected code:

7. No encapsulation

This is most frequently broken rule of clean code and object oriented design paradigm. I see this almost in every codebase. Every class is public with public properties and public methods. This is not object oriented programming. Our duty is to create fully encapsulated objects and hide theirs internals. This is topic for another post why to do this but for know I beg you – stop revealing your classes internals only because your IDE add public keyword by default.

8. Too many conditional statements

Sometimes, when our bussiness logic is complicated, I see a lot nested if/else statements. This is difficult to read and understand.

Often we can get rid part of this statements applying some design pattern and principle (see The Open/Closed Principle and Strategy Pattern for example). If we can’t, we should decompose these conditionals.

9. Unused code

Unused code is created in 2 cases. First case is when code was changed (due to refactoring or requirements change) and some part of that code is not valid. Second case is when programmer wanted to add some additional functionality which is not required at the time of writing but he thinks it may be needed later.

In both cases unused code should not exist. It decreases redadabilty of code, design, adds unnecessary complexity to them – it should be avoided. There is even programming principle for second case – YAGNI.

10. Magic strings and numbers

Programming is enough difficult even without magic. Code with meaningless strings and numbers like Option == 1, order.Type = 'A' is difficult to read, maintain and refactor. Instead of this we should use enums and consts and enjoy good readability and compile-time checks.

Summary

I tried to list all most common issues which I often encounter. I think it is important to remember at least two things when we write the code. Firstly, code is more often read than written. Secondly, working code which even fulfills business requirements is not sufficient if it is written badly. Remembering this and knowing rules of writing good quality code will lead us to software craftsmanship faster.

How to publish and handle Domain Events

2019-06-19 UPDATE: Please check Handling Domain Events: Missing Part post which is a continuation of this article

Introduction

Domain Event is one of the building blocks of Domain Driven Design. It is something that happened in particular domain and it captures memory of it. We create Domain Events to notify other parts of the same domain that something interesting happened and these other parts potentially can react to.

Domain Event is usually immutable data-container class named in the past tense. For example:

Three ways of publishing domain events

I have seen mainly three ways of publishing domain events.

1. Using static DomainEvents class

This approach was presented by Udi Dahan in his Domain Events Salvation post. In short, there is a static class named DomainEvents with method Raise and it is invoked immediately when something interesting during aggregate method processing occurred. Word immediately is worth emphasizing because all domain event handlers start processing immediately too (even aggregate method did not finish processing).

2. Raise event returned from aggregate method

This is approach when aggregate method returns Domain Event directly to ApplicationService. ApplicationService decides when and how to raise event. You can become familiar with this way of raising events reading Jan Kronquist Don’t publish Domain Events, return them! post.

3. Add event to Events Entity collection.

In this way on every entity, which creates domain events, exists Events collection. Every Domain Event instance is added to this collection during aggregate method execution. After execution, ApplicationService (or other component) reads all Eventscollections from all entities and publishes them. This approach is well described in Jimmy Bogard post A better domain events pattern.

Handling domain events

The way of handling of domain events depends indirectly on publishing method. If you use DomainEvents static class, you have to handle event immediately. In other two cases you control when events are published as well handlers execution – in or outside existing transaction.

In my opinion it is good approach to always handle domain events in existing transaction and treat aggregate method execution and handlers processing as atomic operation. This is good because if you have a lot of events and handlers you do not have to think about initializing connections, transactions and what should be treat in “all-or-nothing” way and what not.

Sometimes, however, it is necessary to communicate with 3rd party service (for example e-mail or web service) based on Domain Event. As we know, communication with 3rd party services is not usually transactional so we need some additional generic mechanism to handle these types of scenarios. So I created Domain Events Notifications.

Domain Events Notifications

There is no such thing as domain events notifications in DDD terms. I gave that name because I think it fits best – it is notification that domain event was published.

Mechanism is pretty simple. If I want to inform my application that domain event was published I create notification class for it and as many handlers for this notification as I want. I always publish my notifications after transaction is committed. The complete process looks like this:

1. Create database transaction.
2. Get aggregate(s).
3. Invoke aggregate method.
4. Add domain events to Events collections.
5. Publish domain events and handle them.
6. Save changes to DB and commit transaction.
7. Publish domain events notifications and handle them.

How do I know that particular domain event was published?

First of all, I have to define notification for domain event using generics:

All notifications are registered in IoC container:

In EventsPublisher we resolve defined notifications using IoC container and after our unit of work is completed, all notifications are published:

This is how whole process looks like presented on UML sequence diagram:

You can think that there is a lot of things to remember and you are right!:) But as you can see whole process is pretty straightforward and we can simplify this solution using IoC interceptors which I will try to describe in another post.

Summary

1. Domain event is information about something which happened in the past in modeled domain and it is important part of DDD approach.
2. There are many ways of publishing and handling domain events – by static class, returning them, exposing by collections.
2. Domain events should be handled within existing transaction (my recommendation).
3. For non-trasactional operations Domain Events Notifications were introduced.

Related posts

Handling Domain Events: Missing Part
The Outbox Pattern