Ok. You are probably new to async and await or maybe you aren’t new but you’ve never deep dived into it. You may not understand some simple truths:

aync/await does NOT give you parallelism for free.

Tasks are not necessary parallel. They can be if you code them to be.

The recommendation “You should always use await” is not really true when you want parallelism, but is still sort of true.

Task.WhenAll is both parallel and async.

Task.WaitAll only parallel.

Here is a sample project that will help you learn.

There is more to learn in the comments. There is more to learn by running this.

Note: I used Visual Studio 2017 and compiled with .Net 7.1, which required that I go to the project properties | Build | Advanced | Language Version and set the language to C# 7.1 or C# latest minor version.

Often, a solution may have both Unit Tests and Integration Tests. Unit Tests should be highly specific, and should be testing one class object. Integration Test could be vastly more complex and could use Selenium, or require a real database server, etc. Even if a solution doesn’t have Integration Tests, it may have slow Unit Tests. For example, I have a test that takes about 2 minutes to run because it is testing that when creating 10 million random strings, the character distribution is pretty equal.

I don’t want to either slow Unit Tests or Integration Tests to run every single time I build on my local dev box. I do have an automated build system and builds kick off on check-in. At that time, these slow tests will run every time. But locally, it is just an unnecessary delay.

Usually I am writing in a specific project and that project has specific tests and I can easily choose to only run tests in my current project. But what if I am updating a library that many projects use. I want to know quickly if anything is broke, so I need to run most of the tests in the entire solution.

Visual Studio allows for tests to be tagged with a TestCategoryAttribute.

You can mark different tests with different names: [TestCategory(“Slow”)], [TestCategory(“Integration”)], [TestCategory(“Performance”)], [TestCategory(“Selenium”)]

All other tests are left without a test category. Now, if you want to run all tests that aren’t slow, you can do this in Visual Studio Test Explorer by grouping tests using the “Traits” selection option. Once you have marked all tests with an appropriate TestCategoryAttribute, you can sort by Trait. Now it is simple to click-to-highlight the No Traits group and click Run | Selected Tests.

Dependency Injection makes the claim that a concrete implementation of an interface is going to change. The problem is that theory rarely meets reality. In reality, there usually exists one single concrete implementation of most interfaces. Usually there exists one Test implementation. Other than those two concrete interfaces, a second production implementation of an interface almost never exists. When there are multiple concrete implementations of an interface, it is usually in a plugin situation and is handled differently, using plugin loading technology. So we can exclude plugin scenarios, whether UI or other, and focus on day-to-day dependency injection.

In some projects, 100% of the objects have a single production implementation and a single test implementation. Other projects, you may see 90%/10%, but again, rarely are their multiple.

In other projects, you will find a second production concrete implementation, but it is replaces the previous implementation, not running alongside it.

So why are we not coding to the common case?

Construction Injection

Constructor Injection assumes a few things:

Your class should not even instantiate without something injected into the constructor.

It sounds great in theory, but in practice, it usually leads to constructor injection hell. If you are wondering what Constructor Injection hell is, have a look at this previous post: Constructor Injection Hell.

Property Injection Issues

Property Injection or Method injection are also assuming a few statements are true.

Your class can be instantiated without something injected into the constructor.

Your methods should throw exceptions if a required property has not yet been injected.

Dependency Injection Problems

Should You Stop Using Dependency Injection

So now that you’ve been educated on the truth that theory and reality never mix, and most of Dependency Injection is a waste of time, let me tell you: Keep doing it because you still will benefit from Dependency Injection.

Don’t stop doing it, but instead add to it a simple pattern. The Custom or Default pattern.

Custom or Default Pattern

This pattern is so simple that I cannot even find it mentioned in any list of software development patterns. It is so simple and obvious, that nobody talks about it. But let’s talk about it anyway.

Make everything have a default value/implementation. If a custom implementation is supplied use it, otherwise use the default.

It is a simple pattern where all the Dependency Injection rules are simplified into two:

Your class should instantiate without something injected into the constructor.

However, you didn’t solve Constructor Injection hell. You could solve that with a Service Locator. Here is the same pattern with a Service Locator. I’ll only do one Service Locator example, though it could be done a few ways.

Many developers will immediately react and say that both example result in coupled code. SomeObjectWithDependencies becomes coupled to DefaultDoer or ServiceLocator.

Well, in theory, this is coupling. Your code will never compile, the earth will stop moving, you will rue the day you made this coupling, and your children will be cursed for generations, blah, blah, blah. Again, theory and reality aren’t friends. The code always compiles. The coupling is very light. Remember, it is only coupled to a default. You have now implemented the Custom or Default pattern. With one line of code, you solved a serious problem: With regular Dependency Injection, your code doesn’t work without an injected dependency.

Guess what, you had coupling anyway. Usually you had to spin up some third library, a controller or starter of some sort, that hosted your dependency injection container, and then you had to couple the two objects of code together and now you have an entire third library just to keep two classes from being friends.

The above is still very loose coupling. It is only coupling a default. It still allows for a non-default concrete implementation to be injected.

Property Injection with the Custom or Default Pattern (Preferred)

This pattern could be implemented with Property Injection. However, this pattern suddenly becomes extremely awesome. It is no longer just a standard property. It becomes a Lazy Injectable Property.

A Lazy Injectable Property becomes key to solving most of your Constructor Injection hell. Since it is very rare that a implementation other than the default is ever used, it is extremely rare that a Dependency Injection container is ever really needed to inject a dependency. You will find yourself doing Dependency Injection with a container.

The dictionary is dynamic, based on the passed in parameters, so we have to build it dynamically.

The parameters are dynamic so we call the method with reflection to allow for dynamic parameters.

The dictionary still completely eliminates Cyclomatic Complexity. Notice all the Cyclomatic Complexity is gone. This code never branches. There is very little to test.

There is the overhead of creating a Dictionary and the overhead of reflection, but again, unless you plan to use this for looping through large data sets, the performance difference is negligible.

Dictionary<TKey, Func<>>

Sometimes there isn’t much common at all. Sometimes, the complexities very greatly.

// ... code here

Imagine the code that goes there is vastly different. Imagine you just can’t find much common ground. In these situations, you can use Dictionary<TKey, Func<>>. The pattern is to put the dictionary in its own class file. Then the object that uses it can have an injectable IDictionary<TKey, Func<>>. Injection options are: Constructor injection, Method injection, property injection. I lean toward a property injection variation called a Lazy Injectable Property.

Question: What generic paramaters should be used for the Dictionary? Answer: The TKey is clearly the type of the val property, which in the example is an int.

Question: What generic parameters should be used for the Func<>? Answer: Well, you need to think through to get this answer. First, you need to find the Lowest Common Parameter Set. Second you need to check the return type.

Finding the Lowest Common Parameter Set

If you look at one of the above methods, you can easily get the lowest common parameter set by writing down each and every parameter pass in. Remember this one from above?

In all the previous methods, we resolved Cyclomatic Complexity by taking a method with 8 branches, and reducing that 1 method to 0 branches. We can also get 100% code coverage with 1 unit test.

1, Methods 0, Cyclomatic Complexity

In this final Dictionary<TKey, Func<>> example, we end up with 8 methods that need testing.

8, Methods 0, Cyclomatic Complexity

The reason is that we still have to test all 8 methods in the FuncDictionary. However, when that work was in the switch/case statement, those were harder to isolate for unit tests. Now, all eight methods are isolated and unit tests are simplified.

Model classes have properties and nothing more. Note: Properties are basically getter and setter methods. In languages without properties, getters and setters are the equivalent. Do not use getter or setter methods as methods for anything more complex than default instantiation of the type. Example: You can make sure a List is not null in a getter and lazy load it, but don’t do much more. Or a calculated property might have minor logic but it is all internal to the model.

Any class with methods can reference primitives, collections and lists, interfaces, and model classes. Do not referencing a class with methods directly from any other class.

10/100 Rule (Slightly bendable rule). No method should have more than 10 lines of code, including curly braces and comments. No Class should be more than 100 lines of code, including curly braces and comments.

Look, there is S.O.L.I.D., there is D.R.Y, there is S.R.P., and many other rules. There are design patterns, including the gang of four patterns, and many others. There are architectures, MVC, MVVM, etc. But if you, as a software developer, follow the above three rules, you will automatically end up following most of the other rules. Design patterns will naturally be used in your code, even if you don’t know them, though I recommend you still learn and know about them.

Today I needed to backup a single database table, then test a change to the data, then if the change failed, restore the original data.

Below is how I did this.

What I used

I used SQL Server Management Studio to do all of the following steps. I performed the steps on a database running on a SQL 2012 database server.

Part 1 – Backup the table

SELECT *
INTO MyTable_Bak
FROM MyTable;

Note: This will work usually, however, it won’t work if you have a calculated column. If you have a calculated column, create the table first, then specify the columns you are inserting. I didn’t have a calculated column, so I didn’t take time to figure this out.

So I am a fan of dependency injection (DI), inversion of control (IoC), and the way DI and IoC allow for simplistic methods and Unit Tests. With DI, you can do method injection, property injection, or constructor injection. I don’t care which one a project uses, as long as they keep it simple.

Constructor Injection

This article is focussing on constructor injection. Constructor injection seems to be very popular, if not the most popular method of DI. Constructor Injection is considered to have a benefit because it requires the instantiator to provide all the dependencies an object needs in order to create an instance of it.

An Example of Constructor Injection Hell

Recently, I started working with NopCommerce, which uses DI heavily. They use Autofac and register objects with Autofac so it can provide concrete instances of any interfaces.

I am going to use NopCommerce as an example of what not to do. Now before I do this, I want to explain that NopCommerce overall has a very good architecture. Better than most. Finding something that I consider a “what not to do” in a project should not steer you away from NopCommerce. In fact, their plugin model and architecture works quite well.

Below is an example of constructor injection gone wrong from the OrderProcessingService.cs file in NopCommerce.

Problems in the Constructor Injection Implementation

So what is wrong with the above constructor? Well, a lot. Look, this is just bad code. While constructor injection is a good idea, taking it to this extreme is not a good idea. In fact, it is a terrible idea.

The Constructor breaks the 10/100 rule. The constructor, with comments, method parameters, and method body is 126 lines of code. The method itself is far more than 10 lines of code, it is 39 lines of parameters and 39 more lines of member assignments, and is 80 lines of code.

The Constructor breaks the keep it super simple (KISS) principle. Having to new up 39 concrete instances of the parameters in order to create an object is not simple. Imagine mocking 39 interface parameters in a Unit Test. Ugh!

This constructor is a hint that the entire class is doing too much. The class is 3099 lines and clearly breaks the single responsibility principle. It is not the OrderProcessingService’s responsibility to store 39 dependent services.

The constructor breaks the Don’t Repeat Yourself (DRY) principle. Almost all other classes in NopCommerce use constructor injection to access services.

Options for Refactoring

Option 1 – Container object

You could create a container that has all of these dependecies, a dependency model object for the OrderProcessingService. This object would house the 39 dependent services and settings. But Option 2 would be better.

Option 2 – Accessor objects

Looking at this from the Single Responsibility Principle, shouldn’t there be one class and interface, a ServiceAccessor : IServiceAccessor that allows one to access any dependent service? Instead of passing in 30 services, wouldn’t it make more sense to pass in a single object called a ServiceAccessor that implements IServiceAccessor? Should there be a ServiceAccessor of some sort? Turns out there is a static: EngineContext.Current.Resolve(). Since it is a static, maybe you could wrap it in a ServiceAccessor : IServiceAccessor object.

There are also a lot of “settings” objects passed into the constructor? Shouldn’t there be a SettingsService? Well, there is. One can pass in the ISettingsService and then call _settingService.LoadSetting().

Instead of passing in 39 parameters, methods with a single responsibility to fetch a service should be used.

Option 3 – Refactor the class

Since the class is 3099 lines. If the class were broken into logical pieces, naturally, the constructor for each smaller piece would have less parameters.

This article isn’t about unit testing an extension method. That is pretty straight forward. This article is about unit testing and object that calls an extension method where the extension method is difficult to test. Likely the method is difficult to test because it touches an external system, such as a database or a remote web service.

If you have an extension method that is simple and doesn’t touch and external system, it is easy to unit test. Look at the example below. There is nothing blocking you from Unit Testing code that calls this method.

You need Unit Tests for SomeFunction(). Imagine that all other code is 100% unit tested. But you are struggling with how to Unit Test SomeFunction because it has two dependencies:

MyObject

DoWork

The Unit Tests should not call the real DoWork because it does really complex stuff and touches external systems. However, you need the parent method to provide a valid return value.

Well, you could just drop the ExcludeFromCodeCoverageAttribute on the method and move on. But what if there are a half-dozen other objects that call the parent method that also need to be tested and they need a return value from SomeFunction()? It would be best to solve this in this object as so you only change one class file, not a half-dozen.

One option to resolve this is to use dependency injection. Dependency Injection (DI) simply means that any dependencies can be injected. When some people hear DI, they think they immediately need the huge overhead of an IoC Container. IoC containers are nice and have their uses. But using an IoC container only to allow unit tests substitute a dependency is a huge overkill. If your project already has an IoC container, feel free to use it. Otherwise, I recommend you use a simpler option. I prefer an internal lazy injectable property.

Creating a Lazy Injectable Property

An internal lazy injectable property is a property that is instantiated on first use if it is null, but always for code with internal access to swap out the property value. Here is the syntax:

Note: This assumes your unit tests references your project already, has InternalsVisibleTo configured, and has Moq from NuGet applied to the test project.

Look how simple the above code is. If _MyObject is null, the first time MyObjectProperty is called, it is instantiated to a new MyObject().It is internal because only the unit test will every replace it. I don’t really want this property exposed elsewhere. We can use InternalsVisibleTo to allow the Unit Tests access.Now my ObjectUnderTest will look like this:

However, it is questionable whether this is even necessary. Does MyObject do anything that requires this level of abstraction? Not in this example. It isn’t the object itself that is complex, it is the extension method that really needs to be injectable.

Creating a Lazy Injectable Property for a method

You might be asking yourself, “What about the extension method? It is a method not an object. How can I inject that?” Well, you can. Remember, even methods can be treated as objects. The answer doesn’t change much. The only difference is understanding how to treat a method as an object.You can objectify methods using multiple objects such as Action, Func, Predicate, delegate, etc. I am not going to go into how to do that here beyond the minimal needed to accomplish this task.

Quick tip: Use Action for void methods, Predicate for methods return bool, Func for methods with any return value, delegate if you have ref or out paramters.

Here are the steps:

Create the following Lazy Injectable Property inside ObjectUnderTest:

Note: I am using Func because it has a return value of object. (See the Quick Tip a few lines up.) Since I have two paramters and a return type, I will specifically use the generic Func.

You are now 100% covered. The only code we can’t cover is the lambda call to obj.DoWork because we can’t Unit Test that as it touches an external system. Which is why we marked it with the ExcludeFromCodeCoverageAttribute.

If you create a static Dictionary in code, every time you need to change the dictionary, you have change code, recompile, and redeploy. Wouldn’t it be nice if you didn’t have to change code. What if you could create your dictionary in an Xml file and deserialize it. You can now make the change outside of code.

Code generation is the idea of having a tool write code written for you. If you use a modern IDE, such Visual Studio, you likely use a type of code generation, even if you think you don’t.

Anytime code is written for you, it is code generation. You use code generation whenever you do the following:

Create a new solution or project – Each project is a template with a base set of code ready for you to use.

Add a new class, interface, or another item to a project – When adding a new class to a project, the class comes with a pre-created class object. If you add a new class called Person, the following class file would be created and added to the project:

The using statements are lines of code. The namespace and class definitions and the brackets are lines of code. You get 11 lines of code not including the whitespace lines. This code was created for you because you didn’t have to write it. That doesn’t mean it is 100% useful. If you don’t use threading, the last using statement can be removed.

Similarly, other items that are added have a base set of code.

Use code snippets – Code Snippets are quite powerful. With a few characters and then the tab key twice, you can create a lot of code. There are many built-in code snippets. If you are using them, you should be.

Other Visual Studio features – Visual Studio has some specific use cases where it provides code generation. For example, if you highlight a class name and choose Extract Interface, Visual Studio will generate and interface from the

Plugins and 3rd party tools – Many plugins can generate code for you. For example, Resharper can do numerous code generation features, such as properly overriding the Equals method. ORMs, such as Entity Framework, have code generation tools. Entity Framework can generate most the Entities (class files that represent objects stored in database tables) for you.

You can enhance the code generation tools

Most of these features are available as platforms for you to build upon. Enhancing these can be a simple as copying an existing item or as complex as developing your own product.

In Visual Studio, you can do any of the following: (listed in order of ease of use)

Create your own snippets.

Create your own class/item templates

Download or purchase additional code generation plugins

Create your own Project/Solution templates

Create your own Visual Studio plugins/3rd party tools

If you are repeatedly writing the same code over an over again, you probably would benefit from creating a code generation solution.

Faster and higher Quality

When a human writes something, there is room for human error. If a person writes the same thing over and over, there is a tendency to minimize and cut corners. Also, there are many standard pieces of code that have already gone through significant use and bug fixes resulting in a stable and scalable piece of code. For example, overriding Equals in a class isn’t always straight forward. If you do it yourself, you might be left wondering if you have properly overridden Equals of if your implementation has well-known bugs? Do you leave those bugs in or research and fix them? If you research and fix them, how long will it take you each time you override Equals to make sure you accounted for all well-known bugs? However, if you use a generator with a standard, tested, and bug-free piece of code, your code will be higher quality and it will be created almost instantly. See, faster and higher quality.

I am hoping to have time to create a series of posts on this topic, starting with Snippets. But to get you started, check out my Visual Studio snippets for C# on GitHub.

Some developers like to write one line of code for complex tasks. It’s called code golf and there is a whole subdomain on StackExchange dedicated to code golf. Also, I have seen an idea mentioned on some forums that you should never have a method that is a single line of code. I am going to challenge that statement and suggest that when a single line of code is difficult to understand, wrapping it in a method for the sole purpose of readability is a good practice to follow.

But I am not going to dictate my personal preference onto other developers. That is not the point of this article. The point of this article is to talk about the benefit of a method for the sole purpose of documentation and making the code more readable. Besides, there are hundreds of other single lines of code that are difficult to understand. Thanks to Linq alone, C# now has plenty of examples. But this isn’t just a C# concept. This concept work in C++, Java, JavaScript, or any language. This concept is language agnostic.

So to start with, what is the above code doing? Can you tell from this line of code? I couldn’t at first glance. I had to examine it further. Who wrote this. (Hopefully, it wasn’t me two years ago. It probably was.)

Well, my ORM has Products and each product has a list of Features. My WebService also has Products and each Product has a list of Features. However, the ORM Product and Feature classes are not the same object types as the WebService Product and Feature classes. They are different objects in different namespaces. So basically, this code gets the list of features foreach product from the database and converts the features to a WebService Feature type, puts them in a list and assigns them to the WebService Product type’s feature list.

Wait, why did I have to explain that to you. Why didn’t you simply know what the code did? Because the code is not self-explanatory. Is is not easy to read or understand.

What if instead of our embedding our loop in our current code, we created and called this method instead?

Basically, we encapsulate (did I just use the term encapsulation outside of a CS 101 course) the complex code in a method and use the method instead.

GetFeaturesFromDatabase(dbContext, wsProducts);

Is that not clearer and easier to read?

But should we do this?

Let’s assume that our code already uses dependency injection and we already can mock the dbContext, and our code already has Unit Tests that are passing. So we don’t really need this method for any other reason other than documentation.

My answer is YES! Yes, using a method for the sole purpose making the code self-documenting and easier to read is worth it.

Note: UserType.Contact and User.System are enums in the above example.

INSERT INTO … SELECT with Entity Framework

Imagine you have these three tables. Product, ProductGroup, ProductGroupMembership. You want to make Products a member of a group by inserting into the ProductGroupMembership table.

INSERT INTO ProductGroupMembership (ProductId, GroupId, CreateDate, CreatedBy)
SELECT Id, @GroupId, GetDate(), @CreatedBy FROM Product
WHERE Id IN (1, 2, 3, 4, 5) -- there could be hundreds or thousands of numbers in the IN statement

EPIC FAIL!!! Can't be done without raw sql and opening up to sql injection attacks.

However, you can create a stored procedure that takes and user-defined table called ArrayOfInt. Then add EntityFrameworkExtras.EF6, which is available as a NuGet package, to call the storedprocedure and pass it an array.

WHERE with many AND/ORs with Entity Framework

Imagine you have these three tables. Product, ProductGroup, ProductGroupMembership. You want to make Products a member of a group by inserting into the ProductGroupMembership table.

You have a list of software Products provided to you. However, the input only includes Product.Name and Product.Version. You now need to check if the products exist and get the id.

SELECT Id FROM Product
WHERE (Name = 'Product 1' AND Version = '10.0')
WHERE (Name = 'Product 2' AND Version = '10.0')
WHERE (Name = 'Product 3' AND Version = '10.1')
WHERE (Name = 'Product 4' AND Version = '10.0')
WHERE (Name = 'Product 5' AND Version = '1.0')

EPIC FAIL!!! Can't be done without raw sql

However, you can add LinqKit’s PredicateBuilder to do this. PredicateBuilder works on top of Entity Framework and is available as a NuGet package. See how I used it here: Entity Framework and many WHERE clauses

My other blogs

Entries (RSS) and Comments (RSS). Copyright ® Rhyous.com Linking to content on this site is allowed without permission and as many as ten lines of any article can be used along with such link. Any other use of the content is allowed only by permission of Rhyous.com.