Class naming

In the process of writing one of the chapters in the brownfield book, I started thinking about class naming.  Some time ago I remember hearing someone saying that they didn't much like the use of class names that ended in 'er' even if they conveyed good intent.  For example:

SpellChecker

or

NameParser

My understanding is that the dislike stemmed from the thought that the use of 'er' made the name of the class to much like a verb, and that verbs were the domain of a method name.  I bought into it when I first heard this.  Now I'm not so sure.  In some cases I fully agree.  Other times I find it a little restrictive.  At times I'd change the name of SpellChecker to SpellCheckingService, and NameParser to NameParsingService.  No more 'er' ending, but it does start to encroach on another naming guideline that I have: don't use pattern names in class names.

In the end we want the class names to be intention revealing.  More-so the combination of class and method name should be intention revealing.  What do you people do in these situations?

NHibernate on WCF

I know that there are a few blog posts out there on this subject, so I feel like I'm repeating myself while writing this.  Bear with me...please.  Over the last month I've been chasing an ISession corruption error in our application with little success.  During that time I spent a lot of time looking at our WCF implementation to ensure that it wasn't some piece of that which was causing the problem.  Needless to say, it wasn't, but I have a much greater appreciation for the extensibility of WCF as a result.  Part of my research/debugging/hacking around/crying was looking into the most appropriate way to create, persist and end a nHibernate ISession object during each individual WCF OperationContract call.  Here's what I figured out and created.

The first, and easiest thing that you need to do is set the ServiceContract Attribute to have an InstanceContextMode =  InstanceContextMode.PerCall.  The key here is that I want per call isolation.  Choosing thie InstanceContextMode will force the creation of a new service context for each client request and ultimately create a new InstanceContext object for each call.  What you're doing here is telling WCF that every call to an OperationContext should be treated as a distinctly separate code execution area.  If you were to leave InstanceContextMode to its default (InstanceContextMode.PerSession) the execution area of the code would create an InstanceContext for the duration of the Channel's life. Basically, that would mean that creating a connection to the WCF service would create a new InstanceContext and all OperationContracts would have access to it until the channel was released.  This will allow you to access items in the InstanceContext across calls, which is not how we want to handle our ISessions.

[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[NHibernateContext]
public interface ICustomerServices
{
    [OperationContract]
    IEnumerable<CustomerListingDto> RetrieveListingOfAll();
}

So we've created a service that is set to have PerCall InstanceContexts.  This is the first step to creating and storing the ISession.  Putting an ISession into the InstanceContext requires us to create a custom extension using IExtension<T>.  All our extension needs to do is provide a place to store the ISession object for that OperationContract call.  The extensions on the InstanceContext have a lifetime that lasts only for the duration of the call.  In the end the extension looks like this:

public class NHibernateContextExension : IExtension<InstanceContext>
{
    public NHibernateContextExension(ISession session)
    {
        Session = session;
    }

    public ISession Session { get; private set; }

    public void Attach(InstanceContext owner)
    {}

    public void Detach(InstanceContext owner)
    {}
}

Now that we have that extension we need to get it attached to each and every OperationContract call that is handled by our service.  An IInstanceContextInitializer implementing class is used to trigger the addition of the extension to the InstanceContext.  Every time that an InstanceContext is initialized (which will be on every Operation call since we're using InstanceContextMode.PerSession) the NHibernateContextExtension is added to the newly created InstanceContext.  Also note that it is at this point that the NHibernate ISession object is created and assigned to the InstanceContext's extension.  It's here that the nHibernate session per operation call concept is implemented.

public class NHibernateContextInitializer : IInstanceContextInitializer
{
    public void Initialize(InstanceContext instanceContext, Message message)
    {
        instanceContext.Extensions.Add(
            new NHibernateContextExtension(
                NHibernateFactory.OpenSession()
                )
            );
    }
}

You probably noticed in the NHibernateContextInitializer class above that the ISession object is being created from a NHibernateFactory object.  This object is a wrapper for the native NHibernate ISessionFactory object.  We need it implemented in this way so that we have a technique for accessing a session factory that is created outside of the scope of this little framework.  Later in this post you will see how this object is used and initialized with a valid SessionFactory object.

public static class NHibernateFactory
{
    private static ISessionFactory _sessionFactory;

    public static void Initialize()
    {
        Initialize(new Configuration().Configure().BuildSessionFactory());
    }

    public static void Initialize(ISessionFactory sessionFactory)
    {
        _sessionFactory = sessionFactory;
    }

    public static ISession OpenSession()
    {
        return _sessionFactory.OpenSession();
    }
}

With a way to attach a new ISession to every InstanceContext that is created, we need to trigger this process on each and every call.  To do that we will attribute the WCF service with a custom attribute.  All we need to do is create a class that is an Attribute and implements the IContractBehavior interface.  During ApplyDispatchBehavior we add an NHibernateContextIntializer to start the entire process of creating the new NHibernate ISession for each call.

public class NHibernateContextAttribute : Attribute, IContractBehavior
{
    public ISessionFactory SessionFactory { private get; set; }

    public void Validate(ContractDescription contractDescription, 
                            ServiceEndpoint endpoint)
    {}

    public void ApplyDispatchBehavior(ContractDescription contractDescription, 
                            ServiceEndpoint endpoint, 
                            DispatchRuntime dispatchRuntime)
    {
        dispatchRuntime.InstanceContextInitializers.Add(
            new NHibernateContextInitializer());
    }

    public void ApplyClientBehavior(ContractDescription contractDescription, 
                            ServiceEndpoint endpoint, 
                            ClientRuntime clientRuntime)
    {}

    public void AddBindingParameters(ContractDescription contractDescription, 
                            ServiceEndpoint endpoint, 
                            BindingParameterCollection bindingParameters)
    {}

Simply creating a new ISession for each call to the WCF service isn't enough.  We need to be able to work with that ISession object in our data access endeavours. To do that I've created a simple class with a static method on it that retrieves the NHibernateContext Extension from the current InstanceContext.  This is possible because there is only one InstanceContext during the life of each service call.  To make this fall in line with other 'Context' object that we are used to working with (like HttpContext) I've created the static method called Current.

public class NHibernateContext
{
    public static NHibernateContextExension Current()
    {
        return OperationContext.Current.
                InstanceContext.Extensions.
                Find<NHibernateContextExension>();
    }
}

All of that explanation is well and good, but the real trick is how the hell do you use this.  That is fairly simple.  You need to do three things. First you need to create and initialize a nHibernate SessionFactory and inject it into the custom wrapper that is provided in this code.  Normally you would want to do this once for the life of the application as shown by placing this code in the Application_Start of the global.asax file.  This code snippet shows two options for initializing the factory. The first line will automatically load a nHibernate SessionFactory using the hibernate.cfg.xml file that is in the same folder as the IglooCoder.Commons.dll file.  The second line allows more flexibility to initialize a nHibernate SessionFactory in the way that you need or want.

protected void Application_Start(object sender, EventArgs e)
{
    NHibernateFactory.Initialize();
    //or//
    NHibernateFactory.Initialize(new Configuration().Configure().BuildSessionFactory());
}

Second you need to attribute any services with the NHibernateContextAttribute) that will need to access data using nHibernate.

[ServiceContract]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[NHibernateContext]
public interface ICustomerServices
{
    [OperationContract]
    IEnumerable<CustomerListingDto> RetrieveListingOfAll();
}

The final step is to make use of the ISession object that the framework is creating for each call.  As you can see in the code below there is a bit of a trick to using t

public abstract class BaseRepository<T> : IRepository<T>
{
    public T FetchById(int id)
    {
        return NHibernateContext.Current().Session.Get<T>(id);
    }
}

If you want to use this code and not have to write it all out you can grab the source from the project's Subversion trunk (https://igloocoder.net:8445/svn/IglooCommons/trunk/).  Compile the code running b.bat at the command line and you will find the compiled assemblies in the \compile folder.

My next post will talk about how to maintain testability while using this stuff.

Ideas for implementing this came from Dan Rigsby's posts on WCF extension here and here.

Announcing the ALT.NET Canada Conference

For the last half a year a group of us (Bil, James, Dave, Terry, Justice, Greg and Kyle) have been organizing the first ALT.NET conference in Canada and today, on Canada Day no less, we are announcing the opening of registration to it.  The event will happen on August 15-17 in Calgary. 

If you've not been to, or heard about, the ALT.NET conferences in Austin and Seattle, they have drawn many software development luminaries and created great conversations.  There are no predefined sessions like you would normally find at a conference.  The format follows the Open Spaces principle and is completely self organizing.  The topics, conveners and session attendees happen based on the needs of the day, hour or minute.  One of the most fantastic things about the conference is that conversations don't stop after an hour.  They will carry on in the halls, cab rides, restaurants, and most definitely in hotel lounges.

You can sign up here (http://www.altnetconfcanada.com/registration/index.castle) and review the current attendee list here (http://www.altnetconfcanada.com/participant/index.castle).  Note that the conference is capped at 100 registrants, so signup fast.  If you don't get into that list, sign up anyways to ensure that you're on the waitlist when people start cancelling.

Big shout out to the sponsors that we have so far: Thoughtworks, Solidhouse, CodeBetter and MSDN Canada.

I personally guarantee that one of the two Canadian delicacies you see here will be available in abundance at your hotel breakfast during the conference.  You'll just have to wait to see which one.

On this great day...

The majority of Canadians will be celebrating Canada Day and the creation of our country.  Lost on the majority of the population is that July 1st also marks a day of great sacrifice.  On this day in 1916 eight hundred and one of the Royal Newfoundland Regiment went over the top at Beaumont-Hamel.  The following following morning only sixty-nine answered the regimental roll call.  Since 1916 Newfoundland has born the weight of this sacrifice on their own.  Since 1949 it has been the responsibility of Canadians to remember these men as some of the great fathers of our country.  While they are the brunt of many jokes, Newfoundlanders have a resilience that is characterized by the fact over one percent of it's youth left their homes, country and continent to fight in WWI and sacrifice their lives or their health.

While we celebrate Canada's birthday and the many things we have to be thankful for, we cannot forget to stop and thank the strong, the brave and the selfless who have helped...even if they weren't Canadians at the time.

"It was a magnificent display of trained and disciplined valour, and its assault only failed of success because dead men can advance no further." Major-General Sir Beauvoir de Lisle (commander, British 29th Division) regarding the Newfoundland Regiment at Beaumont-Hamel.

DotNetRocks Brownfield episode

Kyle Baley and I did an interview with Carl and Richard recently where we talked about ecosystems in the context of a brownfield application.  Show #354 was published this morning and can be found here.  Enjoy....I hope.

Communication Waste

For the last few months I've been on a steady mission to absorb as much about lean software development as I can.  This morning I got up and decided to enjoy the morning air, slight breeze, my Zune and the start of the Poppendieck's Lean Software Development: An Agile Toolkit book.  After having read The Toyota Way recently, it was pretty clear to me that eliminating waste was a large component of lean ideals.  In the first chapter of the Poppendieck's book, how waste manifests itself in software development was cemented for me.  I immediately started thinking about a recent experience of mine.

A little while ago I was asked to take a look at some modelling that another project was doing.  The idea was that I would review it and contribute to a discussion with information on our project's Domain Driven Design movement.  I was provided with a forwarded copy of an email thread that spanned a conversation between a couple of architects and a senior level developer along with a small set of attached diagrams.  Rather than initially working through the multi-page email thread, I decided to take a look at the diagrams.  My whole though process boiled down to the fact that looking at four diagrams would provide me with much faster initial insight, and it did.

I immediately realized that the concept of modelling used on this other project was completely different than the model that we created organically as part of our DDD efforts.  While the attachments did provide me with quick insight into the area of discussion that was being engaged, detailed inspection of them didn't provide any information on the project.  After reviewing all four 'model' diagrams, I still had no idea what the project was about.  It's at this point that I decided that I needed to read the email thread.

It was in the email thread that things got interesting for me.  I'll say in advance that I still have no idea what business area, let alone problem, the project is addressing, but that wasn't the most interesting thing that I took from the reading.  The email thread consisted of a series of five to seven emails spread out over approximately a week.  The conversation was triggered by the initial question of "How do the different models you are presenting relate to each other?".  Through the remainder of the thread, the relationship between the models was no clearer to me.

My first thought was that the number of different models was creating communication friction.  The different model diagrams that I had seen in the attachments seemed as though they were fragmented.  While they were cohesive (in the programming sense), they were so loosely coupled that they didn't tie together in any way.  Combined, the diagrams didn't create an understandable story for their consumer.  This is what I initially thought the problem was.

After some thought though, I have decided it wasn't that the project had four different models that weren't tied together in any meaningful way.  What I think happened is that these diagrams were created to enhance communication where it wasn't needed.  In one of the diagrams it was outlined that the project would create a Semantic Model during business analysis, a Platform-independent Model during technical analysis and a Platform-specific Model during technical design.  Overall the project was creating three models that, I'm guessing, were to represent the same business functionality.  Three different views on the same thing.  Does the business get any increased value by having these three representations created?  Probably not.  Instead they're getting more effort required to do the initial creation of the models.  More effort to maintain the models through the life of the software.  More effort to communicate how the models relate.

All of that effort is wasteful since it doesn't provide any additional value to the client.  Lean software development is all about eliminating waste.  I'd say drop multiple models in favour of one that accurately represents the business and is written in a way that allows all parties, clients, analysts and developers, to communicate in one language and context.

Separation of Concerns

I know this has been beaten to death in some circles (521,000 results in Google, 2,551 results in Google's blog search), but it bears repeating until people start paying it some attention.  Separation of Concerns is the concept that software areas exist with as little overlap as possible.  The existence of distinct logical layers within your code is an example of the start of creating good separation of concerns.  A layer exist for the UI, another layer exists for Data Access, and on and on.  Each layer is concerned with one aspect of the application.

Today I saw the complete lack of separation of concerns on my project.  Note that this project has no concept of a dynamically generate user interface.  A stored procedure was presented that had intimate knowledge about the controls that were to be displayed in the user interface.  The stored procedure's output provided both data and the control type that said data should be displayed in.  So a return result might have looked something like this:

John Bloggins Textbox
Male Option
1963 Dropdown

 

The blurring of concerns here, isn't so much a blurring as it's a complete erasing of it.  To change the physical display of data on the screen, a stored procedure (data access component) must be changed.  Because there's a significant group of people in the industry that don't seem to be catching on to why this is a problem, let's look at it in a bit more detail.

In this situation there are two distinct concerns in the life of the application; Displaying data (UI) and retrieving data (data access). Both have distinctly different requirement. When displaying data the application is dealing with screen colour, font information, control location, interaction points, etc. All of these things relate to the experience of the user.  The standard user's primary concern doesn't include what table in the database the information comes from, if/how logging is occurring, ORM vs Stored Proc, etc.

The second concern that is identifiable in this scenario is data access. DALs are quite well known in the industry.  All a DAL is is a logical layer within your application.  Simply having a DAL is a decent first step to separating out the concerns surrounding your data access methods, techniques and nuances. It is just a start though.  A data access layer will be concerned, in some way that is tied to the technology that you're using, with things like creating connections, queries and transactioning.  All of those things, plus some others, have to do with the physical interaction between your code and the data storage repository.  That physical interaction includes anything that lays between table, column, row and your application.  It might be that the interaction uses inline parameterized queries or it could be using stored procedures.  Both of those are part of your DAL along with the C#, VB, Java, whatever code that is managing the connections, transactioning, ect.

So what is the problem with what I saw at work today?  If the user interface is concerned with the formatting, layout, and control rendering of the screen, why does the stored procedure need to know about it?  By putting the control type decision into the stored procedure we've made every layer between the UI and the DAL (and there should be a few different logical layers in there) aware of the UI implementation.  Yes, not all, or even any, of those logical layers will actively interact with the control type information, but it is there which means each layer is aware of it.  The bigger issue is that we've now tightly coupled our UI and stored proc.  The UI is dependent on the stored proc for it to render correctly.  If the stored proc changes, the UI will render differently (outside of the data displayed within the layout/structure of the UI).  The coupling is also reversed.  The stored procedure is now has to be intimately knowledgeable about the capabilities of the UI that is being implemented.  If we moved from a webform to winform implementation there is a very high probability that the stored procedure would need changes to allow it to continue to work.

The capability of one logical layer or concern in the application is directly tied to the implementation in another.  Separating each concern will allow you to work in a section of the application with less worry about the implications in another layer or concern. 

None of this is an exact and quantifiable science, but every developer in the industry should be able to notice where concerns are being blurred or mixed.  If you can't notice this, I'd strongly suggest that you need to look at changing your career to something that involves less abstraction.  Yes, I said it.  If you can't conceive of software at this level of abstract get a different job.  You're not cut out to qualify as a software developer.  All you are is a hobbyist that is getting paid.  Separation of Concerns is a fundamental practice that all developers need to understand.  The size of your application is irrelevant.  The expected life of your application is usually irrelevant.  The technology that you use is irrelevant.  Maintainability, changeability and reverseability are relevant though.  Those are some of the things that make applications that sustain the trials of time and business changes.

[Note] Jimmy Bogard has started a series on separation of concerns.  It's a little more hands on than this rant.  How not to do it and  Part 1

Overloaded Methods as WCF OperationContracts

Interesting find today.  It is possible to create a WCF Service Contract that has overloaded methods on it.  The compiler doesn't complain at all. You can even attribute both as [OperationContract] and the compiler still won't complain.  If you go to use that Service Contract though, it will blow up and thrown an error about duplicate naming.  While this is frustrating you can get around it.  Options include, changing the name of one of the Operation Contracts or setting the name parameter on the Operation Contract attribute (i.e. [OperationContract(Name="SomeUniqueName")]).

Great Indian Developer Summit wrapup

Right after the completion of DevTeach in Toronto, I hopped a plane to India to present at the inaugural Great Indian Developer Summit being put on by Saltmarch Media.  First let's say that the flight duration from North America to India just flat out sucks.  It's an aweful long time to spend in a sealed aluminium tube.  In hindsight, the trip was worth every second of re-breathed air I had to inhale.

Dilip Thomas and his group from Saltmarch Media put on a polished and invigorating conference.  The organization wasn't without flaw, but each flaw that I saw was noted and addressed before the start of the next day.  Not once did I run into the same problem twice.  The most notable of the situations that I ran into (and this will tell you how trivial the problems really were) was that my power adapter wasn't working properly and I was having to run off of battery during my sessions.  The helpers at the conference scrambled in attempts to make the hardware that I had work while sending someone off to find a replacement adapter/powerbar.  That happened on the first day.  On the second day there were power adapters provided in every room for the speakers.

The other thing that I noticed was the amount of advertising and banner work that was present at the event.  There was no question that the Great Indian Developer Summit was being held at the Indian Institute of Science when you drove by it.  Once you drove into the grounds it was pretty clear that this thing was going to be big.  Registration was setup to accept a fairly large number of people at one time.  Lunch provided a wonderfully complete and sizeable buffet that was easily accessed by all.  Probably the only thing that was lacking was seating for attendees to use while having their lunch.

During the sessions the attendees (or delegates as they were being called) took a little bit of time to get warmed up and interacting with you.  Once they did get comfortable with the idea of a dialog instead of a pontification during the presentation, their passion, concerns and technical skill bubbled to the surface.  Presenting to this group was an exceptionally positive experience (more to come in a future post).  For those that attended my sessions and don't want to wait for the CD/DVD to arrive, you can download the Powerpoint files here.

Thanks to Dilip for inviting me to the Great Indian Developer Summit, to Usha for her work to make the trip as painless as possible, and to the delegates for their energy.  If given the chance, I'll be back again.

DevTeach Toronto wrapup

As always DevTeach was a blast this time around.  It was good to catch up with some of the people that I haven't seen for a while.  This was my first time at the conference where I had a full slate of presentations to do.  All of the seemed to go fairly well and the conversation continued in the hallways after the sessions had wrapped up.  The material for all three presentations can be found here (Take CCNet and nAnt to the Next Level, Techniques for Starting on Brownfield Projects, Introduction to Behaviour Based Testing).

One of the things that I learned at DevTeach was to watch the naming of my sessions going forward.  This year DevTeach had a lot of sessions focusing on BDD (Behaviour Driven Development) which led to some confusion with my Intro to Behaviour Based Testing session.  The mistake I made was to use the overloaded term 'Behaviour' instead of the term 'Interaction'.  While both are applicable for the session title, I probably should have cleared that up before the first slide in my session.

Other than that one mistake, the conference went fairly well for me.  A few of us went out to the CBC to watch a taping of The Hour with George Stroumboulopoulos.  We hung out in the lobby until all hours and Jeff Palermo held his infamous Party with Palermo.  Good times all around.  Hope to see some of you at DevTeach Montreal in December.