Subscribe to my feed

As part of my tasks at Verizon Business I’ll be evangelizing about Test-Driven Development, due to some teams in my area are interested into implement this wonderful technique but they never use it before. This is very positive, I think, because they usually take care about the quality of his work and the use of TDD helps a lot with this task.

Doing some research to prepare my presentations I found that lot of people has the wrong idea that if they work with TDD they will be losing time. They has the crazy idea that if they don’t write tests they are saving time, they see the write of tests as and expense rather than an investment.

If I don’t use TDD I’ll have the things faster

To believe that if you don’t use TDD you will have the things faster is a big mistake. First of all, to compare velocity and times of different processes the outcome of these must be the same for all. This belief is assuming that the result will be the same with or without TDD and that’s simply wrong. TDD brings a lot of benefits: clean and decoupled code, reduced use of debug, and the most important: certainty.

It is true for the short-term, if don’t write tests and you go directly to the implementation you probably (at least in trivial cases) got the code written faster that if you use TDD.

In the other hand, you should see the things for the long-term, and if you have experience working at the software industry you will probably know that a big problem at many software projects is the rework (I recommend you to read this paper about software quality and the cost of rework). The certainty that TDD brings to you will make you to avoid a lot of rework and debugging or at least make it easier.

A picture worth more than thousand words:

roulette-table

In a few words, working without TDD seems like gambling, you can win a lot and faster, it is very tempting, but due to the uncertainty there is a lot losing possibilities: risk.

TDD will not solve the changing requirements problem, it will not solve the existence of functional bugs due to requirements misunderstanding, etc, what I’m trying to say is that TDD will not eliminate the risk inherent to any software project, but It will reduce it, at least a little, providing a little of certainty.

Continuing with the analogy, using TDD is like gambling but cheating (having a little more of certainty)…

 B0016IXMPU!w234

Regards!

In order to create maintainable and flexible architectures you must start to split your code responsibilities into several components, each of them with a single responsibility, but also low coupled.

Let me show you what it means. To make it clear lets choose a common scenario:

di.components1

UsersRepository is a component that has the responsibility of Users persistence and storage, and UserService is a component that has the responsibility of applying business rules, like validation for example. As you can see in the diagram UsersService maintains a dependency with UsersRepository, this is how it looks in the code:

di.usersrepository1

di.usersservice1

This is a poor design, due that it creates a hard dependency between both components and that’s no good for maintain and test reasons.

It’s clear that this hard dependency will create problems at maintain time, or if we need to do changes, in the other hand if you work with TDD, or you just want to use automated tests, you probably should test each component separately. This means to test the UsersService without testing the UsersRepository and vice versa.

Let’s start to decouple these components, to do that I need to introduce to you the Design by contract approach. We will start by creating an interface for the UsersRepository that will act as contract. The UsersService will use the UserRepository through this contract:

IUsersRepository 

By using a contract we are changing the rules of the game, instead of using the component we are using his functionality through an interface. It means that if we need to migrate our repository from ADO.NET to LinqToSQL or instead of use a database to save our objects we use xml files or webservices or whatever, we just need to create a component that implements this contract and change only one line of code in the service. Let me show you how looks the service with this new design:

di.usersrepository2

We did it. We have removed the hard dependency, and now our components are low coupled. This is our UML components diagram updated:

di.components2 

Ok, now let’s take it to the next level, by making the UsersService friendly for unit tests, to allow test it without testing the UsersRepository. We need a mechanism that allow us to replace the real UserRepository for an mock in testing time. Let me quote Martin Fowler, from his article Mocks aren’t Stubs:

A mock is and objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Here is where dependency injection comes to play. Dependency injection, also known as Inversion of Control, is a great solution to create testable components and his implementation is really simple. We just need to provide a constructor that accepts an IUsersRepository as parameter, and also, for practical reasons, a default constructor with the default implementation. This is how it looks:

di.usersservice3

Note that the constructor that provides the dependency injection ability is marked as internal. This is because we don’t want to any body from any where be able to use it, from outside they will only view the public constructor, that constructs the service using the default implementation.

Here goes one little trick: to make your internal types visible form other assembly, like a test project, you need to add this line in your AssemblyInfo.cs file:

InternalsVisiblesTo

Just replace “DependencyInjection.Service.Test” by your test project and it’s done.

That’s all, now our components are low coupled, and also we have a testable UsersService, we can even test and create (note I said test before create) our UsersService without have the real implementation of the UsersRepository,  and it is just how it must be.

Hope be useful!

I’ve this problem a thousand times: How to explain to your manager or to any not developer person that you are expending working time on improve your code quality? The only clue that this not developer person may has about you are saying the true it’s if your code quality improvement also was a performance improvement, and they can feel it when running the application, but it not always happen.

One lesson I’ve learned from TDD is the fact that any objective you take must be testable, verifiable or measurable. With code quality is the same, we are engineers (or we’ll be some day) so we need metrics, but first we need to define a quality bar.

Through my admired college Johnny Halife I’ve meet Eric Brechner. Johnny is the Engineering Excellence Director at Southworks and Eric has the same position at Microsoft. The book I. M. Wright’s Hard Code from Eric Brechner about software quality is a must read for any software engineer.

I was reading this post from Eric’s blog when I’ve the idea of writing this one. Eric says something I’ve heard from he before, let me quote his post:

The two keys to successful big projects (100K+ LOC) are thinking ahead and defining done. Thinking ahead is about design and planning. Defining done is about setting a quality bar and sticking to it.

That’s exactly the first thing you must do, define a quality bar and stick to it.

Before you continue reading, the next section is specific about Microsoft .NET platform. In my next lines I’ll show you three quality code metrics that you can take and an example of this quality bar.

I met this tools working at Southworks, at that time we worked with Microsoft teams and we shipped architectonical and code samples of using Microsoft latest technologies, so as you can imagine our quality bar was high.

1. Source Analysis: Defining an automated code standard.

I’ve seen many times people writing standards of naming conventions for methods, types, variables, etc. The result of that is a 400 pages document with standards that no one developer will read before start coding, that’s not agile at all.

The first tool I want to share with you it’s called Microsoft StyleCop. It’s a free tool developed by Microsoft that has the ability of analyze your code in order to maintain an unified style. Let me show you how it works.

You can download and installed it for free, and a nice “Run StyleCop” option will appear by click right button over a project or solution.

sa

Once you’ve run StyleCop you will see the warnings in the error list panel.

sa.results

Just fix this warnings and your code will be StyleCop compliant, this means that all your code will be standardized. It can be hard at begin, but with time you will learn the StyleCop rules and you will code StyleCop compliant.

So there you have your first code quality metric, Source Analysis. Now you can say to your manager “hey, my code has quality because is standarized, it has 0 Source Analysis Warnings/Errors”

2. Code Analysis: Ensuring Microsoft .NET best practices

As I say before, many people lost time writing and writing standards for coding. Please don’t reinvent the wheel, Microsoft has his own 480 pages standard and is published on Amazon, It’s called Framework Design Guidelines and it goes by his second edition. The authors of this book work and worked in the .NET framework development. Through this book they share his experiences and define a naming convention, idioms and patterns to work with the .NET framework in the best way.

Great! we don’t need to write the standard, but we still had the problem that buy this book and read 480 pages before start working is not agile at all. To avoid this Microsoft provide us a cousin of StyleCop, It’s called FxCop.

Just like StyleCop, FxCop is a free tool developed by Microsoft that has the ability of analyze your code, and your design in order to make it fit with the  Framework Design Guidelines idioms and patterns, It will report possible improvements in areas like performance, security, design and localization.

ca

FxCop, also know as Code Analysis, will ensure you that you are using the .NET framework in the best way possible. This is how a result of code analysis looks:

ca.results

If you want to know why FxCop recommends this changes you can go to the book and find the answer, but you don’t have to read all the book before start coding. As bonus you will learn to use better the .NET framework.

FxCop is included in Visual Studio 2008 SP1, but you can download it separately here.

So, that’s your second quality metric, Code Analysis. Now you can say “hey, I’ve been working to increase our code quality, we had 100 CA Errors, and now we have 0 CA Errors, this means our code is more secured, has a better performance, and has a better design”

3. Code Coverage: If is covered is tested

Code coverage is a metric that will ensure the maintainability of your code. It’s basically the percentage of your code that is covered by automated tests.

The code coverage tool is integrated with Visual Studio 2008.

cc

This is how Code Coverage results looks:

cc.results

A way of maintain a good CC is to work with TDD.

So, that’s all, SA, CA and CC, three metrics to measure your code quality. Now you can define your quality bar as: “0 SA, 0 CA and 85% > CC”, that’s an idea…

Conclusion

By using this tools maintain a good code quality do not requires of writing or reading largest documents or have high technical skills. Code quality is very important because it will be the key of the development and maintainability of your project.

And remember, keep it simple, code quality is something very important in any kind of project. Code quality by itself cannot define the success of your software project, but it can define the failure of it.

One more thing, be carefully, all this is about code quality, no software quality. Software quality is about requirements and if we fit them right or don’t, performance and another kind of things.

Hope you like it!