Saturday, July 18, 2009

Just fix it!

It’s Saturday.  I just spent an hour and a half outside a Starbucks killing off open project items for an old client.  It was hot outside and the friendly folks enjoying their Saturday were starting to distract me… so now I’m at the library.

I like developing software – even on Saturday.  There are other things I like doing more (especially on Saturday, especially if it involves my wife and kids.)  Developing software isn’t the worst thing I could be doing, but this particular software is trying my patience.

This software is a giant beast of business critical software that people are counting on.  It needs to be functional soon so the legacy system can rest in peace.  This software project put me out of business (I guess that’s not totally fair… my 5-year-ago self’s lack of project management skills did me in – but this software is the blob in front of me that points that out.)

Why am I writing about this instead of “Just fixing it”?  Good question.  Answer: I don’t know how to fix a lot of the open items that are left.  The original requirements analyst did not give me a good set of requirements explaining how the system should work (btw, I was the original analyst.  And developer.  And accountant.  And salesman…)

Now there, I got that off my chest and onto the internet – I feel much better.  Now, back to work… This is not an intractable problem, but I can’t program my way out of this one without some help.

Some software problems are easy to solve.  For example: “The feature rate isn’t getting populated when I add a feature to the rental agreement.”  I can fix that.

Some problems are harder, even impossible, without a better story behind them.  For example: “The rental agreements are billing 10 days”.  I can’t just fix that.  I get the implication here… rental agreements should not always “bill 10 days”.  How should they bill?  Are there some cases where 10 days is appropriate?  The questions go on and on…

This is not at all meant to belittle the user who reported this issue.  He saw something wrong and reported it, nothing wrong with that.  My point is that I have a lot of non-programming work to do before I can begin to solve such a problem.  I need to expand this user’s ~10 word problem report into a series of stories that look like this:

“When a user does X, the software should respond with Y.”

A more specific, contrived example: “When a rental agreement is created with Usage type D, it should use the Daily Rate and should not be included in the ready to Invoice List until the next Friday after it was created.”

Once I have a complete set of those, then I can fix it.  Since I’m a proactive kind of guy, I’ll spend this Saturday expanding this one issue into lots and lots of short phrases (user stories) like the one above.  It isn’t the most satisfying work… especially since it will probably take a while for my client to confirm, deny or expand my list of stories.  But c'est la vie…

Thursday, June 11, 2009

Side by side code: Classic ADO.Net and the NHibernate ORM

This post continues my “NCharlie” post series, in which I take Agile methods/technologies I picked up at a .Net Bootcamp in Austin back to work. My intended audience is my future self (reference) and my coworkers – we write custom business apps using .Net 2.0 webforms backed by SQL Server.

Currently our team maintains lots of SQL stored procedures per application. As our lead developer I would like to lead the team in a new direction that doesn’t include all these sprocs. The benefits of such a move are numerous and well-stated (edited, updated incorrect link) by people much smarter and more experienced than me. But for us, the immediate value would be:

1) Less code to maintain (yes, Transact-SQL is code).

2) Persistence ignorance, resulting in code that is more testable and easier to create, understand later, and fix if needed. An SQL stored procedure is a terrible place for business logic to reside (hard to test, hard to find)… removing the temptation to put it there is a hidden benefit.

3) Faster development cycles. We’ve built this CRUD over and over again so many times. Let’s be pragmatic and stop repeating ourselves. Even with code generators the CRUD procedures and data access layers are a painful part of our projects we shouldn’t be worrying about.

I could probably go on… instead I’ll jump into an example. You can find this type of example code in many other places, I’m not reinventing anything here. Hopefully this side by side format will help someone else out there move on from writing the type of data access code I’ve been writing for too many years now.

First up let’s knock the “C” off the classic ADO.Net CRUD. “C” is for create, and I want to create a record in my database that corresponds to an entity class in my application I’ve populated with data. The entity may have been populated by taking a user’s inputs on a web form and mapping them to the entity’s properties… it doesn’t matter where I got the data – I’m concentrating now on persisting it to the datastore. Here are the steps involved in such a task:

1) Write a stored procedure that takes input parameters corresponding to the entity properties I want to save, executes an INSERT statement against the proper table, and returns an identifier for the new record. (note: we use a code generator against a database table to create this procedure)

CREATE PROCEDURE [dbo].[InsertTask]
@Description varchar(500),
@Submitted datetime,
@SubmittedBy varchar(50),
@Closed datetime,
@ClosedBy varchar(50),
@Priority int,
@AssignedTo varchar(50)
AS

INSERT INTO
[dbo].[wdtasks_Tasks] (
[Description],
[Submitted],
[SubmittedBy],
[Closed],
[ClosedBy],
[Priority],
[AssignedTo]
) VALUES (
@Description,
@Submitted,
@SubmittedBy,
@Closed,
@ClosedBy,
@Priority,
@AssignedTo
)

SELECT SCOPE_IDENTITY()



2) We use a data helper class (cleverly named DataHelper) to instantiate a connection object and an ADO.Net command object. Then we build up the input parameters and execute a stored procedure.



string cn = ConfigurationManager.AppSettings.Get("dbConnection_Tasks");


SqlParameter[] aParams = new SqlParameter[7];
aParams[0] = new SqlParameter("@Description", SqlDbType.VarChar);
aParams[0].Value = Null.GetNull(oEntity.Description);
aParams[1] = new SqlParameter("@Submitted", SqlDbType.DateTime);
aParams[1].Value = Null.GetNull(oEntity.Submitted);
aParams[2] = new SqlParameter("@SubmittedBy", SqlDbType.VarChar);
aParams[2].Value = Null.GetNull(oEntity.SubmittedBy);
aParams[3] = new SqlParameter("@Closed", SqlDbType.DateTime);
aParams[3].Value = Null.GetNull(oEntity.Closed);
aParams[4] = new SqlParameter("@ClosedBy", SqlDbType.VarChar);
aParams[4].Value = Null.GetNull(oEntity.ClosedBy);
aParams[5] = new SqlParameter("@Priority", SqlDbType.Int);
aParams[5].Value = Null.GetNull(oEntity.Priority);
aParams[6] = new SqlParameter("@AssignedTo", SqlDbType.VarChar);
aParams[6].Value = Null.GetNull(oEntity.AssignedTo);




return int.Parse(DataHelper.ExecuteProcedureScalar(cn, "InsertTask", aParams).ToString());



After executing the command, we receive a scalar value (the new record identifier) in return. Then we dispose of the command object and close the connection. (note: our DataHelper class handles the repetitive code here too.)



Wow, that wasn’t so bad huh? Code generation and that DataHelper really helps! It is a good thing it does too, because those 5 steps have to be repeated over, and over, ad nauseam, for ALL the entities that need to be persisted to the database.



Object Relational Mapping to the rescue… let’s perform that same task (saving our entity to the database) using NHibernate:



1) Create an XML mapping file for the entity.



<?xml version="1.0" encoding="utf-8" ?>
<
hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NCharlie.Core"
namespace="NCharlie.Core.Domain.Model">

<
class name="Task">

<
id name="ID" column="ID" type="Guid">
<
generator class="guid.comb"/>
</
id>

<
property name="Description" />

<
bag name="Tags" access="field.camelcase-underscore" cascade="all-delete-orphan" >
<
key column="Task_ID" />
<
one-to-many class="Tag" />
</
bag>

</
class>

</
hibernate-mapping>



2) Call the “SaveOrUpdate” method.



using (ISession session = GetSession())
using (ITransaction tx = session.BeginTransaction())
{
session.SaveOrUpdate(entity);
tx.Commit();
}


Some of you may be looking at that mapping file and thinking I bumped my head… kind of seems like I’m introducing more complexity if you are used to plain old SQL. And I am. But it is a good tradeoff… because once you get that mapping file done, you also get the RUD parts of CRUD for free, as well as a ton of other NHibernate features (including custom queries, paging…) The other methods (to round out the CRUD feature) are “List”, “Get” and “Delete”.



The code in step 2 above, the code using the NHibernate ORM, is actually really nice and simple to use once you get used to it. You can see it in action in the NCharlie example project… and if you work with me, you’ll see it in the near future in the prototype stage of one of our next projects :)

Geo Tracks – 2009 May 30

(published this a bit after the fact… big deadline at work was cramping my style!)

Elegant Code Cast 23 – Jeremy Miller on the StructureMap IOC tool for .Net, FubuMVC, JQuery, etc.  I’m not a big IOC user (or understander, for that matter)… but I’ll file this away for the future – Jeremy states that an IOC tool helps us construct applications using composition of objects vs. inheritance.

Hanselminutes 162 – Powershell 2.0.  I love my command shell in Windows XP… and it sounds like Powershell, which is built in to Windows 7, is definitely something to learn at some point.

StackOverflow Podcast #54 – Bespoke software development (a.k.a. bidding for jobs vs. creating a new product), the “God” algorithm (the one that just knows the correct answer in one operation), URL routing (and the snafus available when URLs conflict with data… eg. a user with username “username”).

God is Strong, Am I? – Francis Chan from May 10, 2009.  Let’s live by the Spirit people… why do we go through life afraid or weak or ambivalent when the One who made everything dwells in us?

Saturday, May 23, 2009

Revving up the TDD engine

tach

I’m still in the early stages of writing unit tests at work… but I did commit 26 passing tests to source control this afternoon!  The pain is fading, I’m gaining confidence and speed and I’m getting excited about the number of tests I’ve written.  We’re no mature TDD shop yet, but it is an enjoyable stage when the shiny new unit tests still make us go “ah”.

In this post I’ll finish out the TDD section of my NCharlie project series by walking through some code that tests the interaction between a controller and view.  It includes using Rhino Mocks to raise an event and verify that the controller calls the correct method on the view in response.  I know in my last post I practically gave up on Rhino Mocks in favor of writing my own mock classes and methods… well, I changed my mind.  RM is a great tool, and I’m getting used to the syntax required for .Net 2.0 projects.  So here goes…

search-results

I want to test the behavior when a user clicks one of the “[show]” links in the Task Search results list.  The application should show the Task Detail view when this happens:

task-detail

So I’ll name my test accordingly:

[Test]
public void Should_call_show_task_when_task_selected_event_is_raised()
{
}


Before I start into the body of this test method, there is some setup code that I need to get in place:



[TestFixture]
public class TaskManagerControllerTests
{
MockRepository mocks;
ITaskManagerView viewMock;
ITaskRepository repository;

[SetUp]
public void SetUp()
{
mocks = new MockRepository();
viewMock = mocks.DynamicMock<ITaskManagerView>();
repository = mocks.CreateMock<ITaskRepository>();
}



The mock view will allow me to test my controller code without needing to have a view implementation (ASPX page) wired up and working first.  First I arrange the needed elements for the test by creating the event arguments object that will be passed with the event and an event raiser named “clickEvent”:



[Test]
public void Should_call_show_task_when_task_selected_event_is_raised()
{
string taskID = "12345678-1234-1234-1234-123456789012";
TaskSelectedEventArgs e = new TaskSelectedEventArgs(taskID);

IEventRaiser clickEvent = Expect
.Call(delegate { viewMock.TaskSelected += null; })
.IgnoreArguments()
.GetEventRaiser();



Next I use the Rhino mocks “Expect.Call” method to state that I expect the view’s “ShowTask” method to be called with with my test task ID as the parameter.  The expectations are finished with a call to the R.M. “ReplayAll” method:



[Test]
public void Should_call_show_task_when_task_selected_event_is_raised()
{
string taskID = "12345678-1234-1234-1234-123456789012";
TaskSelectedEventArgs e = new TaskSelectedEventArgs(taskID);

IEventRaiser clickEvent = Expect
.Call(delegate { viewMock.TaskSelected += null; })
.IgnoreArguments()
.GetEventRaiser();

Expect.Call(delegate { viewMock.ShowTask(e.TaskID); })
.Repeat.Once();
mocks.ReplayAll();
}



Finally, I execute the code that will test this behavior… I instantiate a new TaskManagerController (this happens when the view is created) and raise the click event.  The R.M. “VerifyAll” method verifies that all my expectations are met when the code executed:



[Test]
public void Should_call_show_task_when_task_selected_event_is_raised()
{
string taskID = "12345678-1234-1234-1234-123456789012";
TaskSelectedEventArgs e = new TaskSelectedEventArgs(taskID);

IEventRaiser clickEvent = Expect
.Call(delegate { viewMock.TaskSelected += null; })
.IgnoreArguments()
.GetEventRaiser();

Expect.Call(delegate { viewMock.ShowTask(e.TaskID); })
.Repeat.Once();
mocks.ReplayAll();

new TaskManagerController(viewMock, repository);
clickEvent.Raise(null, e);
mocks.VerifyAll();
}


That’s it.  The code to make it pass is painfully simple (painful because the code to test it is so much longer… I’m getting less and less offended by this state of affairs though, since the tests look like this for complicated code under test as well.  Besides, these tests copy and paste very easily!)  Here is the code from the controller under test:



private void OnTaskSelected(object sender, TaskSelectedEventArgs e)
{
view.ShowTask(e.TaskID);
}


And that makes it pass:



tests-passed



 



 

Thursday, May 14, 2009

Do we have time to write tests on our projects?

This is a question I would like to answer in the context of my day job.  It came up again today as I was talking with the other developers about some of the “new methods” I would like to integrate into our development process.  The title of this post is how the question sounds now in my head.  This afternoon it went more like this: “We don’t have time to write tests on our projects!”

Granted the developer who made this statement is a big believer in the “speak first, reason it out later” method of communicating… this is his knee-jerk reaction to someone telling him we would write more code for the same functionality.  I can sympathize with him… we have deadlines on our projects to meet.  But I don’t agree with him.  I’ve already written some tests at work to solve a problem in the business logic of software we released 2 months ago.  The exercise helped me find other problems in that code and refactor it to a state that will be much easier to maintain.  Do we have time to maintain legacy code that is hard to understand and has no tests written against it?  I don’t.

But… even though I am convinced we need to write tests, I want to be practical.  Will my team benefit from this?  Are there certain types of developers or certain types of projects that will never see the benefit of writing tests against code?  Maybe so – but I hope that isn’t a description of the team I work with.  And I think the best way to find out is to do the best I can to set us up for success.  That is a big reason I am writing about my experience building up the NCharlie project.  I have some work to do before we are there though.  As I mentioned before, TDD still feels like a pain point for me because of the way my tests look using Rhino Mocks to mock objects like the database access code.  When I mentioned this pain point to my boot-camp instructor his advice was to “abandon ship”… not on TDD, but on the Rhino Mocks Expect-Replay-Verify model and use the easier to understand Arrange-Act-Assert model of testing (I know AAA is possible with Rhino Mocks… but not with nice syntax in .Net 2.0).

So, I am going to follow my instructor’s advice and abandon ship.  I’m going to start writing tests without a mocking framework.  I can create a class quickly that mocks a database access class without using Rhino Mocks.  Sure it will be a bit more code to write, but I think the clarity it will bring to the tests will be worth it.  I also think it will be a good exercise even if I do end up coming back to a mocking framework like Rhino Mocks… I will appreciate it more after manually building mock objects.

This means I am going to stay on the topic of writing tests for at least one more post.  Earlier in this series I wrote some tests to verify that the controller class for the Task Search page in the NCharlie project was correctly responding to events raised in the view.  I didn’t show the code for the test in the post (it was available in the code repository) because I did not want to distract from the intent of that post.  Now it is time to show that code… almost (actually, in the next post).  First, let me answer the question I posed in the title of this post:

Yes, we do have time.  It will make us go faster because our code will end up being easier to work in now, and easier to extend or fix later.

Tuesday, May 5, 2009

TDD Pain Points, A Retrospective

This is the fourth weekend into writing about test driven development… taking agile methods I learned in boot-camp back to work.  Time for a retrospective…

First I will say that writing about this process has been a tremendous help in making these concepts gel.  Try teaching someone about something you are trying to learn.  I don’t care if no one ever reads these posts – the process of writing them has been invaluable to me.

Now, for the pain points:

Supervising controller:

I chose this pattern (a flavor of Model-View-Presenter) for two reasons.  1) We use .Net 2.0 at work and our developers have a lot invested in webforms.  2) It helps me separate functionality away from code-behind files and adhere to the Single Responsibility Principle, which is especially important if the code will be tested.

I like most of the Supervising Controller pattern in the context of webforms.  What I don’t like (pain point) is the "loop" of event handling: view fires event, then raises another event that the controller is subscribed to, then the controller responds by executing some logic and then calling a function back in the view to render results.  This is convoluted... I like the separation of concerns, but I don't like having to subscribe to events more than once.  Can I just call controller methods directly from the view?  Maybe what I'm describing is called the "Passive Controller"... I need to look into it.  This is really, probably, a pain point that should be attributed to webform development.  But hey, webforms pay the bills!

TDD:

Yes, as of now I’m listing Test Driven Development as a pain point.  I really like testing my code.  I don't really like the syntax I'm using to mock functionality.  Mocking my dependencies is necessary to write unit tests, but the Record, Replay, Verify syntax in Rhino Mocks is not natural for me to set up and harder to explain to my team.  I am still trying to shove the Rhino Mocks 3.3 RRV syntax into the Arrange, Act, Assert (AAA) method I learned in boot-camp.  I need to change the way I'm using Rhino Mocks, or I need to start using a different mocking framework (Rhino Mocks supports the AAA syntax and is explained really well... Using .net 3.x lamba expressions.  AAA is possible with Rhino Mocks, but the 2.0 syntax is painful.

That’s it for pain points for now.  These by no means mean I am giving up on TDD or Supervising Controller.  Although painful right now, I think these are birth-pangs… I am hopeful that in 2 or 3 months they will be big giant assets in my toolbox.  I’ll end now on a (what is the opposite of a pain point?) happy point: Resharper 4.5 is incredible.  It makes me go faster… I intend to dedicate a future post to my top X favorite features.

<< NCharlie: TDD – Part 3 (a UI test)

Geo Tracks – 2009 May Cinco

I’m a little late this week because we moved last weekend.  Now I am closer to work (cut 2 hours per day off the commute!)… which means less time with the podcasts and more time with the family – a nice trade I think.  I’m still listening to book one in the Wheel of Time series, and will be for while.

Saturday, April 25, 2009

Geo Tracks – 2009 Apr 25

Hanselminutes 158 - Visiting Fog Creek Software and Joel Spolsky… I’m still not sure what exactly FogBugz is, but I learned a lot about how it was built and has evolved? Also, good to get some encouragement to keep writing, even if no one ever notices your blog :)

Psalm 80 – Psalm 85 ESV read by Max McLean

I started book 1, The Eye of the World, in Robert Jordan’s Wheel of Time series. Jeremy Miller put this at the top of his book list… I had never heard of it, so I’m giving it a try.  (Thanks for the iTunes gift cert Lucas!)

That’s it for this week… I worked from home Friday, so no commute.  Thursday I brought my wife to work with me so she could spend the day looking at places to live and schools in the area I work in… which means no podcasts since the wife likes to talk to me instead. :)  We may be moving closer to work soon!

NCharlie: TDD – part 3 (a UI test)

In this post I tackle the last task on my list for the task manager search feature: “Write tests, then implement the ShowSearchResults method.”

In part one I wrote unit tests to verify my TaskManagerController class is listening (subscribed) to the SearchRequested event, and that it correctly responds by calling the TaskManagerView class “ShowSearchResults” method.  In part two I verified that the TaskRepository correctly returns tasks when the Search method is called.

I admit: as I write this sentence I’m not sure how I will accomplish writing a test to verify that ShowSearchResults works… so I posted the question to Twitter:

I wrote a unit test to verify my controller calls my view's "ShowResult" method... What kind of test verifies ShowResult shows the result?

…and got a reply from my boot-camp instructor:

@charliesolomon we automate testing the ui. don't know that there's a great name for that other than automated ui test. or just ui test.

@mhinze So at this point (UI testing) it is time for me to use WatiN or equivalent?

@charliesolomon yes, sounds like it.

So here I go… WatiN is an open source web application test framework for .Net that will spin up an instance of my web browser and verify things on a web page.  To verify that ShowSearchResults is working I want to verify that the correct search results display on screen when the ShowSearchResults method is called on the TaskManagerView.

TaskManagerSearch_2

First I create a new class library project named UITests.  I want to keep these tests in a separate project because they take much longer to run than my unit tests.  If I’m going to keep this example strictly “Test First”, I need to, well, write my test first:

[Test]
public void Should_show_search_results()
{
Task task = new Task("foo");
TaskRepository repository =
new TaskRepository(new HybridSessionBuilder());
repository.Save(task);

using (IE ie = new IE("http://localhost:1035/Default.aspx"))
{
Button search = ie.Button(Find.ById("btnSearch"));
search.Click();

Div tasks = ie.Div(Find.ById("tasks"));

Assert.IsTrue(tasks.InnerHtml.IndexOf("foo") >= 0);
}
}


I’m not showing the [SetUp] method here for this Test Fixture… it ensures I have a clean database before running this test.  The test above just adds a task to the database, fires up the web page and verifies the search results come up correctly.



Default.aspx is a very simple page… just a text field, button and repeater to show the results. The “ShowSearchResults” method is what I’m interested in implementing and testing for this feature.  For the sake of brevity in this post, I will just refer you to the code to see how the ASPX page and code-behind file are constructed.  Here is the ShowSearchResults method from Default.aspx.cs:



public void ShowSearchResults(ICollection<Task> tasks)
{
rptTasks.DataSource = tasks;
rptTasks.DataBind();
}



I run my test and see WatiN fire up Internet Explorer, click the “Get” button, then search the results for my test record…



watin-clicking-get



watin-showing-results



…and the Resharper test runner shows the results:



ui-tests-passed



That’s it!  Of course it looks really simple here, and it is… but it actually took me 3 hours to get this simple test working.  Here’s why:



NUnit uses multi-threading by default, WatiN requires a single-threaded execution.  I solved this using a config file (“NCharlie.UITests.dll.config”… naming this config file correctly was actually the biggest time sink for this exercise.  I ended up adding a test to check that my config file was being read – thanks Charlie Poole)



For more information, check out the tdd-demo code branch and see the WatiN getting started guide.



<< NCharlie: TDD – part 2 (an integration test)  TDD Pain Points, A Retrospective >>

Saturday, April 18, 2009

NCharlie: TDD – part 2 (an integration test)

In my last post of this series I wrote unit tests to verify that an event (SearchRequested) from the View was handled by the Controller in my Agile/TDD sandbox application NCharlie.  I started with a sequence diagram showing the interactions needed to accomplish a search, then wrote down the tasks needed to complete this feature:

  1. Create interfaces for TaskManagerView and TaskRepository.
  2. Write tests, then write code to raise and handle the SearchRequestEvent method.
  3. Write tests, then implement the Search method.
  4. Write tests, then implement the ShowSearchResults method.

Two down, two to go.  The first two tasks could be test driven using unit tests.  Rhino Mocks allowed me to create a mock View and a mock Repository and concentrate on the TaskManagerController class… making sure it responded and handled the SearchRequested event correctly.  Now I want to wire up the Search method to return some actual results, and I want to show those results in an ASPX page, like this:

TaskManagerSearch

Since the Search method will be interacting with my database, I’ll need to test it using an integration test.  I like the way CodeCampServer keeps integration tests in a separate project… from the Resharper test runner it is easy to run all the tests in a project – so keeping the fast-executing unit tests separated seems to be a good idea.  I will add a new project to the NCharlie solution for integration tests and get to work (source is available in the tdd-demo branch of the NCharlie project.)

Here is the test method I want to build:

[Test]
public void Should_search_by_task_description()...


To write this test I will need to able to save Task entities to the database, retrieve them using the Search method, and make sure that the returned items contain the correct search results.  The saving part is accomplished in NCharlie using NHibernate and some helper classes that can be found in the open source projects CodeCampServer and Tarantino: IRepository, PersistentObject and HybridSessionBuilder.  These are mostly the same in NCharlie, though I did make a few changes so they would be .Net 2.0-friendly for this project.  The “PersistEntities” method below saves entities to the database, ensures the transaction is committed and the session is closed, so that subsequent calls to the database in this test can count on the entities being there.  I have not shown it here, but when running integration tests against a database it is important to setup the test first and make sure the database is in a consistent state.  This is done via a [SETUP] method in the RepositoryTestBase class, which my TaskRepositoryTester class is derived from.  Here is the test that verifies the search method is working correctly:



[Test]
public void Should_search_by_task_description()
{
Task task1 = new Task("foo");
Task task2 = new Task("xFOo1");
Task task3 = new Task("no fu");

PersistEntities(task1, task2, task3);

TaskSearchSpecification searchSpecification =
new TaskSearchSpecification();
searchSpecification.Description = "foo";

ITaskRepository repository =
new TaskRepository(new HybridSessionBuilder());
Task[] tasks = repository.Search(searchSpecification);

CollectionAssert.Contains(tasks, task1);
CollectionAssert.Contains(tasks, task2);
CollectionAssert.DoesNotContain(tasks, task3);
}


The “TaskSearchSpecification” class contains the search input fields (in this example I’m only searching on the Description field.)  Finally, I call the actual “Search” method on the TaskRepository and verify the results using the “CollectionAssert” class (part of NUnit.)



This test fails initially, and I implement the search method in TaskRepository to make it pass:



public Task[] Search(TaskSearchSpecification specification)
{
ICriteria criteria = GetSession()
.CreateCriteria(typeof (Task));

IList<Task> tasks = criteria
.Add(Restrictions
.InsensitiveLike("Description",
specification.Description,
MatchMode.Anywhere)
)
.List<Task>();

Task[] taskArray = new Task[tasks.Count];
tasks.CopyTo(taskArray, 0);

return taskArray;
}



task-search-test


For more information:



As I was writing this post I ran across Billy McCafferty’s article on NHibernate Best Practices with ASP.Net… I highly recommend it if you are interested in how these patterns are implemented.  I know things have changed in our field since he wrote this article (Billy later contributed the S#arp architecture which uses ASP.Net MVC), but this article is a great resource… especially for someone like me who works in a place where Webforms are still the tool we use to get our work done.  It is also very apparent from reading Billy’s article just how much it has influenced the ASP.Net world since it was written.  The CodeCampServer project I’m basing NCharlie on uses much of the architecture and patterns first described in Billy’s article and later in his S#harp architecture.



<< Previous NCharlie: TDD – part1, Next NCharlie: TDD – part 3 >>

Geo Tracks – 2009 Apr 18

Alt.Net Podcast #18, talking with Jeremy Miller about Alt.Net.  I like what Jeremy and James Avery have to say here.  My summary: Alties need to focus on improving their own craft instead of trying to force feed their current stack of tools/patterns/archs into the .Net mainstream.

Stack Overflow Podcast #47 – Joel and Jeff talk about sketching mockups with Balsamiq Mockups (a favorite of mine), say they will talk about Eclipse but really don’t, and keep ramblin’ on and on…

Hanselminutae 5 with Richard Campbell – Scott admits he is out to waste my time with this episode, but hey, I’ve got an hour and 15 to waste driving to work anyway!

SE Radio #129, F# with Luke Hoban – Good talk about use cases for F#.  Luke thinks the increase of parallelism in software as we keep adding cores to CPUs will make languages like F# much more needed.  Also interesting that F# targets the ad-hoc algorithm crowd… people who analyze data using tools like MathCAD or Mathematica.

Why People Believe What They Do, SciAm Podcast April 10, 2009 – Interesting discussion about a study on the correlation (or lack of) between education, religious affiliations, and beliefs in evolutionary theory and origins of life.  One general consensus was that humans naturally gravitate to solutions that show some sense of purpose vs. “it just happened randomly”.

Gospel Conference Part 5, Francis Chan – Francis starts with Ephesians 2 and the hope of heaven… also talks through some of the ways his church (Cornerstone Simi) cares for and rescues orphans, poor and abused people around the world.

Psalm 37 – Psalm 50 ESV read by Max McLean

Saturday, April 11, 2009

Geo Tracks – 2009 Apr 11

I spend a lot of time in the car each week.  This car, specifically (91 Geo Metro… 47 mpg!):

geo

I’m going to start linking to what I’m listening to during the commute each week (if I think they are worth sharing).  I’ll tag them “Geo Tracks”:

.NET Rocks #433: Phil Haack on ASP.NET MVC RTM!! Good explanation of MVC, and Supervising Controller / Passive Controller (MVP) models.

.NET Rocks #421: Derik Whittaker on nHibernate Good talk about use cases for nHibernate… but the best part of this show was Richard Campbell’s call out to the IT community (52:40) that the default monitor configuration for a developer should be 4960 by 1600 (30” in the middle, bookended by two 20” screens in portrait mode).  Yes please.

Stack Overflow Podcast #43 Joel and Jeff discuss how to handle incompetent programmers, among other things.  Specific other things include Joel whining about the service he receives everywhere he travels… It is getting more difficult to finish these each time I listen to this podcast, but I don’t think I’ll give up yet.  I was really impressed with the Podcast site.  First time I’ve visited, since I always update through iTunes.  They really keep good show notes and are liberal with the links to resources.

Francis Chan – 3/22/09 Living a Life that Matters Series: “Living with Joy” If you have never heard Francis speak, get ready to be convicted and changed.  Rejoice in the Lord… it is a command!

Scientific American PodcastIn Search of Time Journalist and writer Dan Falk talks about his new book In Search of Time, about the cultural, physical and psychological aspects of the mysterious ticking clocks all around us.

NCharlie: Test Driven Development – part 1

This is the second post in a series that tracks my progress implementing some of the technologies, patterns and methods I picked up at an Agile .Net boot-camp in March 2009.

The exercise for this post is to strip down my sandbox project, NCharlie, to a point where I can really see the benefit of test-first development.  Then I will add a feature to the project using the process my instructor followed (“User Story Execution Process”, described here).  You can download the source for this exercise by browsing the tdd-demo branch of the NCharlie project on Google Code.

The project is a simple task management tool.  The first feature I’ll implement is the search feature.  Here’s the requirement:

“A user should be able to search for existing tasks.”

I know, that is a pretty vague requirement.  I’ll add on more layers later… for now, this requirement will serve nicely (I hope) in demonstrating the TDD method.  I spent some time setting up my “Core” project which contains the domain model (for now, just one entity… a Task).  Next I create a sequence diagram describing a search for existing tasks:

task-manager-search-sequence

Aside: If you are staring at this diagram wondering why I’m using Views, Controllers and Repositories, it is because of the architecture decisions I’ve made for this project.  I hinted at the motivation for this architecture in the first post of this series… I may come back to that in more detail later.  For now though I will just admit that it was pretty easy to think about the ingredients for this sequence diagram because I had already built this and now I’m just starting over.  When I built NCharlie initially there was some pain I had to work through getting the parts of the Supervising Controller pattern to work in the context of a webforms application using the Onion Architecture.  But that is figured out now, and I won’t have to figure it out again on every application.  I know now that I need to model View events and handle those events in a Controller.  The Repository pattern is used to abstract away the persistence (database) part of the application. (end of Aside)

Back to the exercise… I’ll break the elements of the sequence diagram down into development tasks:

  1. Create interfaces for TaskManagerView and TaskRepository.
  2. Write tests, then write code to raise and handle the SearchRequestEvent method.
  3. Write tests, then implement the Search method.
  4. Write tests, then implement the ShowSearchResults method.

Step 1: Here are the two interfaces:

public interface ITaskManagerView : IView
{
event EventHandler<TaskSearchEventArgs>
SearchRequested;
void ShowSearchResults(ICollection<Task>);
}



public interface ITaskRepository : IRepository<Task>
{
Task[] Search(
TaskSearchSpecification specification);
}



The view interface is derived from the IView interface, which I won’t explain in detail here.  Phil Haack did a good job of explaining this in his Supervising Controller example – IView holds common event handlers and methods for a web form (Init, Load, IsPostBack…)



The repository interface is derived from IRepository, which holds CRUD methods used to persist objects.  I added the Search method to ITaskRepository.



Step 2: The SearchRequestEvent:



For this step, I need to write 2 tests.  First, the Controller must listen (subscribe to) the View event so that it can respond.



[Test]
public void Verify_controller_attaches_to_search_requested_event()...



Second, I want to make sure the Controller calls the Search method on the repository when this event is raised.



[Test]
public void Repository_search_method_should_be_called_in_response_to_search_request()...



You may be asking why I left the guts of these tests out of this post?  After all, this is supposed to be a post about writing tests first.  I struggled with this for a while and decided not to show the implementation here because I don’t want to get sidetracked trying to explain how to create mock calls to the view and to the repository.  One of the benefits of writing these tests is that I can do so before I create any ASPX pages or database procedures.  Before I even have to think about ASPX or database connections and queries I can have a compiling project with unit tests that specify the behavior I want to achieve.  That is the value I hope to convey in this post.  The test implementation details are available in the source for this exercise, and I hope to cover it in more detail in a later post.



After implementing the above two tests correctly my project compiles, but when I execute the tests they fail (I’m using the Resharper test runner to execute my test methods.  At boot-camp we used TestDriven.Net.  You can also execute these tests from NUnit’s console runner or the command line if you like.):



SearchRequestedEvent tests failed



Now I’ll write the code to make these two tests pass.  I create an event handler method (OnSearchRequested) that calls the repository’s Search method and attach it to the View’s SearchRequested event:



public class TaskManagerController
{
private readonly ITaskManagerView _view;
private readonly ITaskRepository _repository;

public TaskManagerController(
ITaskManagerView view,
ITaskRepository repository)
{
this._view = view;
this._repository = repository;
SubscribeViewToEvents();
}

private void SubscribeViewToEvents()
{
_view.SearchRequested += OnSearchRequested;
}

private void OnSearchRequested(
object sender,
TaskSearchEventArgs e)
{
ICollection<Task> tasks =
_repository.Search(e.SearchSpecification);
_view.ShowSearchResults(tasks);
}

}



Now I rebuild and execute my unit tests:



SearchRequestedEvent tests pass



These two unit tests are passing now, and they don’t require an ASPX page or a database to do so.  I think that is valuable!  They clearly describe what the behavior of this part of my application should be and they enforce that behavior without requiring me to think about the specific implementation of the web form or the repository.



Next time I will continue with steps 3 and 4 in my task list above... testing and implementing the Search and ShowSearchResults methods.



<< Development Driven Tests (Introduction), NCharlie: Test Driven Development, part 2 >>

Sunday, April 5, 2009

Development Driven Tests

I’ve got the title wrong backwards to make a point.  That point is coming…

I attended .Net boot-camp a few weeks ago and practiced Test Driven Development.  We talked about new features to add to CodeCampServer (the open source project used as the coding sandbox for class).  Our instructor drew sequence diagrams on the whiteboard and we designed the interfaces and interactions the features would require.  We assigned tasks, wrote tests that failed, then wrote code to make them pass.  It was great.  To me it felt the way development should feel, like we were doing it right.

Now I’m trying to work through how to take these methods, which feel so right, back to work.  It seems to me this is a common problem developers like me deal with, and I want to succeed.  So I’ve been working through a project that uses the agile tools and methods demonstrated at boot-camp and tries to flesh them out using code that will run in our environment at work.  My thought was that a finished project, built using the methods I want to use more at work, would go a long way to convincing my coworkers of the value these methods and tools could bring.  Here are the ingredients I’m throwing together in my example project:

  • Onion Architecture (to remove some pain caused by tightly coupled areas of our applications)
  • Test First Development (using NUnit and Rhino Mocks, to realize the increased code quality and code longevity that TDD proponents promise)
  • Object-Relational-Mapping (using NHibernate, because I’m tired of maintaining dozens (hundreds?) of stored procedures per app)
  • Visual Studio 2005 (because that’s what we use at work)
  • Web Forms using the Supervising Controller pattern (because we can’t use MVC at work and this seemed to me a testable next best thing for web forms)

I’ve named my project “NCharlie” for now, since it uses at least 3 technologies that start with “N”, and since it will help Charlie (me) chronicle my journey towards becoming a better programmer.  It is a simple task management tool (add to-do items, assign tags to them, search for them).

This brings me back to the title of this post, and my point.  After spending a few hours on NCharlie I’m realizing that it is hard to make the transition to TDD.  I have been making the software work first for so many years now that it feels unnatural to write tests before implementations.  I am now at the point where I am writing more tests… but NCharlie is already working!!  I fell hard back into my old pattern and implemented the design before I wrote tests.  Sure I wrote a few tests up front, but I have to be honest with myself and admit they were only copies of tests I learned about at boot-camp.  Anything specific to the design of my test project has been just plain hard for me to test first.

So is NCharlie just going to end up on my FAIL list?  I hope not… I still have plans for it (actually it is the reason I’m starting this blog.)  The way it sits now NCharlie is of no use to me or my coworkers because it doesn’t prove what I set out to prove… in fact it disproves it! 

This is a wake up call for me, because I think a developer who excels at writing tests first must also have a good handle on other principles/patterns that distinguish an average developer from a master.  So I’m average, that’s ok.  But I don’t want to stay here.  I have been reading books and blogs for a couple years now that describe pragmatic and agile methods I know I want to use in my career as a developer.  I’ve been successful with some, but the more I learn the more I realize how far I have to go.

So here I go… new plan.  I’m going to dissect NCharlie and show you its ugly guts in public.  I have no shame.  In fact I’m quite proud of some of it… even though it is blatantly not original.  It uses code from open source projects like CodeCampServer and Tarantino.  I can however, take credit for getting them all working together from “File, New Project”.

So let’s call this an introduction to a series of posts.  Mainly I want to document the process for my team at work and for myself so we can use this as we hopefully start to integrate these methods into our workflow (if I can get NCharlie to the point of proving its usefulness).  In the next post I’ll attempt to strip down NCharlie and start over at the point where TDD actually shows some benefit.

Next in series -  NCharlie: Test Driven Development – part 1 >>