All posts by James

Dependency Injection 101

As developers we are always trying to find ways to make our applications more flexible and tolerant of change. Ideally, we want our components to be modular and reusable. The ability to unit test our code is also becoming a requirement in more and more software development projects.

A technique that can help us in both of those areas is Dependency Injection or DI. DI is a simple pattern where we take elements of our class that would normally be treated as static dependencies and instead we provide an implementation of that dependency at runtime. Consider the following snippet of C# code:

In this case MyDomainClass has a dependency on some sort of data repository. As you can see on line seven, our class is expecting to use a specific implementation of this dependency. While this is something you’ve no doubt seen in many demos, training materials and even in production code, it’s actually not a good idea for several reasons:

  • By declaring our variable of the specific type OracleRepository we are bound to that implementation and have limited the reusability of this code to only situations where Oracle is being used to store data.
  • When we combine the instantiation with the declaration in the class, we have no opportunity to vary what’s being provided as our repository at runtime
  • Static dependencies make unit testing more difficult

Refactoring this to use DI involves two steps. First, I would prefer it if MyDomainClass was dependent on an abstraction of a data repository instead of a specific data repository. This can be accomplished by creating an interface called IDataRepository that serves as an abstraction for a generic data repository and provides definitions of the methods needed to interact with such a repository:


Next, we want OracleRepository to implement the IDataRepository interface:


By doing this we are saying that OracleRepository supports the abstraction represented by IDataRepository and will provide the methods defined in IDataRepository. This means that OracleRepository can be used anywhere my application expects an instance of IDataRepository, such as the instance variable definition in MyDomainClass (line 7):

Now MyDomainClass is a lot more flexible. It can use any data repository that implements the IDataRepository interface. This opens us up to using other types of databases like MS SQL Server or MySql. It even enables us to use things like document databases, file systems or proxies representing web services. As long as the methods in IDataRepository are implemented, MyDomainClass can use it.

But we still have the problem of being statically bound to OracleRepository. This is due to the combination of declaration and instantiation on line seven. This is where DI comes into play. Instead of being statically bound to an implementation of OracleRepository, we are going to “inject” an implementation of IDataRepository at runtime. The easiest way to accomplish this is with “constructor injection” which is a pattern where an implementation
of IDataRepository is provided as a constructor parameter at runtime:

Now we no longer have a static dependency on one type of data store provider. Instead we are dependent on an abstract, for which we will be provided a concrete implementation at runtime. This provides several benefits:

  • We can leverage other types of data stores, so long as their repositories can support the IDataRepository interface
  • MyDomainClass becomes more reusable as it’s no longer dependent on OracleRepository
  • Unit testing is easier as we can provide amocked instance of IDataRepository instead of a concrete implementation.

I hope this post has helped you understand DI a little more. It’s definitely a great pattern to adopt in your software development practices.

Why TDD – A Question

I love TDD. I speak a lot about TDD. During these talks I tend to field a lot of questions. Occasionally someone will say “I’m just not sold on TDD” which isn’t really a question, but begs a response.

For many TDD evangelists, the response to this is to launch into a monologue of all the reasons why TDD is great and why you should use it and all the scary stuff that will happen to you (… up to and including death!) if you don’t use TDD.

This is the wrong approach to bring someone around to TDD. If they are at this point where they can say they aren’t “sold” on the idea, they probably have already heard the speech about TDD before. It didn’t move them then, why should it move them now?

That doesn’t mean that it shouldn’t be addressed. But the first thing to figure out is why someone isn’t sold on TDD. So that’s what I’m doing. Now.

I’ll be working on a series of posts that (I hope) will help people see the light and drink the TDD Kool-Aid. But first I want to know what is keep you from loving TDD. Is it the process? Is it the learning curve? Is it the tooling? Help me help you.

Leave your reason in the comments below, or tweet them to me. I’ll address as many as I can in future posts.

Your Business Card Sucks

You probably know one of the most common cliche lines someone will say during a break up is “It’s not you, it’s me.” Well, this time it’s definitely not ME. It’s YOU. More specifically it’s your business card.

I go to a lot of software development conferences, user group meetings and meet ups and I’ve collected hundreds of business cards. Many are very straight forward; name, title and contact information. Several years ago it was trendy to create an “interesting” business card. Sometimes this was a funny or interesting picture or phrase. Sometimes is was a curious bit of personal information about the person who gave you the card. On occasion is was even weird shapes or sizes.

One of the trends was the off-beat title. It wasn’t good enough to be just a “developer” or a “consultant” anymore. People had to have crazy titles that, it seemed, were more intended to get a laugh than to convey useful information.

I’m not saying the colorful titles are a bad thing. When done well they can certainly differentiate you from the rest of the herd. They can convey a feeling of passion beyond just slinging code. A well crafted title can make you memorable.

But here’s the key; your off-beat, colorful invented title still has to convey to me what you do. When this trend first started I would see titles like “Software Craftsman”, “Bit Herder” or even the occasional “JavaScript Ninja.” I like these. Maybe they are clever, maybe not. But they still convey to me some notion of what it is you actually do.

What. The. Hell?

Lately I’ve started to see a lot more titles like “Web Visionary” and “Awesomeness Instigator” and even a “Thinker in Residence.” I also seem to meet a lot of “Whisperers” who ironically always seem to be the loudest people in the room.

OK, other than screaming that you are likely a giant douche-bag, these titles don’t tell me anything about you or what you do. Well, that’s not quite true; they tell me that you spend WAY too much time trying to think of clever things to call yourself. Not particularly helpful to me.

By the way, the “X Whisperer” thing was played out two years ago. Can we finally make that go away? And can it take “Keep Calm and X On” with it? Can these be done please?

After a conference when I can no longer put a face to a name I need your business card to help me remember you and what you do. If your card says you are the “Chief Donut Consumer at” odds are I’m not going to remember what you actually do, what your skill set is or why I should even care. I’m also unlikely to take time to go to your website and try to figure this out. I’m a very busy man, and, well, Arkham Knight isn’t going to play itself now is it?

The Takeaway

I’m not saying “zany” business cards or interesting titles are bad. The truth is that a well-crafted one will stand out and keep my attention. Heck, it may even get me to follow that person on Twitter. But we need to remember that the purpose of the business card is to be your proxy when you’re gone and the person you gave it to is trying to remember who you are, what you do and why they should care. I’ll take a boring informative card over a clever card that tells me nothing anytime. If you can combine the two, then you’ve got something!

Code Coverage – You’re Doing it Wrong – Part 1

I love TDD. I practice it in my “day-to-day” developer life. I’ve written a book about it and speak about it and conferences everywhere I can. I even did a 30-post series on it for a previous employer. So I tend to get involved in a lot of discussion about TDD, BDD, ATDD and many of the concepts, practices and tools surrounding them. One topic that is paradoxically my most and least favorite is Code Coverage.

For those who may be unfamiliar with Code Coverage, allow me to explain. Developers write unit test that exercise code. These test are run and they either pass or fail. Code Coverage is the process of analyzing those test runs and determining which lines of non-test code are exercised (or run) by the tests. The data collected is generally viewed in two ways; which specific lines of code were exercised by a test and which were not (more on that later) and the percentage of the code base the was exercised.

Death by Numbers

Of the two pieces of data generated by code coverage, management tends to latch onto the percentage of the code base covered as a means of evaluating the effectiveness of the development teams testing efforts. This makes sense. Most managers are trained to work with numbers, manage several teams (making looking at actual lines covered impractical) and in some cases aren’t technical. In these cases, when analyzed correctly, the percentage can be a good metric to track.

The catch is the whole “when analyzed correctly” part. To the uneducated, 100% code coverage sounds like a great goal. The problem is that very little though is put into how that number is arrived at by the code coverage tool.

When Is Your Code Not Your Code?

If you’re a .NET developer you’re probably using some feature of the .NET framework to support your presentation layer; either WPF or ASP.NET. And when you created your WPF or ASP.NET application, Visual Studio helped you out by creating a lot of… stuff. Mostly boilerplate code to handle “frameworkey” things that developers don’t want to deal with. No question; WPF and ASP.NET are HUGE timesavers for software developers.

And they are also the cause of why most software development projects will never reach the “100% code coverage” panacea that many managers crave.

And this is OK. But we need to understand how use of these libraries skews code coverage percentage.

When a developer writes a unit test they are expecting to exercise the code in the method they are testing as well as the code in any private methods on the same class that the public method we are testing uses. And external resources, and ideally any third party frameworks, should be mocked out and not covered by the unit test.

This is logical and what most developers expect. And if we’re writing code that’s not in the presentation project, our code coverage makes sense; the only code in the class or library (generally) is the code we create. And, or course, we would never DREAM of writing code without having a test for it first, right? RIGHT?!

It’s when we get into the presentation project that things get a little complicated. Remember all that code that Visual Studio crated for your to take care of the stuff you didn’t want to do? Well, just because you didn’t write it doesn’t mean it’s not there.

If you’re Test-fu is strong, you are no doubt creating tests for your Controllers/Model/ViewModels/etc. That’s good. But, since you’re generally not running in the same application context during testing that you would be running in during execution, all that boilerplate helper code that was created is never going to be tested. Which means while that code counts toward your “total codebase” (the number of lines of code in your application) they can’t be covered by a unit test.

Even if you could reach it with a test your test context is not going to have the services and facilities the WPF/ASP.NET runtimes need to execute correctly. And even if you could create those services and facilities, you would be flirting pretty heavily with having an integration test (still important!) but you wouldn’t really have a unit test anymore. In any case, trying to cover this code with a unit test is really just not practical.

We Should Probably Just Give Up Now Then, Right?


The problem isn’t the boiler plate code, it’s the way we are measuring the code coverage percentage. Ideally we don’t even want the code coverage tool looking at this code for purposes of determine our “full code base.”

When determining what get’s measured for code coverage metrics we want to exclude the boilerplate code and only check the code that we (as the development team) actually write. We also want to make sure that we that we exclude any source code that ships as part of a framework or library we are using. Most .NET libraries ship as pre-compiled assemblies, but there are some that still ship with a source component, those need to be excluded. Does your application have integration tests? Guess what, those are probably being analyzed by your code coverage tool as well.

The good news that most code coverage tools enable you to exclude code on a project or class level. Some even let you exclude on the method level. As your project continues to grow I recommend that you update your “exclude list” to accommodate new boiler plate code, libraries and tests that will be added to your solution.

By excluding the code you don’t write, your code coverage number should be more inline with the impact of your unit tests on your code. When you are only testing your code, 100% code coverage is very achievable. But what does a number that is less than 100% mean? In my next post on this topic I’ll discuss situations where your code coverage dips, what to do about it, and why it’s not always a bad thing.

Well, that’s A Horrible Idea…

Earlier this week John Chen, CEO of Blackberry wrote this post on the Blackberry blog.

In the post Chen basically hijacks the Net Neutrality argument to bootstrap a justification that the government should enforce “Application/Content Neutrality.” Basically, he wants the government to force mobile application developers and companies who develop applications of iOS and Android to also create the same applications for Blackberry. He points out that while Blackberry makes their BlackBerry Messenger application available for iOS and Android, Apple does not allow non-iOS users to use iChat and other Apple applications. He also seems upset that there is no Netflix application for BlackBerry.

Call me cynical, but this post seems like an attempt to blame everyone else for BlackBerrys misfortunes over the past few years, except for BlackBerry. It’s not us, it’s those jerks at Apple! It’s not us, its Netflix discriminating against our users! It’s not us, it’s those greedy developers who focusing on platforms with the largest users bases!

Sorry, it’s Not the Mobile Developers Fault

In the article Chen cites some numbers attempting to show that BlackBerry is still a widely used mobile platform. And for customers with a specific need for what BlackBerry is selling, it is very popular. But since the iPhone, Android and even Windows Phone have come out, BlackBerry has become a niche product.

So, why aren’t developers writing applications for BlackBerry? Because why would you invest the time in creating something for less than 1%1 of the market when for a similar level of effort you can write an Android application and potentially get 84.4%1 of that market? I’ve never written an application for BlackBerry. From a technical stand point I have no idea what’s involved in creating a BlackBerry application. But at less than 1% of the market, it’s not even worth my time to investigate how I would write a BlackBerry application. Smart developers go where the money is. The money is clearly not in BlackBerry.

Sorry, it’s Not Apple’s Fault

Chen complains that while BlackBerry has made their messaging application open and available on iOS, Apple has not seen fit to reciprocate and make their proprietary applications and services available on other platforms. Is this really a surprise? Apple has never been known for being an open ecosystem. And the fact that you create an application for their platform does not imply a quid pro quo where they will stock your application store with their products.

I may not like or agree with Apple’s closed ecosystem philosophy. But Apple, or any other company for that matter, has a right to package and sell their products and services however they like. You have a right to buy it or not. Apple is under no moral obligation to allow you into their house. And they shouldn’t be.

Sorry, it’s Not Netflix’s Fault

One thing that really seems to be getting under Chen’s skin, based on his post, is that Netflix is “discriminating” against BlackBerry customers by not providing an application for their platform. I think that use of the word “discrimination” is a bit inflammatory and totally unfair here. I don’t know this for a fact, but I highly doubt that Netflix has made a conscious decision to keep people from purchasing their product simply because they use a BlackBerry.

Developing mobile applications cost money. Netflix makes money by having subscribers who use their service. Netflix is a smart company. I have to believe that they have done a cost/benefit analysis of creating an application for BlackBerry. The lack of an application indicates that they found ample reason not to invest in the platform. My guess is that they concluded the number of new subscribers they would receive from creating a BlackBerry application would not justify the cost of creating or maintaining a BlackBerry application.

There are many ways to access Netflix. Aside from the mobile applications you can watch Netflix on a PC. If you have a gaming console there is likely a Netflix application available. My cable box has a Netflix application. And every “Smart TV” I’ve seen includes a Netflix application. If there was really a huge outcry for a Netflix application for BlackBerry, I have to believe Netflix would have created one by now.

Sorry BlackBerry, it’s Your Fault

So who does that leave? Well, unfortunately for Chen, it leaves BlackBerry.

Asking the government to level the playing field is a horrible way to try to save your business. Aside from the fact that it’s akin to asking for a government bailout, it’s unfair to mobile developers and the companies they work for. Forcing companies and developers to create applications for your tiny user base forces them to spend time and resources from which they are not likely to see a profit. Creating this policy of “Application/Content Neutrality” limits the freedom of these developers and companies to conduct their business and make money.

And let’s be clear, this is not a situation where you’re asking the government to break up a monopoly or cartel. BlackBerry was king of the hill at one point. Their lack of innovation has seen iOS and Android take their market share. They aren’t a new company struggling with a barrier to entry. This isn’t a case where companies are colluding to keep the new guy out. BlackBerry got caught flatfooted, made some bad decisions, and now they’re paying for it.

Sorry your market share crashed BlackBerry, but it’s not our fault and it shouldn’t be our problem. You want more applications? Create a compelling platform that can compete with Android and iOS. Don’t force me to write applications for you because of a law; force me to write applications for you because if I don’t I’m leaving a lot of money on the table! If you do this, the applications will come.

One More Thing…

In his blog post, Chen only talked about getting application developers to write applications for BlackBerry. He made no mention of the other application-poor mobile platform; Windows Phone, which sports a 2.9%1 market share.

I am a Windows Phone user. I love my Windows Phone. However, after many years of owning and loving my Windows Phone, I have decided that I’m going to get an iPhone.

This is not because I think iOS is superior to Windows Phone. To be sure there are many things I’m going to miss about my Windows Phone. But after more than three years, I’ve decided that I’m tired of not having access to the mobile applications I want. I’ve waiting and been patient, but the applications have not come.

Why do I bring this up? Because you could argue that Microsoft is facing the same issues with Windows Phone that BlackBerry has. Yet Microsoft has not responded by crying to the government about how unfair things are. Microsoft is trying to make their platform more attractive, thus increasing their market share. Earlier this week Microsoft showed some of the new features for Windows 10, including many features for the Phone version of the operating system. It’s clear they are working hard to create features that users want to try to get them to switch. Will it work? I don’t know. But I applaud their approach and I think BlackBerry could learn a lot by watching them.

1 –

Hey, where’s all the old content?

Heh, funny story….

Through a weird conflux of events, the old content has been “lost.”

This is partly to blame on my former hosting provider (who shall remain nameless, unless you see me in person and buy me a beer or two) for not keeping track of my PROPER email contact information, even though I told them a couple dozen times they had the wrong email address.

It’s also partly my fault for lacking the omniscient skills required to know they were sending emails of a “Please contact us NOW or we’re going to nuke all your data.” to an email address that as far as I know doesn’t even exist.

So, it looks like things are gonna be starting over here on Bender’s Blog. And that’s fine. Every so often you have to clean out the old crap and start new. Some of the old content is still cached on Google and all the stuff I did for my previous employer (the one with the Ninja) still seems to be up on their site. If you come across any of this stuff and have questions or comments please feel free to let me know.