Typemock Isolator: A CLR Interception Approach to Unit Testing

Recently I have contacted Typemock and I was offered a license of Typemock Isolator, their flagship tool, in support of my OSS project LINQBridgeVS. Typemock Isolator is a viable tool to incorporate CLR interception for unit testing in .NET.

CLR is the acronym for Common Language Runtime and it is the virtual machine that manages the execution of .NET programs. Typemock Isolator intercepts CLR calls at run-time and offers a fluent API to fake almost anything: static and sealed classes, instances, virtual or non-virtual synchronous and asynchronous methods, P-invoke calls, private and static constructors and also LINQ queries.  Typemock Isolator comes as a Visual Studio extension compatible with Visual Studio from 2010 through 2017 with any .NET Framework version up to 4.7.2 and incorporates four different components: 

  • Typemock Isolate contains the Typemock Isolator Mocking API, a fluent API to fake and mock objects based on the Arrange-Act-Assert pattern, and Insight which gives detailed information about the behaviour setup during test debugging. 
  • Typemock Suggest suggests and creates tests, for either NUnit or MsTest, for methods and classes in legacy or mainstream code that have partial to no test cover. 
  • Typemock SmartRunner is the built-in test runner and identifies and runs only the impacted tests after the solution’s tests have run for the first time. This includes all modified tests and those tests that need to run because the code they test has changed. 
  • Typemock Coverage is a code coverage tool that displays code coverage for tests, methods, all classes or only those that have recently changed or the entire solution. It also display real-time code coverage while code is written.

Licensing System

Typemock Isolator for .NET has three different types of licenses which are offered in two versions: annual or perpetual. The price starts at €479 pa or (€899 perpetual) for Isolator Essential which comes with the mock framework, the test runner and method coverage. Isolator Complete adds Auto-generated test suggestions and it costs €799 pa (€1599 perpetual). The last one is Isolator for Build Server which adds support to run tests on up to five machines and comes at €1119 pa (€2499 perpetual) . For more information visit the pricing page. Typemock is free for MVPs and there is also support for open source projects, although not directly advertised through their website. If you’re interested in having a license for your open source project get in contact with them through the contact us form and send a brief description of your project.


Writing unit and integrations tests is a vital part of the software development life-cycle. It is often underestimated and left as the last part of the development. Achieving an extended test coverage is extremely important for the creation of a reliable and stable product. Techniques and principles from Test Driven Development could be used by teams to make the creation of tests easier.

Reality is often different though. It is a rare opportunity to work on a brand new project where both the design and the development process can be decided from the beginning. Often enough a team determined to follow TDD principles ends up not allocating enough time to hit the desired coverage or tests are not strictly written first. In such cases it is preferred to offload developers and delegate QA teams to write automation tests or to test an individual feature manually. Clearly this approach is not scalable and doesn’t guarantee stability over time. When code changes are not monitored by both unit and integration tests it is very hard to estimate and also to predict the impact that a specific change will have to other parts of the system. 

Unless TDD principles are followed and a robust and clean design is made from the very beginning, the process of writing tests in isolation becomes increasingly more difficult as the project evolves and cannot be achieved without proper (and often painful) refactoring.

The Limitation of Mock Frameworks

Mock object frameworks simulate objects’ behaviour. A mock is something that is setup as part of a test so that it returns an expected result. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything. As a rule of thumb mocks are used to ‘fake’ dependencies of a class. When a method or a class is tested in isolation, i.e. when a a unit test is written for it, dependencies to other systems should be mocked.

There are a lot of free open source mock framework for C#: MoqRhinoMocksFakeItEasy and NSubstitute just to name a few. There is also a built in Visual Studio version called Microsoft Fakes.

The aforementioned frameworks (except for Microsoft Fakes) have one peculiar aspect in common: they can only mock a class given its interface or its base class as long as the base class is inheritable and it declares virtual methods for the behaviours to be setup. 

Testing using the Proxy pattern

Sealed classes, static classes and non-virtual methods cannot be mocked with the proxy pattern approach most mock frameworks use. A proxy is a class functioning as an interface to something else. The proxy has to implement the same interface as the Subject so that the Client doesn’t realise that it is using a proxy. Mock frameworks in fact create proxies at run-time based on interfaces or abstract classes and they are able to override any virtual method. 

The Proxy Pattern
The Proxy Pattern class diagram.
public class Auth
   public int AuthStatus { get; private set; }
   public virtual bool IsAuthValid(string user, string pwd)
      return false; //this could be an external call to an auth server

   public void AuthenticateUser(string user, string pwd)
      if ( IsAuthValid(user, pwd) )
           AuthStatus = 10;

 // Arrange
 var moqAuth = new Mock();
   .Setup(p =&gt; p.IsAuthValid(It.IsAny<string&gt;(), It.IsAny<string&gt;()))
 // Act
 moqAuth.Object.AuthenticateUser("myUser", "myPwd");
 // Assert
 Assert.IsTrue(moqAuth.Object.AuthStatus == 10);

In the arrange section of the snippet above, Moq creates a proxy that inherits from the class Auth. During the setup, a call to IsAuthValid is overridden so an expected value is returned by default when the method is invoked. The method IsAuthValid however must be virtual, otherwise Moq won’t be able override it and will raise an exception. 

Testing using CLR Interception

Let’s see how the test and the class Auth could be re-written using the CLR interception approach adopted by the Typemock API:

public sealed class Auth 
   public int AuthStatus { get; private set; } 
   public bool IsAuthValid(string user, string pwd) 
     return false; //this could be an external call to a server or db 

   public void AuthenticateUser(string user, string pwd)
      if ( IsAuthValid(user, pwd) )            
         AuthStatus = 10; 

var auth = new Auth(); 
 .WhenCalled(() => auth.IsAuthValid(string.Empty, string.Empty)) 


Assert.IsTrue(auth.AuthStatus == 10);

I changed the class Auth to be sealed instead and I also made the method IsAuthValid non virtual. Classes should either be designed for inheritance or prohibit it. There is a cost to designing for inheritance, and unless there is a good reason, it should be avoided.

In the test code above there is no mock created. The behaviour is overridden directly on the instance of the object. Typemock intercepts the call to the object’s method at runtime and redirects it to return the value setup instead. If I wanted to make the method private it would also require a small change in the test:

Isolate.NonPublic.WhenCalled(auth, "IsAuthValid").WillReturn(true);

Private or non-virtual methods cannot be tested using a proxy based mock framework. The alternative is using Microsoft Fakes, which I mentioned earlier, and it has similar features to Typemock Isolator.
Microsoft Fakes has support for either proxy-based mocks, which are called stubs, and method interception mocks called shims, which diverts method calls at run time. With Microsoft Fakes every assembly needs to be faked manually. For example if you need to generate a mock for a .NET system type, like DateTime, then a Fake for the System.dll must be created and referenced in the test project. Microsoft Fakes has also some other limitations. Please refer to this link for a detailed comparison of Microsoft Fakes vs Typemock.

Improved design using the Bridge pattern

At this stage one could argue that the current design for the Auth class is poor and a better one would be to abstract away the dependency that authenticates the user from the Auth class.

The Bridge Pattern class diagram.

The Bridge pattern, initially designed by the Gang-of-four, is the best structural pattern to decouple an abstraction from its implementation so that the two can vary independently. It removes the compile-time binding and the implementation can be selected at run-time. Let’s use the Bridge pattern in the Auth class, and let’s add two more dependencies for logging and for db access:

public interface IAuthSystem
   bool IsAuthValid(string user, string pwd);

public interface ILogging
   void Log(string msg);

public interface IRepository
   IEnumerable<T&gt; Get<T&gt;();

public sealed class Auth
  private readonly IAuthSystem _authSystem;
  private readonly ILogging _logging;
  private readonly IRepository _repository;

  public int AuthStatus { get; private set; }
  public Auth(IAuthSystem authSystem, ILogging logging, IRepository repository)
     _authSystem = authSystem;
     _logging = logging;
     _repository = repository;

  private bool FindUser(string userName)
     var result = from user in _repository.Get<User&gt;()
                where user.UserName.Equals(userName)
                select user;

     return result.Any();
  public void AuthenticateUser(string user, string pwd)
       _logging.Log($"User logging in {user}");

      if ( FindUser(userName) &amp;&amp; _authSystem.IsAuthValid(user, pwd))
         AuthStatus = 10;
  var authSystem = new Mock<IAuthSystem&gt;();
  var logging = new Mock<ILogging&gt;();
  var repository = new Mock<IRepository&gt;();
    .Setup(p =&gt; p.IsAuthValid(It.Is<string&gt;(s =&gt; s == "Coding"), It.Is<string&gt;(w =&gt; w == "Adventures")))

    .Setup(p =&gt; p.Get<User&gt;())
    .Returns(new List<User&gt;{ new User{UserName = "Coding"}});
  var auth = new Auth(authSystem.Object, logging.Object, repository.Object);
  auth.AuthenticateUser("Coding", "Mock");

  Assert.IsTrue(auth.AuthStatus == 10);

  var auth = Isolate.Fake.Dependencies<Auth&gt;();
  var fakeAuthSystem = Isolate.GetFake<IAuthSystem&gt;(auth);
  var fakeRepository = Isolate.GetFake<IRepository&gt;(auth);
     .WhenCalled(() =&gt; fakeAuthSystem.IsAuthValid("Coding", "Adventures"))

     .WhenCalled(() =&gt; fakeRepository.Get<User&gt;())
     .WillReturnCollectionValuesOf(new List<User&gt; {new User {UserName = "Coding"}});

   auth.AuthenticateUser("Coding", "Adventures");
   Assert.IsTrue(auth.AuthStatus == 10);

With this new design it is much easier to mock away the dependency to IAuthSystem, ILogging and also IRepository. In Moq a mock must be created, setup and an instance passed to the constructor of Auth for each dependency declared in the constructorIn Typemock API there is a shortcut instead to fake all dependencies declared in a constructor using the Isolate.Fake.Dependencies<T>() method. With Isolate.GetFake<T>(object) the corresponding faked dependency can be retrieved to setup behaviours on it:

Auth authObject = Isolate.Fake.Dependencies<Auth&gt;();

IAuthSystem fakeDependency = Isolate.GetFake<IAuthSystem&gt;(authObject);
IRepository fakeRepository = Isolate.GetFake<IRepository&gt;(auth);

Mocking static methods

One thing I always wanted to do freely is using static methods or static classes and also have the ability to override behaviours without having to wrap dependencies with an abstraction layer. For example in my OSS project I have a class called CommonRegistryConfigurations that has a lot of helper methods to access the Windows registry. I always refused to create an abstraction layer that wrapped the Registry class to access the windows registry. I  would eventually end up having parts of my code that rely on these helper class un-tested. Typemock supports faking static methods on static classes, so I was able to setup my object behaviour to mock the call to the static method that access the registry:

public static bool IsSolutionEnabled()
   string keyPath = "aKey";

   using (var key = Registry.CurrentUser.OpenSubKey(keyPath))
       return (bool)key.GetValue("myValue");

// Test 
  .WhenCalled(() => 

There is one important caveat to keep in mind though. When Isolate.WhenCalled is used to define a fake behaviour on static methods and/or static classes, the behaviour has a global scope. This means that the setup will redirect calls from other unit tests also. It is in fact good practice to mark the test class with a specific attribute available in the Typemock API called IsolateAttribute which makes sure all behaviors are reset at the end of a test method.

Typemock and LINQ Queries

Abstracting away the access to a database is no easy task. One common route is to implement the Repository pattern to abstract away the data access logic, so unit tests can use stubs or mocks as implementations of the IRepository interface. Another solution, if an ORM like Entity Framework is used, could involve faking the DbContext itself instead of wrapping everything with the Repository pattern. There’s a good article here with a thorough explanation on the topic. 

A feature that has really caught my attention is the ability to fake the result of a LINQ query.  Let’s look at the following code:

public bool FindUser(string userName)
   var result = from user in _repository.Get<User&gt;()
                where user.UserName.Equals(userName)
                select user;

   return result.Any();

// Typemock
 var auth = Isolate.Fake.Dependencies<Auth&gt;();
    .WhenCalled(() =&gt; from user in Enumerable.Empty<User&gt;()
                    where user.UserName.Equals(string.Empty)
                    select user)
    .WillReturnCollectionValuesOf(new List<User&gt; { new User() });
 bool userExists = auth.FindUser("Adventure");


In the snippet above, the method FindUser fetches users from a repository using a LINQ query. Instead of changing the behaviour of the method, or faking the repository, it is also possible to fake the result of the query itself. It’s a bit obscure to me though the criteria the API uses to swap the original LINQ query with the one setup in the unit test. I looked up at their official documentation on the topic, but I couldn’t found anything that hints at how linq expressions are swapped around. Regardless of the gore details this feature is very powerful.

Build Server Integration

Typemock Isolator integrates with the several famous build and continuous integration servers like CruiseControl.NET, Jenkins CI, TeamCity and Team Foundation Server, as well as custom build servers. There is a good bit of documentation on their website about Server-side integration. I personally use Appveyor, a free continuos integration solution for Windows and Linux that integrates nicely with GitHub.

Typemock doesn’t integrate with Appveyor as easily as it does with the official supported build servers. Tests that use CLR interception must be run by TMockRunner, a utility part of Typemock Isolator that launches external programs like code coverage tools or a unit test runner like MSTest.

There is some documentation that explains how to run TMockRunner and also how to install it on a custom build server. I’d have preferred to have everything in a single page (or section) so I didn’t have to jump around to find what I needed.

It took me a while to figure out a powershell script that worked nicely with Appveyor. Appveyor runs any custom script with low privileges, thus access to the windows registry is forbidden. TMockRunner needs to access the registry for the initial setup, so I had to come up with a hack to set some specific environment variables to trick TMockRunner into thinking there was no windows registry available. Luckily the support team in Typemock offered a better solution by suggesting to elevate the privileges of my custom powershell script.

I’ll share with you both solutions, in case you need to setup TMockRunner in Appveyor like I did. In the first solution I had to setup the following environment variables in my yml file:

TM_INSTALLDIR: c:\PathToTMockRunner\ 
TMOCK_NO_REGISTRY: 0x1 #this actually tells TMockRunner
there's no registry available
secure: the encrypted licence number
secure: the encrypted company name

Which lead me to this powershell script:

   -deploy AutoDeployFolder 
    vstest.console.exe "mytest.dll" "mytest2.dll" 

The proper fix though involved elevating the privileges of the powershell script. Then the setup of those four environment variables was no longer needed:

$args = TMockRunner.exe 
   -deploy AutoDeployFolder 
   -register yourLicense vstest.console.exe 
   "test.dll" "test2.dll" /logger:Appveyor

Start-Process powershell -Verb runAs -ArgumentList '$args'


The ability to override methods and classes everywhere, and also in some .NET  classes, is very powerful. It enable developers to write unit tests in isolation in both legacy code where there is none to very little degree of freedom and also in mainstream code. Such freedom shouldn’t be an encouragement to write poorly designed software and TDD (or BDD) should always be the preferred approach when possible so that tests are guaranteed to be part of the product from the very early stages.

The other side of the coin is that a software architecture should always be designed around the problems it solves and the tasks it performs. Being forced to declare methods virtual, avoid sealed or static classes or create a lot of interfaces to abstract any dependency, if not for some technical limitation of mock frameworks, is in my opinion unnecessary. 

On the cons Typemock is not yet compatible with .NET Core and I guess the reason is the different common language runtime (the CoreCLR) .NET Core uses. Also Typemock Suggest needs to be disabled or it will crash if you’re working on a .NET Core project.

I also struggled a bit to setup Typemock in Appveyor, adding the relevant steps I highlighted in this article in their official documentation would be of great help. Another improvement is keeping the Visual Studio extension in sync with the version of the Typemock API. If they mismatch, e.g. you update the Typemock API to a newer version using NuGet but not the extension then an exception is thrown when unit tests are run. 

I really had fun creating tests on my OSS project using Typemock.
For long time I didn’t have much test coverage and finally I was able to increase it in relative short time without doing a huge refactor. The fluent API is very intuitive and easy to use. I hope Typemock will add support for .NET Core in the near future.

This is it, I hope you enjoyed reading this article, see you soon!

NDepend: A Static Analyser for .NET and .NET Core

NDepend is static analyser for .NET and .NET Core. Recently I was contacted by its creator, Patrick Smacchia, who kindly offered a license in support of my OSS project LINQBridgeVs.


NDepend is a tool mainly targeted for software architects who want to have a deep insight into their projects. NDepend gathers data from a code base and includes code quality metrics, test coverage statistics, assembly dependencies, evolution and changes, state mutability, usage of tier code, tech debt estimation and more. Another interesting feature is the ability to write custom rules using a domain specific language called CQLinq, which is based on LINQ, C# and the NDepend API.

NDepend comes with tons of features and it feels overwhelming at first. It has a quite steep learning curve before getting familiar with it. However there is lot of documentation, both on the official website and also in App which helps a lot.

Licensing System

There are two types of licenses: per seat (€ 399.00) for developers that use the UI (or the stand-alone app), and per machine ( 799.00) for servers that integrate NDepend into their build process. This price model is probably not a problem for companies but it might be a for individual developers. Although it is not advertised on the website there is official support for MVP and open source projects. Microsoft MVP are eligible for a free personnal license. Get in touch at this email address mvp@ndepend.com.


NDepend does not have an installer, it comes in a zip file, but its setup and first activation are pretty straightforward. Check out the introduction video on how to install it and get started.

NDepend can be run either as a stand alone application, using the executable VisualNDepend or within Visual Studio, by installing the extension (support for 2012 through 2017). There are also two console applications:

  • NDepend.Console is the command-line version of NDepend and can be used to automate the report generation using a CI server. NDepend has built-in integration with TeamCity, FinalBuilder, TFS and CruiseControl.NET
  • NDepend.PowerTools shows how to make the best out of the NDepend API syntax. It contains a lot of examples for code rules checker, code diff reporter, handy development tools, build process checker, etc.

First Impressions

I’ve been using NDepend for quite a while now and honestly it took me some time to get my head around the UI and the tons of features this tool is shipped with. The amount of information is at first overwhelming, and in my opinion the UI at times contains a lot of information. However after a few hours of usage I felt I was more confident to use it and it became easier to search and find what I needed.

The Visual Studio integration is handy, as you don’t have to leave Visual Studio. New reports are generated after successful build and it’s possible to compare metrics across different analysis. Having a second monitor is advised though as it makes it tidier and easier to keep the NDepend window on one monitor and avoid annoying switching between windows.

One feature that caught my eye is the technical debt estimation (TB). The TB metaphor was coined in 1992 by Ward Cunningam, a design pattern and extreme programming pioneer. Think of TB as a financial debt. It must be paid at some stage and it accumulates with other debts, generating interests and prolonging the time needed to pay it back.

I’m sure at some stage in every software developer’s carrier there grows an urge to refactor the code and reality is there is never time for it. Unfortunately strict deadlines or difficult targets lash back leading to hacks, quick fixes and poor design decisions in favour of quicker releases to satisfy customers. Technical debt is often underestimated as it is seen as a cost that doesn’t produce an immediate benefit. “It’s just code!” as they might say.

The technical debt estimation in NDepend produces an estimate, expressed in man-hour to fix code issues found. Settings can also be changed for the average cost of man-hour of development, the currency, the estimated number of man days to develop 1000 logical lines of code, scale debt rating percentage etc in the debt settings. The ability to calculate the cost of technical debt and monitor it over time is a great advantage especially to communicate it to non technical people and justify how a refactor or a new re-design could save a lot of time and money over time.


Smart Technical Debt Estimation – Configuration

Under the hood NDepend uses code rules, i.e. code metrics, to calculate debt and are grouped by: application, assemblies, namespaces, types, and methods. When a rule is violated then there could be a code smell, poor object oriented design, immutability and/or threading issues, naming convention consistency across types, methods and namespaces, source file organisation and so on.

NDepend and LINQBridgeVs

LINQBridgeVs is a Visual Studio extension that transmits debugging variables from VS to LINQPad. I’ve been working on it for quite some time now but the code base is not huge. There are over 1700 lines of code over 6 assemblies. Let’s have a look at the NDepend dashboard:


NDepend Dashboard – I got a B!

The dashboard page has several panels on top and trend graphs on the bottom or on the side if your monitor has enough resolution. Panels contain info about code metrics, technical debt estimation, test code coverage, method cyclomatic complexity, quality gates and violated rules. NDepend also supports trend metrics, which is the ability to monitor the evolution of the project by comparing metrics across different analysis. Trend graphs can be found below the metric panels:


Trend Graphs

Every number in the dashboard is interactive. Clicking on any of them generates a reports, which is essentially a specific CQLinq query run in a temporary preview tab (like the temporary preview documents in Visual Studio), which can be found in the “Rule Editor Window”, i.e. the NDepend query editor.


Rules Violated Tab in the Rule Editor Window

Tabs are divided in two sections: the description on top and the result of the query below in a data grid form, which is highly interactive. It’s possible to switch between description and source code view to personalize the corresponding query:


Rules Violated – CQLinq Source

The result is shown in the grid at the bottom. For each rule there are the number of issues:

  • Debt: the estimated effort to fix the issues.
  • Annual interest: The amount of time needed required to fix the issue if left unfixed.
  • Breaking point: it represents the time-point from now to when the estimated cost-to-fix the issue will reach the estimated cost to leave the issue unfixed. It is calculated by dividing the estimated debt by the annual interest. The breaking point is inversely proportional to the Return On Investment of fixing an issue. Thus the lower the breaking point, the higher the ROI.

Based on this assumption I modified the query above for violated rules to filter only those that have a breaking point within 1 and 365 days:

// Rules violated
from r in Rules
where r.IsViolated() && r.BreakingPoint() < TimeSpan.Zero && r.BreakingPoint() <= TimeSpan.FromDays(365)
orderby r.BreakingPoint().TotalMinutes ascending
select new
Issues = r.Issues(),
Debt = r.Debt(),
AnnualInterest = r.AnnualInterest(),
BreakingPoint = r.BreakingPoint(),
Category = r.Category

The grid in the image below shows 19 rules that need to be addressed, two of which are flagged as critical. In NDepend critical rules represent high priority rules that must never be violated. They are marked with a red triangle over the exclamation mark.


Hovering the mouse over a rule or clicking on it opens a floating panel that contains a thorough description of the issue and often link to a discussion page on the topic. Double clicking on a rule opens instead its corresponding CQLinq source.

InfoRuleViolatedThe two violated critical rules are: “Avoid having different types with the same name”, and “Avoid non-readonly static fields”.

I only agree with the first rule partially. I wouldn’t want to have a huge number of different types with the same name as that in fact could easily generates confusion (and probably is a sign of bad design). However if there are only a few types with the same name I believe it’s not going to be an issue. It is not uncommon to have shared names across types in different domains. For instance, in the .NET Framework, the class Timer is defined either in the System.Windows.Forms.Timer and also in System.Threading.Timer namespace. The former is a timer suitable for Windows Form environment and it runs on the main thread as it is often used to modify properties on a form. The latter instead is a thread timer and provides a mechanism for executing a method on a thread pool’s thread at specified intervals. The two classes, despite the same name, do similar things in a very different way. One could argue that the two timers could be called with different names, e.g. FormTimer and ThreadTimer but the disambiguation is better managed at namespace level.

Conditions for a rule to be violated can be changed though in its corresponding CQLinq source. For example I changed the minimum number of types before the rule is considered violated and reported:


Increasing the minimum number of types allowed with same name.

The second critical rule “Avoid non-readonly static fields” is a warning for an OOP design flaw. Static fields are states shared with every instance of the class where they are declared. If they are mutable then extreme care must be taken to initialise and to reset them correctly.  In a multi-threaded environment mutable static fields are not thread-safe. Race conditions cannot be avoided, and in this scenario bugs could be very hard to trace and even to replicate. It is important to make static fields immutable and private. The rule however suggests to declare them as readonly but that by itself doesn’t enforce complete immutability. Readonly guarantees that the instance can only be assigned once during the construction and it cannot be changed during its lifetime in the AppDomain. For instance, in a readonly List or a Dictionary, values can still be added or removed. Clearly it’s up to us to “protect” those fields from being modified by enforcing immutability. To read more on the topic a good explanation can be found here.

In my specific case I declared a public static string in a class (I know it’s horrible) called RavenWrapper. Such class has been designed to be a Singleton that uses lazy instantiation.  I wrote this class as a separation layer for the Raven SDK, a library that sends errors to Sentry (an open source error tracking system). More on the singleton later.


6 methods use the public static field VisualStudioVersion directly.

The public static string represents the version of the Visual Studio instance where LINQBridgeVs is running on. For “convenience” (truth is laziness) I set this field once outside the class so that I don’t have to pass the vs version all the time as a method parameter. The choice of a singleton class doesn’t help either. I can’t overload the constructor to do the most obvious thing: make the field private, non-static and read-only and let the constructor initialise it.

In fairness this class has too many design flaws and issues, so I decided to isolate it in a query and see what NDepend thinks about it:


Violated Rules in Raven Wrapper

As I imagined this class is violating many more rules than I expected: immutability, visibility, OOP design and naming convention. Let’s have a look at the class code:

public sealed class RavenWrapper {
 private static Lazy _instance = new Lazy(() => new RavenWrapper());

 public static RavenWrapper Instance => _instance.Value;

 private RavenClient _ravenClient;
 public static string VisualStudioVersion;

 private RavenWrapper() { /*init stuff*/ }

 public void Capture(Exception exception, ErrorLevel errorLevel, strIng message){ }

Looking back at it now, I realise there was no real benefit in having this class as a singleton. I should probably have made the RavenClient static, readonly and private. Even in that case there is no advantage really. RavenClient doesn’t open or reserve a connection when it is instantiated, so there wouldn’t’ be any benefit in “caching” its instance.

In my first refactor attempt to the class I changed the way the static instance of the object is created using a method instead of a property so that I can pass along the vs version as a parameter to the constructor. This class is still designed as a singleton:

private static RavenWrapper _instance;
public readonly string _visualStudioVersion;

public static RavenWrapper Instance(string vsVersion)
   if (_instance == null)
         _instance = new RavenWrapper(vsVersion);
   return _instance;
private RavenWrapper(string vsVersion)
   _visualStudioVersion = vsVersion;

When I ran another analysis on the solution I surprisingly found that the debt went up by 2%. Also 4 more rules were violated (1 of which was critical). It didn’t seem the change I made to the class was the right one.


~2% Tech Debt Increase.

Let’s see again what NDepend thinks about RavenWrapper now, and how many rules I fixed/broke.


RavenWrapper – More violated rules.

Despite the number of violated rules hasn’t changed, the total cost, the debt and annual interest has halved just by resolving the first critical rule. Although I am not quite there yet, I think I’m on the right track.

Interestingly NDepend now recognises the RavenWrapper uses the singleton pattern while it didn’t when the it was implemented using lazy instantiation. The singleton is considered by many an anti-pattern and there can be found a lot of different opinions around the web. On the corresponding violated rule there’s an interesting link to an article that treats the topic extensively.

In my third refactor attempt I decided to remove entirely the singleton implementation. This is what I came up with:

public sealed class RavenWrapper
    private readonly RavenClient _ravenClient;

    private readonly string _visualStudioVersion;

    public RavenWrapper(string vsVersion)
_visualStudioVersion = vsVersion;

Only now I understand how complicated and unnecessary the original design was. The simplest solution is most of the time the best. When I ran again the query I finally got a good result:


RavenWrapper – Two violated rules only.

The “API breaking changes Methods/Fields” rule warns that the current API has changed since the baseline and a method or a field has been removed. These warnings are very important for SDK development because a change in the API can break that rely on them. This is not relevant to me though as this is a Visual Studio extension and not a library like JSON.NET or Moq for instance.

Final Thoughts

It’s been fun to play around with NDepend. I brushed up my skills on code metrics, OOP design practices and code smells. Although it is a software targeted for skilled software architects I also believe it could be a great learning opportunity for mid and senior developers.

I can’t of course say if this software is the right one for you as it very much depends on your needs, budget and size of your project.

NDepend has a lot of features and it’s fully configurable although the first few hours will be a bit of a pain. NDepend is very broad it might take a long time to master it. There are plans though to release with the next version of NDepend a simplified beginners VS menu, that can be switched to the actual one at any time. Also a series of 2 minutes intro video will be released soon for each feature.

I hope you enjoyed this article. Try NDepend if you get a chance, you can download a 14-day trial evaluation here. If you instead want a boost during your debugging sessions try LINQBridgeVs, and let me know what you think in the comments below!

See you soon!

Unity Mono Runtime – The Truth about Disposable Value Types

When I started making games using Unity, after almost 10 years of C# development, I was very concerned to acknowledge that foreach loops are highly avoided in Unity because they allocate unnecessary memory on the heap. Personally I love the clean syntax of a foreach. It aids readably and clarity and it also increases the abstraction level. However a very clear and neat explanation of the memory issue problem can be found in a blog article posted on Gamasutra by Wendelin Reich.

From Wendelin’s analysis it emerged that the version of the Mono compiler adopted in Unity has a different behaviour from Microsoft implementation. In particular enumerators, which are usually implemented in the .NET framework as mutable value types, are boxed by the compiler, causing an unnecessary generation of garbage. Boxing is the process of converting a value type (allocated on the stack) into a reference type, thus allocating a new instance on the heap.  Continue reading “Unity Mono Runtime – The Truth about Disposable Value Types”