Yet another geek blog about software development

Main menu

Category Archives: Patterns and Practices

This is probably one of the biggest bullsh*ts people usually tell in the world of software development:

I’ve heard it many times before, and I bet you’ve heard it too. I was unfortunate enough to work for companies where PMs and other people had this mentality, even giving the impression that unit tests were a waste of time. “Just do it quick and dirty” – this was a very common sentence in one of the last companies I worked for.

A lot has been written about unit tests in the last 15 or 20 years, and the advantages should be obvious by now – you can refactor your code with confidence without the fear of breaking existing functionality, you can run unit tests as part of an automated build, and so on.

But there are disadvantages as well – you do need to spend some time to write the test and debug the piece of functionality you’re testing, as obvious. This is usually the excuse given for NOT writing unit tests. But the truth is that we need to test the functionality somehow – it’s not acceptable to write a piece of code without testing it, right? You simply have to test your code, one way or another – even if you don’t use unit tests.

That leaves me with another question – from a development perspective, do you think that the alternatives ways to test your code are faster than writing a unit test? I don’t think so. I still believe that unit testing is the fastest way to do it, if you have a decent enough experience with it (you don’t need to be an expert, though). Let’s analyse the following scenario below.

The scenario – discount calculator

Imagine that you are working on an e-commerce website – the UI is an ASP.NET website that uses a REST API (ASP.NET Web API), where all the business logic is. You need to implement a discount calculator in the API, based on the customer type:

So let’s examine some of the different ways we could test the discount functionality.

1. Testing using the UI (website)

In this scenario you basically need to run the website and the API, and navigate to the page where the discount is being displayed (e.g. view shopping cart). This means that you might eventually need to login, search for a product, add it to the shopping cart and then view the shopping cart in order to check if the discount is correct or not. Also, you need to do it for each customer type.

As you can imagine, this is not the most efficient way to test this functionality. We need to compile and run both the website and the REST API (authenticate user, etc).

2. Testing the API using a REST client

This is more efficient compared to the previous example (testing the UI) because you can skip all the steps mentioned before and invoke the service using a REST client such as Postman or SoapUI. You still need to create sample HTTP requests that might include HTTP headers (content type, authorization, etc), HTTP method and message body (JSON request object).

Depending on the service, it might take a while to configure the requests for each customer type. Also, we need to compile and run the REST API. Remember that in this scenario all we want to do is to calculate the discount for each customer type.

3. Testing using a console application

This is one of the simplest ways to run the test. There’s no need to use the UI to get to the page where the discount is displayed and there’s no need to create HTTP requests in order to invoke the API, i.e. we can test directly the discount functionality using .NET code. Also, console applications are faster to compile and run compared to an ASP.NET website.

4. Testing using an unit test framework

It’s basically as simple and fast as creating a console application – just add add your unit tests to a class library and you’ll be able to run the tests in a few seconds, using Visual Studio built-in functionality or a tool such as Resharper.

Conclusion

Saying “we don’t have time for unit tests” is deceiving. Giving that we need to to test our code somehow, ask yourself if the alternative to unit tests is easier and/or faster (creating a sample console app to run some tests, etc) – I’m pretty sure that in most of the cases the unit testing is the better option.

This is nothing new – if you need to re-throw an exception in a catch block without losing the stack trace you use the throw statement like this:Things are a bit different outside a catch block, though. Consider the following code sample:

This is a very common scenario that I’ve seen in many different places over the last few years – each method has some code wrapped in a try-catch block. To get rid of the code duplication is easy, we can move the try-catch block to a new method that will take a delegate as a parameter (code to be executed):

As you can see, for each model you have an if statement. This works fine if you only need to create 2 or 3 validators but if you need more your code will get bigger and bigger and will be harder to read/maintain. The same applies to switch statements.

The first step to solve this problem is to create a Dictionary to store the validators. The key of the Dictionary will be the type of the model and the value will be a delegate that creates an instance of the validator for that model:

The purpose of the exercise is to write the code incrementally, one step at a time – starting with the simplest case scenario (1 digit numbers) and then adding the code to handle the other scenarios (2 digit numbers, 3 digit numbers, etc).

Assume that the input is valid (number).

Test cases:

1 digit numbers

0 should return “zero”

3 should return “three”

7 should return “seven”

2 digit numbers

10 should return “ten”

14 should return “fourteen”

20 should return “twenty”

21 should return “twenty-one”

56 should return “fifty-six”

3 digit numbers

209 should return “two hundred and nine”

300 should return “three hundred”

417 should return “four hundred and seventeen”

560 should return “five hundred and sixty”

698 should return “six hundred and ninety-eight”

4 digit numbers

3004 should return “three thousand and four”

4000 should return “four thousand”

5020 should return “five thousand and twenty”

6300 should return “six thousand and three hundred”

7111 should return “seven thousand and one hundred and eleven”

5 digit numbers

40000 should return “forty thousand”

70393 should return “seventy thousand and three hundred and ninety-three”

87654 should return “eighty-seven thousand and six hundred and fifty-four”

6 digit numbers

500000 should return “five hundred thousand”

803308 should return “eight hundred and three thousand and three hundred and eight”

999999 should return “nine hundred and ninety-nine thousand and nine hundred and ninety-nine”

You can see my implementation here (I’m using WebStorm v8 and JS Test Driver):

As you can see, I have created to properties HasCategories and HasFormats in the Product class to check if the collections Categories and Formats have any element, respectively.
The following ASP.NET MVC view shows how these properties can be used:

There is a problem with this code though – the properties improve the code readability and can be reused, but you may have dozens or hundreds of classes that may need properties like these. It is a verious tedious and time consuming task to create such properties in all the classes we need – a better option would be to create an extension method to do that work for us.

Extension methods to the rescue

If you take a good look into the HasCategories and HasFormats properties you can see that the code is similar, the only thing that changes is the type of the properties.

We can then create a generic extension method to check if any object that implements IEnumerable (List, etc) is null or empty:

Final thoughts

In short, you can (and should) use extension methods to keep your code DRY.

Basically you need to identity pieces of code that are generic enough and replace them with an extension method, if possible. You will have code that is easier to maintain and also more time to develop other funcionalities.

Step 1: Setting up the container in Global.asax

The first step is to setup Unity Container in Global.asax file. This is a good place to do it because it can be accessed either by web pages or by web services.
The CreateContainer() method is the place where the dependencies are specified.

Composing specifications

Existing specifications can be combined to form more complex ones. Using these extension methods it’s easy to create composite specifications (see this article to understand how to combine lambda expressions):

Using T4 to generate Specification Objects

T4 is a code generator built right into Visual Studio. You can generate any text file using T4 templates: C#, javascript, HTML, XML and many others. If you’ve never heard about it, this is a good place to start:

I’ve created a T4 template that generates automatically all the Specification Objects, one for each entity in our model. All the generated objects have all the public properties of their respective entities, including association properties. All objects were marked with the [Serializable] attribute, so you can easily serialize it if you need.

In a previous article I’ve created query objects for Entity Framework, I’m generating exactly the same properties in this template. You can see a complete description of the generated properties here.

When you save the template file or you rebuild the project the code will be regenerated. If you don’t want to generate the code, remove the value of the Custom Tool property in the property browser of the template file (by default the value is TextTemplatingFileGenerator).