Organizing Code by Feature using Vertical Slices

I’ve written about organizing code by feature and vertical slices instead of technical concern quite a bit on this blog. However, it doesn’t seem to have caught on as much as I’ve hoped. I’m always seeing posts on Twitter about this concept where people finally catch on and make the discovery.

YouTube

Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing everything that is in this post.

Technical Concern

I’ve always found it interesting that layers or technical concerns ended up being seemingly the most important thing when organizing code. I’m curious how this came to be. My guess is there are many reasons, but I think project template/scaffolding are a culprit.

If you create a brand new ASP.NET Core MVC application, you’re going to get a folder for Models, Views, and Controllers. By default everything is organized by technical concern.

What I find interesting about this is you usually end up having Models, Views, and Controllers all be a 1:1:1. Meaning a ViewModel is likely only used in one View which is only used in one Controller Action. If this is the case, why benefit does having these files/classes live in a project structure based on technical concern?

What does your application do?

I care about capabilities. Features. I care about what an application does.

When I’m looking at a project structure and see a ManageController file, that gives me no insights into features or capabilities that bring to the system. Looking at this project structure below, of course, it’s an e-commerce site, but what are the rich set of features it provides?

Change

When I was creating systems in layers, my pain point was making simple changes to an existing feature or adding a new feature.

Having to edit multiple files across multiple projects seemed absurd and cumbersome.

Data is flowing throw layers. When a user invokes a request, data must flow through all the layers to ultimately hit a database. The same occurs when you need to present data to a user.

In some situations, you could be editing more than 6 files for a simple change.

  • DataAccess/ShoppingCartModel.cs
  • DataAccess/ShoppingCartRepository.cs
  • BusinessLogic/ShoppingCartServices.cs
  • Controllers/ShoppingCartController.cs
  • ViewModels/ShoppingCartViewModel.cs
  • Views/ShoppingCart/View.cshtml

Organize Code by Feature

Organizing Code by Feature

When you start organizing code by feature you get the benefit of not having to jump around a codebase. Things that related in behavior are placed together. From the screenshot above, if you need to make a change to how products are added to a Shopping Cart, guess which file you’d be changing?

Layers in Features

I’m not saying to throw out layers. Layers ultimately live inside the vertical slice of a feature.

The way I like to describe this is think of your system/service as a cake that has multiple layers. Each layer represents a technical concern. If you have a data access layer, it controls all of the data access within that service/system.

Instead of it being application wide, cut a slice out of that cake.

You still have layers. You still have technical responsibilities, but you’ve made those boundaries to within the vertical slice of a feature.

Dependencies

The biggest win when you start organizing by feature, is now your dependencies are within the vertical slice. This allows you to manage dependencies per vertical slice.

If you wanted to move from EF6 to EF Core, you could do this one vertical slice at a time. It does not mean you have to re-write an entire data access layer to migrate from one to the other.

Follow @CodeOpinion on Twitter

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

More

Defining Service Boundaries by Splitting Entities

Defining Service Boundaries is a really important part of building a loosely coupled system, yet can often be difficult. Here’s one way of realizing where service boundaries lie but looking at Entities and the properties and how they relate.

YouTube

Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing everything that is in this post.

Catalog

For the purpose of this example, I’m going to use an e-commerce, distribution domain. Don’t worry too much if you don’t know distribution. At a high level, you buy products from vendors, store them in your warehouse, then sell them to customers.

Here’s what my Loosely Coupled Monolith demo application has as a solution structure.

Defining Service

There are 4 boundaries defined. Catalog, Purchasing, Sales, and Shipping.

In the Catalog project, we have a ProductModel that represents a product in our system.

Dependency

Because we have this singular model of a product in our Catalog boundary, you can imagine the rest of the system will need access to it. In the Sales boundary, we have a feature to create an Order, which requires the Price of a product we’re purchasing.

For Sales to get the Product Price, we’ve exposed an interface & implementation to return product info.

Now here’s an example of using the IProductQuery.GetProduct() in our PurchaseProduct feature in our Sales boundary.

Splitting Entities

Now, this might not seem like all that bad that Sales has to take a dependency on Catalog. But we want our boundaries to be as autonomous as possible.

The primary reason I think the above example occurs is that the notion of an entity must live only in one place. I call this the “Entity as a Service”. Where a particular boundary owns an entity and provides an API to manage that entity.

In my example in this post, the Catalog boundary owns the Product entity.

What’s better served, in my opinion, is to have each boundary own the behavior and data around the concept of an entity.

Sale Price

The Price property/field on our ProductModel has no bearing on any other property on that model. Meaning, the price does not affect the name of the product. The same goes for Cost and Quantity. If any of those properties were to change, it has no bearing on what the Price is.

If they have no bearing to each other, why are they in the same model?

In this case, Price on a Product actually belongs to the Sales boundary, not the Catalog.

We can have the same concept of a Product live in multiple boundaries.

The above example is the ProductModel I’ve created for the Sales Boundary and added it to our Entity Framework SalesDbContext.

Now the PurchaseProduct feature does not need a dependency on Catalog anymore.

Cost

Since we no longer need the Price in our Catalog ProductModel, I’ve removed it.

Now the Cost property is the next easy target. The likely same applies that our Purchasing boundary would be the owner of the Cost. It’s going to be managing this value with the Vendor/Manufacturer, so it would make sense that it would own the Cost of a Product.

Quantity

Quantity here is referring to the Quantity on Hand of the product in the warehouse. The logical next step would that the Quantity on Hand would be managed by an Inventory or Warehouse boundary.

Warehouses with physical goods can some times do what is called an Inventory Adjustment. This can happen for various reasons such as people actually counting the products, finding damaged product, etc. This is a way to update the system to reflect the actual quantity on hand.

What if we had business rule that stated that you cannot purchase a product if there is no quantity on hand?

How would you model this? Would Sales have to have a dependency on the Inventory/Warehouse context so it could get the latest Quantity on Hand of a product?

In the situations I’ve been in, they use a business function called Available to Promise. This is a value that is calculated by the quantity on hand in the warehouse, what has been purchased from vendors but not yet received, and what has been ordered.

Defining Service

With using asynchronous messaging/events, the Sales context would keep track of a products ATP value and use that for the business rule around when an Product can be ordered.

Defining Service Boundaries

Defining service boundaries is difficult. Start out by looking at your Entities and splitting them up by sharing the same concept of a Entity across multiple boundaries.

An Entity does NOT need to reside in one single boundary. As shown in this example, the concept of a Product can reside in many different boundaries, and each concept owning the data/behavior it owns.

Follow @CodeOpinion on Twitter

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Links

Using Hangfire and MediatR as a Message Dispatcher

Two popular libraries in Hangfire and MediatR can be used together to create a pretty powerful out-of-process messaging dispatcher. I’ve covered this a bit many years ago but I figured I’d give it a refresh since it’s a bit easier in the world of ASP.NET Core.

YouTube

Check out my YouTube channel where I post all kinds of content that accompanies my posts including this video showing everything that is in this post.

Hangfire and MediatR Bridge/Wrapper

The first thing you need to do is create a bridge/wrapper around MediatR. At first this may seem completely pointless, but it has a purpose. Hangfire has a lot extensibility in terms of how jobs are executed that are often times defined by using attributes. Because we don’t own the MediatR library, we need to have our own class that we can defined these attributes on.

Here’s a simple start to our Bridge/Wrapper

In the example above, I have an overload for Send() that accepts the jobName as the first parameter. The DisplayName attribute will be used by Hangfire to show in the UI Dashboard the name of the job. This is a simple example of why we need this wrapper.

MediatR Extensions

The next piece of the puzzle is creating extension methods to be able to use Hangfire to create background jobs. In the example below I’ve created Enqueue() extension methods that use the Hangfire BackgroundJobClient to enqueue work using our Bridge/Wrapper

Hangfire Serialization

In the BackgroundJobClient.Enqueue() above, Hangfire will use Json.NET to serialize the IRequest that we are passing to Send() that ultimately gets put into storage. When Hangfire then pulls that job out of storage to perform the work, it needs to deserialize it. Because it’s just an IRequest it has no way to turning that into a concrete type.

To handle this, we need to configure Hangfire to add type handling when it serializes/deserializes.

ConfigureServices

The last thing we need to do is actually configure Hangfire in the ConfigureServices of either your ASP.NET Core Startup or your HostBuilder.

Here’s an example of my Worker process. This is just a console app that is purely a Hangfire server that just processes jobs from Hangfire.

Enqueuing a Request

In order to enqueue a MediatR request to Hangfire is a matter of calling the Enqueue() extension method we created off of IMediator.

In the example above, the HTTP Request to our Controller action will return a 204 NoContent, even though we are throwing in our PlaceOrderHandler because it’s execution is actually done out of the context of the HTTP Request. This could either be in a different thread, an entire different process, or on a totally on a different server).

More

There’s a lot more you can do with this and take it much farther to handle things like event publishing to have each event handler be it’s own job within Hangfire.

You can get all the source code of this running example on my GitHub.

If you have any thoughts or questions, please leave a comment on my blog, Twitter, or on the YouTube video.

Follow @CodeOpinion on Twitter

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Links