Improve your .NET code quality with NDepend

Functional C# Improves Your Design without Making Your Code Cleaner, Exactly

Functional C# Improves Your Design Without Making Your Code Cleaner, Exactly

Today I offer another one of the code research posts we’ve been doing.  If you want more backstory on the series, check out the last post in the series, where I give a brief history.  You should also read it if you want to understand both what I mean by functional C# and for details about its impact on codebases at the method level.

Quick editorial note: a couple of people have commented/sent notes asking about p-values.  I’ve been eliding those to keep the posts more narrative.  But as we’ve expanded the set of variables we capture, we’ve been looking only at dramatically lower p-values.  Those cited in this post, for instance, range between 0 and 0.04, with most being less than 0.01.

I’ll summarize the last functional study here, briefly.  Last time, I studied about 500 codebases to see what functional-style programming did to methods and types.  And the answer was that it made them less object-oriented, but it had surprisingly little influence on clean code statistics, like

  • Lines of code per method or type.
  • Cyclomatic complexity.
  • Parameters per method.
  • Method nesting depth.
  • Methods per type.

I expected that functional codebases would correlate with a reduction in all of those things.  In other words, I figured that functional-style programming would lead to smaller, clearer, more focused, and less complex methods.  It didn’t.

Undaunted, I vowed to take a broader look at the effect of functional programming on a wider array of concerns. And I did just that, with the help of my partner who runs the statistical regressions. Continue reading Functional C# Improves Your Design Without Making Your Code Cleaner, Exactly

C# Immutable Types Understanding the Attraction

C# Immutable Types: Understanding the Attraction

In our post about value objects, we briefly covered the topic of immutability. There, we talked about the more conceptual side of immutability, as in “value objects must be immutable types since it wouldn’t make sense for them to be otherwise.”

As it turns out, there are many practical benefits to making your types immutable—not just the value objects. I remember the first time I came across the concept of immutable types. I was researching string immutability, and somehow Google led me to a Stack Overflow question about immutability in general.

Up until that moment, I wasn’t familiar with the concept of immutability. I must admit it wasn’t an easy idea to wrap my head around. I remember thinking, “Why would I want objects that don’t change? Things change in real life!”

So, I’m writing this post with my past self in mind. The goal here is twofold: to explain why immutable types are desirable and to provide a quick recipe on how to work with them.

Continue reading C# Immutable Types: Understanding the Attraction

Checking DDD Ubiquitous Language with NDepend

Since NDepend version 2018.1, the tool proposes a default rule to check Domain Driven Design (DDD) Ubiquitous Language validity.

DDD Ubiquitous Language

Let’s quote Martin Fowler on Ubiquitous Language:

Ubiquitous Language is the term Eric Evans uses in Domain Driven Design for the practice of building up a common, rigorous language between developers and users. This language should be based on the Domain Model used in the software – hence the need for it to be rigorous, since software doesn’t cope well with ambiguity.

Evans makes clear that using the ubiquitous language between in conversations with domain experts is an important part of testing it, and hence the domain model. He also stresses that the language (and model) should evolve as the team’s understanding of the domain grows.

–Martin Fowler

Eric Evans coined the term DDD, let’s quote him:

By using the model-based language pervasively and not being satisfied until it flows, we approach a model that is complete and comprehensible, made up of simple elements that combine to express complex ideas.

Domain experts should object to terms or structures that are awkward or inadequate to convey domain understanding; developers should watch for ambiguity or inconsistency that will trip up design.

–Eric Evans

See below a sample of ubiquitous language usage in the real-world. We end up with clean and readable code:

The TrainTrain Code Base

To explain and demonstrate the rule, we’ll conduct our experiment on the TrainTrain code base.

This OSS code base has been developed by Bruno Boucard and Thomas Pierrain from 42Skillz, a French consultancy company specialized in DDD and developers coaching. TrainTrain has been developed in order to illustrate concretely most of DDD concepts (including Ubiquitous Language) in a session named How To Distill The Core Domain From Your Legacy App (Live Coding). In this session, a legacy version of the code is live-refactored to a DDD-compliant version. It has been performed both at Explore DDD 2017 (Denver, Sept 2017) and DDD Europe 2018 (Amsterdam, Jan 2018).

We worked with Bruno and Thomas to develop this first rule related to DDD and we expect that more rules will follow from this collaboration.

The Rule

See below the full source code of the new rule named DDD ubiquitous language check that can be found in the rule group Naming Convention. This rule is disabled by default because before using it, the user must customize both:

  • The core domain namespace name (by default set to “TrainTrain.Domain”)
  • The vocabulary list

The idea is to centralize in this rule source code the vocabulary. The rule then checks that all code elements defined in the core domain namespace are named with one or several terms found in the vocabulary list. Code elements checked include classes, enumerations, structures, interfaces, methods, properties and fields. If a term needs to be used both with singular and plural forms, both forms need to be mentioned, like Seat and Seats for example.

The NDepend rule system makes easy to modify the source code of an existing rule. There is no Visual Studio project to create and store, no NuGet package to reference, no assembly to compile, version and maintain, no integration. Just textual edition with code completion, API documentation and live result while editing, and then Ctrl+S, that’s it. As a consequence, the NDepend rule system is well suited to implement such rule that must be customized with some user data before usage.

Notice that this rule relies on the new NDepend API method ExtensionMethodsString.GetWord(this string identifier). This method extracts words from code identifiers. For example from the field identifier _seatsRequestedCount it extracts the 3 words seats, Requested, Count. To be compliant with the vocabulary list, we then set the first char to upper, for example seats becomes Seats.

Running the Rule

See below a screenshot on running this rule on a TrainTrain version. An issue is spotted on a core domain class named TreasholdCapacity. Both words are reported in the column wordsNotInVocabulary because both words are not in the vocabulary list. Moreover the word Treashold has a typo. At this point, to fix this issue:

  • either this class should be renamed with existing core domain vocabulary words
  • either these words should be added to the vocabulary list (with the typo fix)


DDD is nowadays a popular concept. We are proud to innovate with a static analysis code rule related to DDD. We have plans for more DDD related rules and we would like to hear both your feedback on using this rule, and your needs for more DDD related rules.


New .NET Core 2.1 and ASP.NET Core 2.1 APIs

.NET Core 2.1 and ASP.NET Core 2.1 Preview1 have just been released (see here the official announcement) and we are going to explore new APIs in this post. We’ll found out many of the new features announced in the .NET Core 2.1 Roadmap and ASP.NET Core 2.1 Roadmap on the MSDN blog.

We just released NDepend v2018.1 and we took a chance to support analysis of .NET Core 2.1 and ASP.NET Core 2.1 applications. NDepend is often deemed as the Swiss-Army Knife for .NET developers thanks to its code query language (CQLinq). CQLinq can be used to write code rules, quality gatestrend code metrics, explore dependencies or advanced code search. One thing CQLinq excels at is exploring the diff between two snapshots of a code base. Exploring new APIs is a sub-task of exploring what was changed. Let’s harness this capability to explore new .NET Core 2.1 APIs.

New .NET Core 2.1 Preview1 APIs

We could have downloaded sources files of both .NET Core 2.1.0 Preview1 and 2.0.0, recompile and then do the diff. Instead, since NDepend can analyze raw assemblies even without sources available, we compared assemblies in these two folders:

  • C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.0-preview1-26216-03
  • C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.0.5

Here is the CQLinq code query that lists all new public classes and types. It is also refined to match public members (methods and fields) of each new type in the result.

Find the whole list here .NET Core 2.1 new public classes. Here is a first glimpse in the screenshot below. We highlighted the new great Span<T> capability.

.NET Core 2.1 new classes

Not only new public classes list is interesting, but also new public methods added on existing public classes. This query does list these 1.500 methods:

Here also find a screenshot below and the whole list here: .NET Core 2.1 new public methods on existing public classes. For this screenshot we used the new Dark theme support of NDepend v2018.1.

.NET Core 2.1 new public methods

Interestingly enough let’s list new namespaces that contain at least one public type:

.NET Core 2.1 new public namespaces


New ASP.NET Core 2.1 Preview1 APIs

To analyze ASP.NET Core assemblies it was a bit more difficult than just comparing assemblies in 2 folders. ASP.NET Core assemblies are stored in NuGet packages so we did explore assemblies in the folder C:\Program Files\dotnet\sdk\NuGetFallbackFolder and then tinker a bit to get the wanted versions in both 2.1 and 2.0 cases.

Let’s use the same code query to match ASP.NET Core 2.1 new public classes :

ASP.NET Core 2.1 new public class

The same way here is the ASP.NET Core 2.1 new public methods on existing public classes :

ASP.NET Core 2.1 new public methods in existing public classes

And finally, here are the new ASP.NET Core 2.1 namespaces that contain at least one public classes.

ASP.NET Core 2.1 new namespaces



CQRS Understanding from First Principles

CQRS: Understanding From First Principles

There seems to be no end to the choices you have for architecture when building an application. You don’t want to fall victim to cargo cult programming, so you need to truly understand the options available. Today, we’ll focus on one option, called CQRS.

CQRS leads to a clean architecture that’s easy to maintain. Let’s take a look at the underlying principles of CQRS. This will help you understand what the benefits are and whether you want to use it in your applications. Continue reading CQRS: Understanding From First Principles

How to Measure Lines of Code Let's Count the Ways

How to Measure Lines of Code? Let’s Count the Ways

There are a few ways to count lines of code, and they each have their advantages and disadvantages.

Much of the differences come down to defining what a “line” is. Is a line a literal line in the source file, a logical statement in the language we’re using, or an executable instruction?

Let’s take a look at three metrics:

  • Source lines of code—the number of lines of code in a method, skipping comments and blank lines
  • Logical lines of code—the number of statements, ignoring formatting  and often counting a line as more than one statement
  • IL instructions—the number of instructions that the code compiles to

Is one better than the other? It depends on what you’re trying to measure.

Continue reading How to Measure Lines of Code? Let’s Count the Ways

Your Guide to Winning Arguments About Code

Your Guide to Winning Arguments About Code

The whole “tabs versus spaces” thing occupies sort of an iconic position in the programmer world.  It represents the impossibility of winning arguments that are unwinnable by their very nature.  These are so-called religious wars — our techie version of The Butter Battle Book but without the Cold War overtones.

But this and arguments like it rarely actually play out in team rooms and offices.  At least, that’s always been my experience.  I’ve only ever witnessed live “tabs versus spaces” arguments happen ironically.

Actual Arguments in the Programmer World

So here’s how it really goes down.

You take a job with a company, excited about the new office, the shorter commute, and the bump in pay.  You’re riding high.  But then the onboarding starts with the codebase.

Greg, the most senior member of the group, walks you through the codebase with a slightly smug affect of obvious pride.  The codebase has everything you could ever want, according to Greg.  To your mounting horror, this includes

  • Inheritance hierarchies that are inscrutable, dark, and deep (with miles to go before you sleep).
  • A generous portion of global state.
  • Liberal use of reflection, often for no discernible reason.
  • And, of course, an extensive, homegrown “framework.”

Greg finishes with a flourish: “So, anytime you need to add a new feature, you just open GodClass.cs, scroll down to line 12,423, add another method, and get started!”

You’re new, and you’re not entirely sure that this isn’t an elaborate prank, so you swallow and say, “Oh…great!” while already planning the lengthy suggestions document that you’re going to put together.  And so the stage is set for what will become a never-ending string of arguments of variable politeness about the codebase.

Swap my hypothetical specifics for yours, but the formula is the same.  Someone is asking you to exist in a codebase that you have philosophical reservations about, which will force you to write code you don’t like.

Winning Arguments: How Does One Define This?

I’ve now set the stage, but what does it actually mean to “win” an argument?  This is pretty hard to define in a lot of contexts, such as people arguing on Facebook about politics or fighting at dinner.  Is it the one who got the last word in?  The one who was louder?  The one who didn’t simply give up?

Luckily, in your quest to de-Greg your new company’s codebase, “winning” is easier to define (if admittedly something of a loaded term).  You win if, by mutual consent, however grudging, the thing you think should happen winds up immortalized in the team’s source control.  And the mutual consent part matters.  Just slamming something into source control and being forced to revert later by an angry Greg doesn’t count.

You win when your argument carries the day and results in concrete action.  So let’s look at some techniques for making that more likely.

Continue reading Your Guide to Winning Arguments About Code

Functional Programming Makes Your Code Not OO...And Thats It

Functional Programming Makes Your Code Not OO…And That’s It

Over the course of the fall and winter, I’ve been gaining momentum with code research posts.  Today, I bring that momentum to bear on the subject of functional programming.  Or at least, on functional style of programming in C# codebases.

But before I do that, let me provide a little background in case you haven’t caught the previous posts in the series.  It started with me doing automated static analysis on 100 codebases to see how singletons impact those codebases.  Next up, I used that data to look at how unit tests affect codebases.  That post generated a lot of buzz, so I enlisted a partner to help with statistical analysis and then boosted the codebase sample size up to 500.

At the end of that last post, I suggested some future topics of study.  Well, now I’ve picked one: functional programming.

What Is Functional Programming?

The idea with this post is mostly to report on findings, but I’d be remiss if I didn’t provide at least some background so that anyone reading has some context.  So first, let’s cover the topic of functional programming briefly.

Functional programming is one of the major programming paradigms.  Specifically, its calling card is that it disallows side effects.  In other words, it models the rules of math, in which the result of the function (or method) is purely a deterministic function of its inputs.

So, in pseudo-code, it looks like this:

This is a functional method.  But if you do something like this

or like this

then you’re out of the functional realm because you’re adding side effects.  These two modified versions of Add() each concern themselves with the world beyond processing the inputs to add.  (As an aside, you could “fix” this by passing the global variable or the _databasePlopper dependency to the method as a parameter.)

Now, take note of something because this matters to the rest of the post.  While C# (or any other object-oriented language) is not a functional language, per se, you can write functional methods in C#.

Continue reading Functional Programming Makes Your Code Not OO…And That’s It

An Introduction to Clean Architecture

An Introduction To Clean Architecture

It seems to me that the topic of software architecture has attracted a lot of interest in the last few years. And among many different flavors and styles of software architecture, there’s one that attracts even more interest than the others. I’m talking about the clean architecture, proposed and evangelized by Robert C. Martin, a.k.a. Uncle Bob. (And for the rest of this post, it’s simply referred to as “clean architecture.”)

By employing clean architecture, you can design applications with very low coupling and independent of technical implementation details, such as databases and frameworks. That way, the application becomes easy to maintain and flexible to change. It also becomes intrinsically testable.

We’ll start today’s post not by explaining what clean architecture is right away. We’ll first dive into the problems that high coupling can cause in software projects. Then we’ll proceed to see the more mainstream solution to these problems.

Finally, we’ll explain the flaws with this solution, showing why and how clean architecture can be the piece of the puzzle that was missing for your application to achieve its full potential.

“Desperation” of Concerns

If you have at least a couple years of software development experience under your belt, then I can almost guarantee you’ve heard the term “separation of concerns.” It’s a principle that shows up quite often when talking about software architecture.

One of its incarnations is in the form of advice: “Separate presentation from business logic.” It’s very sound advice and I agree with it wholeheartedly, but the problem is that it’s not so easy or clear how to put it into practice, especially for beginners.

In practice, what ends up happening is that logic business frequently leaks to the application’s UI. And the same can go the other way around: it’s not so rare to find business logic code concerning itself with UI concepts, such as colors, markup languages, font sizes, and what have you.

And things can get even worse when you add data access to the mix. How does one free oneself from this mess?

Continue reading An Introduction To Clean Architecture