Tutorial – BDD and Dependency Injection in .Net (4)

As usual we are picking up from where we left off. In this brief post we will expand our SpecFlow knowledge by focusing on parameterised the step definitions.

Currently the SpecFlow tests are as follows:

PlayRoundFeature.feature

Feature: Play a single round of Rock Paper Scissors
	As a player
	I want to play a round
	So that I can test my luck

Scenario: Computer chooses rock and the player chooses paper
	Given the computer makes a secret choice of rock
	When I choose paper
	Then the result should be “Player Wins!”

Scenario: Computer chooses rock and the player chooses scissors
	Given the computer makes a secret choice of rock
	When I choose scissors
	Then the result should be “Computer Wins!”

PlayRoundSteps.cs

namespace RockPaperScissorsTest.Specs.Steps
{
    [Binding]
    public class PlayRoundSteps
    {
        private const string GameKey = "Game";

        [Given(@"the computer makes a secret choice of rock")]
        public void GivenTheComputerMakesASecretChoiceOfRock()
        {
            var game = new Game(new DescissionEngine());
            ScenarioContext.Current.Add(GameKey, game);
        }

        [When(@"I choose paper")]
        public void WhenIChoosePaper()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            game.PlayerMove = "Paper";
        }

        [When(@"I choose scissors")]
        public void WhenIChooseScissors()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            game.PlayerMove = "Scissors";
        }

        [Then(@"the result should be “Player Wins!”")]
        public void ThenTheResultShouldBePlayerWins()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            Assert.AreEqual("Player Wins!", game.Result());
        }

        [Then(@"the result should be “Computer Wins!”")]
        public void ThenTheResultShouldBeComputerWins()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            Assert.AreEqual("Computer Wins!", game.Result());
        }

    }
}

Continue reading

Tutorial – BDD and Dependency Injection in .Net (3)

In part 2 of this tutorial, we moved the decision logic out of the Game class into the Decision Engine class to separate concerns. Now we introduce dependency injection.

In this part of the tutorial, we will use dependency injection (DI) to improve the design of the code base. Zby provides a useful definition of dependency injection: “Dependency injection means giving an object its instance variables instead of letting it create them”.

In our case, we will be giving the Game object an instance of Decision Engine instead of letting the Game object create it itself. We will do this via the Game’s constructor, however it could be done though a property or a method. These alternatives are known as constructor injection, property injection and method injection respectively.

This is the essence of the dependency injection pattern. Confusion tends to creep in when a dependency injection container is introduced. DI containers, such as unity or Castle Windsor, provide mechanisms to aid in implementing the dependency injection pattern. However, they are not required to implement the pattern. I recommend the use of DI containers when the benefit of using one outweighs the complexity that is introduced by using it.

For the sake of simplicity, I will be using the dependency injection pattern and will avoid dependency injection containers for the time being. Returning to the rock, paper scissors example, DI will provide two main benefits:

  • Flexibility – we will be able to provide different implementations of the Decision Engine without changing the Game class. This ‘pluggable architecture’ adheres to the open close principle. An example of this would be a decision engine that not only decides on a result, but also logs the results to a data store. I will return to this should time allow.
  • Testability – during testing, we will be able to pass a mock object to the Game object, thus allowing us to test the Game class in isolation of the Decision Engine. This will be demonstrated in the code below.

Continue reading

Tutorial – BDD and Dependency Injection in .Net (2)

In this post we concentrate on separating concerns. We will not cover dependency injection within this post, but we will set things up so that we can cover that topic in the future.

We continue where part 1 left off. The SpecFlow feature file looks as follows:

PlayRoundFeature.feature

Feature: Play a single round of Rock Paper Scissors
	As a player
	I want to play a round
	So that I can test my luck

Scenario: Computer chooses Rock and the player chooses Paper
	Given the computer makes a secret choice of Rock
	When I choose Paper
	Then the result should be "Player Wins!"

Scenario: Computer chooses Rock and the player chooses Scissors
	Given the computer makes a secret choice of Rock
	When I choose Scissors
	Then the result should be "Computer Wins!"

The step definition file has the following:

PlayRoundSteps.cs

namespace RockPaperScissorsTest.Specs.Steps
{
    [Binding]
    public class PlayRoundSteps
    {
        private const string GameKey = "Game";

        [Given(@"the computer makes a secret choice of rock")]
        public void GivenTheComputerMakesASecretChoiceOfRock()
        {
            var game = new Game();
            ScenarioContext.Current.Add(GameKey, game);
        }

        [When(@"I choose paper")]
        public void WhenIChoosePaper()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            game.PlayerMove = "Paper";
        }

        [When(@"I choose scissors")]
        public void WhenIChooseScissors()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            game.PlayerMove = "Scissors";
        }

        [Then(@"the result should be ""Player Wins!""")]
        public void ThenTheResultShouldBePlayerWins()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            Assert.AreEqual("Player Wins!", game.Result());
        }

        [Then(@"the result should be ""Computer Wins!""")]
        public void ThenTheResultShouldBeComputerWins()
        {
            var game = ScenarioContext.Current.Get(GameKey);
            Assert.AreEqual("Computer Wins!", game.Result());
        }

    }
}

The unit tests look as follows:

GameTest.cs


        [TestMethod]
        public void ComputerRock_PlayerPaper_PlayerWins()
        {
            var game = new Game();
            game.PlayerMove = "Paper";
            Assert.AreEqual("Player Wins!", game.Result());
        }

        [TestMethod]
        public void ComputerRock_PlayerScissors_ComputerWins()
        {
            var game = new Game();
            game.PlayerMove = "Scissors";
            Assert.AreEqual("Computer Wins!", game.Result());
        }

With the implementation being as follows:

Game.cs

namespace RockPaperScissors
{
    public class Game
    {
        private string _playerMove;
        public string PlayerMove
        {
            private get
            {
                if (String.IsNullOrEmpty(_playerMove))
                    throw new ArgumentNullException("PlayerMove");
                return _playerMove;
            }
            set
            {
                _playerMove = value;
            }
        }

        public string Result()
        {
            return PlayerMove == "Paper" ? "Player Wins!" : "Computer Wins!";
        }
    }
}

Turning a critical eye onto the Game.cs class we see that it has become responsible for deciding the result of the game as well as the string being returned to the user interface. This class is mixing domain logic with UI concerns. Therefore there are two reasons we may need to change this class. This breaks the single responsibility design principle.

Continue reading

Tutorial – BDD and Dependency Injection in .Net (1)

This tutorial focuses on Behaviour Driven Development, Dependency Injection and application design in general. The primary technologies being used will be SpecFlow and MS Test. While we are targeting the .Net platform the content is applicable to most object oriented languages.

A Brief Introduction to Behaviour Driven Development

Behaviour Driven Development (BDD) is an ‘outside in’ or ‘top down’ development approach. Development starts from the user interface downwards as opposed to starting with the database design.  When there is no user interface (as in the beginning of this tutorial) we work from the highest level possible.

BDD encourages thin slices of work. Where we break features down into very small ‘end-to-end’ pieces of work. This work is expressed in the form of examples. This is known as specification by example and we will see this in the tutorial.

In SpecFlow speak, each example is known as a scenario. We need to implement a number of scenarios before the feature is considered complete. We will flesh out the design as we implement each scenario.

The following diagram from The RSpec Book shows the BDD cycle:

BDD Cycle

As depicted, there are two levels of testing – high level system or integration tests and lower level unit testing. The high level tests often drive a user interface and may be referred to as automated acceptance tests.

Not only will we be following the BDD cycle, but we will only implement the code we need to make the existing tests pass – and no more. We will be very strict with this. This may seem tedious to some however this approach is good to practice. You can always fall back to this approach should you become stuck when writing production code.

Interestingly TDD was always meant to have multiple levels of testing. In Extreme Programming Explained, Kent Beck and Cynthia Andres have the following to say about architects: “Architects on an XP team look for and execute large-scale refactorings, write system-level tests that stress the architecture, and implement stories”. This is similar to what we are trying to achieve in BDD. In fact Dan North introduced the term BDD to help him explain TDD to developers. This is why I say that BDD is TDD done properly.

These days it is common to hear teams say they are doing “TDD but not BDD”. By this they sometimes mean that they are writing system tests and unit tets, but they are not using a “BDD testing framework” like Cucumber or FitNesse. There is nothing wrong with this approach. Sometimes “we do TDD but not BDD’ means that the team members are not writing system level integration tests. This is better than no tests at all, however it is not true TDD and they are missing a trick.

A Brief Introduction to Dependency Injection

James Shaw does a great job of explaining Dependency Injection (DI). He points out that “Dependency Injection means giving an object its instance variables”. The instance variables are typically reference types which provide a layer of abstraction. We can give an object it’s instance variables through a number of different ways namely constructor injection, property injection, method injection.

There are many reasons for using Dependency Injection. The most obvious reason is that it makes the code more testable. It makes it easy to use mock objects in place of the real dependencies during testing. Testability is not the only reason, when done properly code which uses dependency injection tends to support the SOLID design principles, most notably the Single responsibility principle and Open/closed principle. This will be shown in the tutorial.

Dependency Injection is a simple concept, the confusion seems arise when Dependency Injection containers enter the discussion. For this reason I will not use DI Containers for the first few parts of this tutorial. All I will say is that DI Containers may help when composing objects, however they are not required to implement the dependency injection pattern.

Continue reading

Ajax Fundamentals – Part 3

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

3. Security Issues

The XMLHttpRequest object is restricted to run within the browser’s security sandbox. Any resources requested by the XMLHttpRequest object must reside within the same domain from which the calling script originated. Therefore the XMLHttpRequest object is constrained to requesting resources that reside within the same domain from which the script was originally served. The W3C states, that in the future The XMLHttpRequest Object specification will define a way of doing cross-site requests.

There is an overabundance of online documentation stating that Ajax introduces multiple security threats. These threats include fake requests, denial of service, cross-site scripting (XSS), reliance on client-side security, and more. Jeremiah Grossman’s article, Myth-Busting AJAX (In)security, maintains that these security issues existed before Ajax and the recommended security best practices remain unchanged. Part of internet security basics is to distrust the client. Ajax is a client side technology and requests need to be treaded with the same caution as all other calls.

4. Disadvantages

4.1. Usability Problems

Web users have become familiar with using classic web pages. Users have become accustomed to using browser features such as the back and next buttons. Ajax calls are not loaded onto the browsers navigation stack. Therefore the back button will not undo the last ‘Ajax operation’. Developers need to explicitly cater for undo operations.

Ajax enabled pages have a notion of state; this state is altered as the user navigates through the site. The browser is unaware of this state, and it is not reflected in the address bar. Therefore users are not always able to book mark a certain page state. Developers need to consider this when deciding on when to use Ajax.

The asynchronous nature may make page updates difficult for the user to notice. The developer needs a way of drawing the user’s attention to the modified section of the page. The ‘yellow-fade technique’ has become common practice. In this technique the changes are highlighted with a yellow background, and the yellow fades gradually. These and other techniques are becoming familiar to web users.

Continue reading

Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 6 of n

In part 5 we looked at RESTful routing. In this part we continue to explore RESTful routing, by examining nested resources.

I originally planned to cover nested routes and to cover two questions posted to me in previous comments and emails. One question was with regards to ‘one to many relationships’ e.g. an album has many songs. The second question was from Tom in part 3; this was about adding save as functionality.

In trying to answer these questions I created a new application – a text editor with a version history. This has turned out to be a fairly interesting piece of work. I then changed my mind and decided to include it in a follow up post. I am hoping to have that out later this week (before Friday the 11th of July).  As the ‘follow up’ post will have a practical example of nested resources, this post will not have the usual practical section with the experiments.

Part 6

Introduction to Nested Resources

The Nested URI

Returning to the familiar Music Store application, imagine we added songs to the application. Like Albums, Songs are resources and we could expect to access a song with this URI:

/songs/124

We could then perform the required CRUD operations on that URI based on the REST API as discussed in part 5.

An album has many songs. We can express this within the URI e.g.

/albums/10/songs/124

Once again we could make use of the HTTP verbs to perform CRUD in a RESTful way.

In this particular implementation, this URI does not mean that this is the 124th song of album 10 – it is possible for it to be the fist song of album 10.  The URI is pointing to the 124th song in the system.

If we wanted the URI to state the songtrack number of the specified album then we could alter the above implementation. Then we could expect to see URIs of:

/albums/10/songs/5
and
/albums/11/songs/5

This would not result in a URI conflict.

Continue reading

Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 5 of n

Part 6

In part 4 we explored named routes. In this session we move onto Rails’ REST.

Part 5

The Critics

Before we begin you should know that there are many critics of the Rails implementation of REST. There are many reasons for arguments against Rails’ REST e.g. Rails uses server side session state and client side cookies. Some people say that this is not REST compliant. Rails’ REST might not be 100% REST compliant, but you can still benefit from using REST in your Rails applications. In The Rails Way, Obie Fernandez explains that the benefits from using Rails’ REST fall into two categories:

  • Convenience and automatic best practices for you
  • A REST interface to your application for the rest of the world

Therefore it is worth learning and using Rails’ REST.

The Standard Introduction

Representational State Transfer (REST) is an architectural style. It was first introduced by Roy Fielding in his PhD thesis. Roy Fielding is one of the principal authors of HTTP.

The Mindset

When developing a Rails application in the RESTful way it helps to change your mindset. You should not think that you are developing a web site for users accessing the site via a browser. It is better to think of the application as being a service. The service performs actions for clients. These clients may be humans or other machines on the network.

This service will typically be placed on the internet. Therefore we could call it a web service. When I hear the term web service I immediately start thinking about SOAP and all the WS-* specifications. Let’s be clear, we are not talking about ‘those’ web services. We are talking about RESTful web services. These two technologies provide similar functionality, but RESTful web services are simple and sensible.

The Terminology

As previously stated, programming in REST requires a change in the way we think about the system. This naturally leads to a change in the way we talk about the system. The following provides a brief description of some of the key terms used in discussions about REST and HTTP.

A resource is one of the key concepts in REST. Many discussions on REST claim that a resource is anything and everything. This is neither true nor helpful. Let’s examine this concept with the aid of an example.

Let’s assume that the music store has started selling albums. The database may have the following schema:

orders erd

The data in the database is the raw data. There is data which, given in isolation, is of no real value to a client. For instance it is unlikely that a client will want only one row from the LineItems table. This means that a LineItem (on its own) is not a resource within the context of the music store service.

A client would want all the information pertaining to an order. This would include data from one or more tables. Some data would not be included e.g. database keys. Some information may be added e.g. the total cost of the order might be calculated and included in the ‘order information’. This ‘order information’ is an example of a resource. Order resource is the type, there will be one order resource instance for each order made.

Each resource must be given a globally unique identifier. This is done using a URI. This could look like this:

http://www.example.com/orders/65

A client, in an admin role, may want a list of all the orders. This collection of orders would be another resource. Following the REST architecture, the orders resource would be assigned the following URL:

http://www.example.com/orders

It is important to note that these resources are not HTML documents. Roy Fielding describes a resource as a conceptual mapping. As a resource is a conceptual entity it can not be used by a client. The service provides the client with a representation of the resource.

When the client is a browser, the service typically provides an HTML representation of the resource. If the client is another machine then the service may provide an XML representation of the resource. Other representations could include a PDF file, an image, csv etc. A representation is only supported by the service if it is applicable and required.

Resources are often referred to as nouns. This is often done when talking about HTTP to assist learning. The term ‘noun’ is more abstract. For our purposes, resources and ‘nouns’ are synonymous.

HTTP also has the notion of verbs. These are the HTTP operations. We are all familiar with the POST and GET operations. In addition to these two operations, HTTP also supports: DELETE and PUT.

There are a few more terms to cover, but we can do that later. The core terms have been explained.

Continue reading

Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 4 of n

Part 5

The routes we have discussed so far are known as simple routes. I have been referring to them as custom routes, but ‘simple routes’ is the correct term. The default route we discussed in part 3 is also a simple route. The aim is to move onto RESTful routes, sometimes called resource routes. RESTful routes are built on top of named routes. Therefore we must first cover named routes, and that is what part 4 is all about.

Part 4

Introduction

Referring back to part 1, the routing system has two main functions:
Interpreting a request URL
Generating a request URL

We had a detailed look at route generation and interpretation in part 2, but let’s have another quick look at it. Let’s assume, for some insane reason, that we defined the following route in the music_store routes.rb file:

map.connect ‘apples/bananas/:id’, :controller => “albums”, :action => “show”

link_to would use this rule to generate a URL, this can be seen in the following line extracted from index.html.erb:

link_to ‘Show’, :controller => “albums”, :action => “show”, :id => album.id

This could generate a URL of: http://localhost:3000/apples/bananas/7
And when given this request, Rails would handle it correctly e.g. the show action will be called on the albums controller and the show view will be sent as the response to the browser.

Coming back to the real world, we are more likely to define the routing rule like this:
map.connect ‘albums/show/:id’, :controller => “albums”, :action => “show”

link_to (and friends) would then generate a URL like this:
http://localhost:3000/albums/show/7.

To show the index (the listing of the albums) we could define a rule like this:
map.connect ‘albums/index’, :controller => “albums”, :action => “index”

The matching link_to in edit.html.erb is:
link_to ‘Back’, :controller => “albums”, :action => “index”

Looking at the last example, there is some repetition. Both lines contain:
:controller => “albums”, :action => “index”

The link_to method needs this (controller, action) information to obtain the URL. If we had the URL stored as some global variable, or method, then we could simply pass that into link_to. link_to could use this ‘literal’ URL without needing to generate one.
This could look something like: link_to ‘Back’, albums_index_url
This is one of the main ideas behind named routes.

Continue reading

Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 3 of n

Part 4

Part 3

At the end of part 2, routes.rb looked like this:

ActionController::Routing::Routes.draw do |map|
  map.connect 'music', :controller => "albums", :action => "index"
  map.connect '', :controller => "albums", :action => "index"
  map.connect 'music/show/:id', :controller => "albums", :action => "show"
  map.connect 'music/delete/:id', :controller => "albums", :action => "destroy"
  map.connect 'music/edit/:id', :controller => "albums", :action => "edit"
  map.connect 'music/update/:id', :controller => "albums", :action => "update"
  map.connect 'music/new', :controller => "albums", :action => "new"
  map.connect 'music/create', :controller => "albums", :action => "create"
end

To simplify things, let’s remove the routing rule for the empty URL. Remove line 3.

We can no longer browse to http://localhost:3000/, but we can still browse to http://localhost:3000/music. Besides that, the site should continue to work as before.
Looking at the routes.rb file we see 7 rules defined.

ActionController::Routing::Routes.draw do |map|
  map.connect 'music', :controller => "albums", :action => "index"
  map.connect 'music/show/:id', :controller => "albums", :action => "show"
  map.connect 'music/delete/:id', :controller => "albums", :action => "destroy"
  map.connect 'music/edit/:id', :controller => "albums", :action => "edit"
  map.connect 'music/update/:id', :controller => "albums", :action => "update"
  map.connect 'music/new', :controller => "albums", :action => "new"
  map.connect 'music/create', :controller => "albums", :action => "create"
end

We have 7 rules and only one database table. Does this mean we need to add 7 more rules for every table we add? No, there are ways to reduce the amount of explicitly defined rules.

When Rails receives a URL it tries to find a matching routing rule. It does this by comparing the URL to the pattern string in the rule.
The pattern string for map.connect ‘music/create’, :controller => “albums”, :action => “create” Is: music/create

The pattern string for map.connect ‘music/edit/:id’, :controller => “albums”, :action => “edit”
Is: music/edit/:id

The :id is a Ruby symbol and is referred to as a receptor. If you are new to Ruby you may not be too familiar with symbols. I once came across a short and sweet description of a symbol “A symbol is the name badge, not the person”. I may have read that in here.

A receptor is used as a wildcard. It matches anything that it is compared against. The wildcard receptor gets passed into the controller action within the params hash e.g.

def edit
    @album = Album.find(params[:id])
end

You can change :id to almost anything as long as you remember to change it in the controller and in the views where the URL is generated e.g. when using link_to. I recommend you use :id as that is the convention.

Continue reading