Category Archives: Tutorials

Dependency Injection and Inversion of Control are not rocket surgery

I see a lot of people talking about how “advanced” techniques like dependency injection and inversion of control are and how their team won’t understand either technique.

 

Folks, this isn’t hard. In fact, both of these things are so simple I simply call it “using the programming language”.

 

Let’s look at dependency injection.

    public class MyClass
    {
        private DataTableReader _reader;
        public MyClass()
        {
            _reader = new DataTableReader(new DataTable());
        }
        private void DoStuffWithTheReader()
        {
            while (_reader.Read())
            {
                //do fun stuff with the reader.
            }
        }
    }  

See the reader variable? That’s a dependency. You have to have it in there to do fun things later on. But we have to create it ourselves, which is one more thing that we have to do in our class constructor. In reality we also have to populate the DataTable. So what if we make the reader variable constructor parameter so that another class can do the work of creating the DataTable and the reader?

    public class MyClass
    {
        private DataTableReader _reader;
        public MyClass(DataTableReader dataTableReader)
        {
            _reader = dataTableReader;
        }
        private void DoStuffWithTheReader()
        {
            while (_reader.Read())
            {
                //do fun stuff with the reader.
            }
        }
    }

There, that’s better. Now our class doesn’t have to worry about creating the reader and the DataTable. This, in a nutshell, is dependency injection. It’s not very complicated is it? We’ve made our class construction a little simpler and if we want to unit test this, we don’t have to do any complicated mocking, we can just new up our own DataTableReader instance and populate it with whatever test data we want. If you run into any funny looking data in the DoStuffWithTheReader method, you know that you don’t have to look in this class at all to see where the funny data is coming from, only in whatever method is creating this class and passing in the DataTableReader.

Now is there anyone who thinks that developers on their team would have trouble understanding passing in a parameter? Should they really be a developer if they do?
Honestly, it's not that hard.

Ok, so let’s look at inversion of control. The original definition of inversion of control I read was by Martin Fowler:

There’s a big difference now in the flow of control between these programs – in particular the control of when the process_name and process_quest methods are called. In the command line form I control when these methods are called, but in the window example I don’t. Instead I hand control over to the windowing system (with the Tk.mainloop command). It then decides when to call my methods, based on the bindings I made when creating the form. The control is inverted – it calls me rather me calling the framework. This phenomenon is Inversion of Control (also known as the Hollywood Principle – “Don’t call us, we’ll call you”).

If you look at the previous example, you’ll see that we have already inverted the control a bit just by using dependency injection. But the class still has a degree of control over WHAT concrete object is created, in this case a DataTableReader. What if we need to switch over to a SqlDataReader or an OleDbDataReader? Well, we could create three other classes that all take the specific type of data reader we might want to use. But that’s a bad idea, you end up with the same logic spread all over the place. Instead we can use the IDataReader interface that all three classes implement.

    public class MyClass
    {
        private IDataReader _reader;

        public MyClass(IDataReader dataTableReader)
        {
            _reader = dataTableReader;
        }
        private void DoStuffWithTheReader()
        {
            while (_reader.Read())
            {
                //do fun stuff with the reader.
            }
        }
    }

Now our class not only doesn’t have to worry about creating the DataTableReader, it doesn’t even really care if it gets a DataTableReader at all. All it cares about is that the reader is referencing something that implements the IDataReader interface. This is a type of inversion of control. Most of the time people get confused between inversion of control and a container that enables inversion of control and dependency injection (like Ninject, StructureMap or Unity). You don’t have to use a container to utilize these two techniques, it just makes it a little easier.

update:Also check out this great post “It’s all about the delivery

update: I mistakingly thought it was hard to do D.I. in Python due to the inheritance mechanism in Python. Turns out, it’s just as easy.

class MyClass():

    def __init__(self, dataTableReader):
        self._reader = dataTableReader
        
    def DoStuffWithTheReader(self):
        while(self._reader.Read()):
            #Do Fun Stuff with the reader.
            print(self._reader.item)

Mocks versus stubs and fakes

I dislike using mocks I dislike using dynamic mocking/stubbing frameworks. because it means my tests have an extra dependency beyond just the SUT (System Under Test). I often find myself spending more time getting the mock to work correctly rather than my app code. The lambada + generics based Mock suites (Moq, RhinoMocks, etc), IMO, complicate the test and make them unreadable in some situations.

 

Compare the two examples in this post. One uses RhinoMocks to create a stub of IDataReader and the other uses the DataTableReader to create a stub for the test. Which example is simpler and has less chance to fail due to the stub?

 

 http://www.lazycoder.com/weblog/2008/12/12/mocking-idatareader-using-rhinomocks-35/

Using RhinoMocks

IDataReader reader = MockRepository.GenerateStub<IDataReader>();
            reader.Stub(x => x.Read()).Return(true).Repeat.Times(1);
            reader.Stub(x => x.Read()).Return(false);
            reader.Stub(x => x["ID"]).Return(Guid.Empty);
            reader.Stub(x => x["FullName"]).Return("Test User");

Using DataTableReader

DataTable table = new DataTable();
            DataRow row = table.NewRow();
            table.Columns.Add(new DataColumn("ID"));
            table.Columns.Add(new DataColumn("FullName"));
            row["DirectoryUserID"] = Guid.Empty;
            row["FullName"] = "Test User";
            table.Rows.Add(row);
            DataTableReader reader = new DataTableReader(table);

Stubs/Fakes allow me more control over HOW the test fails and results in a test/fixture that is easier to read. I’m not saying that mocks aren’t useful in certain situations, but I would favor a stub over a mock IMO, your test should only fail because of the code it is testing, not because of a mock.

 

Although it is fun to say "Mock ME? No mock YOU!".

update: I forgot to link to Rob’s post that inspired this post. “Using Dependency Injection and Mocking For Testability

update to the update: Jeremy Miller and Nikola Malovic both pointed out that I’m using the terminology incorrectly. It turns out I don’t specifically hate mocks themselves, I dislike use dynamic mocking/stubbing frameworks due to the extra dependency they introduce into my tests. Thanks for the corrections. Back to reading Fowler for me!

Why these jQuery worst practices aren’t.

jQuery … Worst Practices

In this post, Steve Wellens tries to make the case for two common patterns your run across when using jQuery as “worst practices”. Practices that are either superfluous or harmful to your code.

1) Wiring up events using unobtrusive JavaScript.

Instead of wiring up your elements events using jQuery, instead you should set the OnClientClick property of the ASP.NET Web Control in question and call whatever JavaScript you want to handle the event.

Instead of this:

    <script type="text/javascript">

        $(document).ready(function()
        {
            $("#Button1").click(function(event)
            {
                alert("You Clicked Me!");
            });
        });

    </script>

Do This:

    <asp:Button ID="Button1" 
                runat="server" 
                Text="MyButton"                
                OnClientClick="alert('You Clicked Me!');" /> 

His reasoning is as follows:

You might want to change event handlers dynamically depending on some condition in the page. If you need to assign a common event handler to several objects on a page, it makes sense to do it in one place. As a matter of fact, that’s the beauty of jQuery. But for a single event on a single control….NO.

On can debate whether or not a worst practice can really be applied to a single, specific , one-time event or not. But there are other reasons why you might want to hook up events to a single element using jQuery. one being that you can’t hook up multiple event handlers using OnClientClick or HTML’s OnClick event, only a single event handler can be assigned. If you are using the observer pattern in your JavaScript, you may have multiple observers that want to subscribe to your buttons click event. But a really strong argument could be made for using the OnClientClick property simply due to ASP.NET’s suck-ass way of handling client IDs.

2) Chaining can lead to unreadable code.

In a badly written example, he states that chaining calls to jQuery makes the code unreadable. I’d suggest re-formatting the code in this manner to make it legible and allow for a tighter minimization.

$("div.highlight")
  .css("color", "yellow")
  .css("background-color", "black")
  .css("width", "50px");

Of course, you wouldn’t write jQuery code like that and call the css method multiple times. Ideally, you would just set a class or at the very least pass in a set of properties in an object.

$("div.highlight").css({
  color:"yellow",
  background-color:"black",
  width:"50px"
});

3) Comment your code.

// get all the Divs with the highlight class and
// format them and set their width

var Divs = $("div.highlight");
Divs.css("color", "yellow");
Divs.css("background-color", "black");
Divs.css("width", "30px");   

I like this explanation by Jeff Atwood best. If you need comments to explain WHAT your code is doing, you need to use better names and/or write better code. Comments are best when used sparingly and explain the WHY of the code. Why did you choose to use a particular algorithm

ASP.NET MVC Tip – Return specific views for specific errors.

Earlier I had said to keep your controllers as thin as possible, that doesn’t mean that they should necessarily just be two, or one, lines of code.

Take an instance where you are retrieving items from a web service in your controller. Let’s say that you get a 404 error and your service will throw an exception telling you that the service can’t be found. Take a look at this controller action

public ViewResult Item(string itemID)
{
	Item item = MyWebServiceWrapper.GetItem(itemID);
	return View("Item", item);
}

As it stands this action is pretty thin, but if an exception is thrown the user will be presented with either whatever custom error page you have defined in your web.config or the dreaded Yellow Screen of Death.(YSOD). You can wrap the call in a try-catch block and catch the exception. But rather than creating a generic errors page that will display any raw exception message, it’s a much better idea to return an error specific view to your user with a friendly error message.

public ViewResult Item(string itemID)
{
	try
	{
		Item item = MyWebServiceWrapper.GetItem(itemID);
		return View("Item", item);
	} 
	catch(ServiceCannotBeReachedException) 
	{
		Item item = new Item(itemID);
		return View("CannotRetrieveItem", item);
	}
}

//The CannotReachService view has a line that looks like this
// "The item <%= Model.itemID %> can not be retrieved at this time. Please try again later"
// obviously this can be globalized/localized as needed.

This leads to a much “dumber” view and is a much better idea than modifying the “Item” view to display errors if something isn’t right with the model or passing in special error parameters to the view. Let the view deal with the data it is meant to display and nothing else.

ASP.NET MVC tip – Don’t use the Content or Scripts directories for view specific files

ASP.NET MVC creates a default file structure for you when you create a new project. It includes a Scripts directory, which contains the MS AJAX and jQuery .js files, and a content directory, which contains a Master page and CSS files. I find this to be extremely cumbersome and it forces me to jump around a lot. Storing shared CSS and JavaScript files in those locations is fine in my opinion. But if you are using View specific CSS or JavaScript files, you should put them alongside your view page in the Views directory. This allows you to quickly find the file you want to work on.