Technology with opinion

Sunday, March 18, 2012

How to Cleanup Your Email


As a software developers email has been around about as long as I've been doing development professionally.  Managing email 10 years ago was much different than managing it now.  When you might get at most 5-10 emails per day (per account) then it doesn't take that much to clean up old emails and find old emails.

One of the great things that Google did when they came out with Gmail was to give people more than enough space for email.  While Microsoft (MSN) & Yahoo were giving 3-5mb, Google gave you 1gb.  Fortunately now all mail providers have caught on and give users plenty of space, when means you don't have to delete anything, almost ever.

So where's the problem?  It's two-fold, for one if you have an offline mailbox of your mail then it's going to be huge & eat up a lot of unnecessary space.  Two: finding old email threads or contacts can be very difficult.

If you just page through all of your email and cherry pick email to delete then it will take you forever to make a decision about keeping one email as opposed to another.  These steps are going to be faster to perform on the webmail client for your email providers as opposed to whatever client your normally use (OS X Mail or Exchange).

Step 1: Delete large groups of emails based on keywords

Here I've basically searched my inbox for mail with "Buzz from Scott White" as the subject.  Skim this list to make sure no email got mismatched and then click the Select All button then Delete.




Repeat those steps until there's no mail left which you want to delete.  Some other search phrases you can use to delete "Facebook", "Monster" (Monster.com), "LinkedIn", "Twitter" or any other site which sends you tons of email.

Email from distribution lists & user groups can accumulate really large, I will usually delete all of these often too because there are already archives of these on the distribution list servers.

Step 2: Unsubscribe & Refine Email Subscriptions From Websites


By this point you pretty much know which sites are cluttering your inbox, if you haven't already, visit the websites and change your preferences so that you only get email from them that is relevant to you.

Our choices & selections of websites and news change over the years and if you find you always delete all mail from a certain website then it's probably time to unsubscribe.  Also consider using an News or RSS reader (which is already built into every email client) so that you don't get as much junk in your inbox (personally I prefer Google Reader for subscribing to RSS feeds).

Step 3: Going Forward Delete Unwanted Email Right Away


Going forward:
  • If you aren't going to read it anyway, just delete it
  • If action items from an email is complete and you don't need to prove it in more than 30 days then delete it too (remember, Gmail keeps your Trash for 30 days unless you purge it)
  • If you just read the article from the email, delete it right away.  It's easy to get out of the habit of keeping Inbox clean and it doesn't take long for it to become cluttered again

Monday, April 04, 2011

The Way of Kung Fu Programming

Kung Fu's literally meaning is the skill achieved through hard work. I was watching my kids watch the new version of Karate Kid and caught the scene where the kid is taking of his jacket and putting it back on repeatedly.

In the original Karate Kid the student was doing chores for his master, however, in politically correct times such as these this would be considered child labor so they decided to have him put on his jacket over and over again. Nevertheless, the point that is being made in both films (and throughout all martial arts movies and dojos) is that skill is achieved through hard work and practice.

This is something that is severely lacking from most of our occupations and lives. Our society is full of quick fixes for people in search of a quick buck within a culture that is driven more by money than passion. For the uber ambitious you can trade your weekends and in a few years have an MBA (weekend MBA programs). For the technically inclined, you can become Microsoft certified within one week even if you lack real world experience. Nothing is wrong with either of these in of itself however they are more/less marketing tools for yourself to land a job.

Trades used to have apprenticeship where individuals would be mentored within their occupation and people were given time to mature based upon their natural abilities and ambition. Repetition and practice is the key to becoming good at anything, but these two things are also great at filtering out people from a career for which they have no ambition. Of course, management and programming are part of many careers which people seek out without any true ambition of the subject. Unfortunately, the natural filters which used to exist that required someone to practice something no longer exist. Today with enough money, charisma or connection just about anybody can be anything, but that doesn't mean they can achieve anything.

Having Kung fu programming would mean that you are skilled. It doesn't mean that you're a a "Senior Developer" or "Architect"; these are just titles that our employers give to us. Seek your passion and if that passion is programming then follow in the ways of Kung fu programmers such as: Jimmy Bogard, Oren (AKA Ayande), Derick Bailey, Jeremy Miller or anyone blogging at Los Techies or CodeBetter. Also don't forget to practice even things that originally seem like basics and take some risks. It will help you improve and open up opportunities.

Tuesday, March 29, 2011

"Whatever happens is the only thing..

that could have happened" ....  this is the creed of Open Spaces:

"Whatever Happens is the Only Thing that Could have Happened"

To some people, this saying sounds ludicrous, and honestly when I first heard it I laughed.  Since the time I first heard it a few years ago at the first Open Spaces I attended, it seems more true every day.

Obviously there are no absolutes in life.  Self help books are one of the most popular categories in nonfiction but there is very little progress, why is this?  Perhaps because there is a difference between wanting your problems to go away and being ambitious & forward thinking enough for the fix.

One of the first books that I read early in my career was Code Complete and the Software Project Survival Guide.  Both were good books however the psychology of a project team is not often a discussed topic.  The purpose of this creed and the point behind Open Spaces is empowerment.  When people are empowered they will make the most honest decisions, work harder and be happier.

So why don't we do this more often and why does the word "deadline" even exist since it's only used to drive fear?  I asked a question on Twitter not too long ago, it was: "serious question, have you ever seen a project that was on time, on schedule and on budget (within the original scope)?".  Not one response from someone saying, "yes, we did".  One reply sums this up from @sdether "@kibbled_bits I've yet to see a product that finished with original scope".

Do projects ever finish on time, scope & budget?  It's probably very uncommon but I'm sure it has happened before.  The magical question is why the mass delusion?  Collectively, programmers, analysts & project managers on any team have been on dozens of projects that have been late, over budget or delivered with less scope.

Do we all suffer from a God complex, thinking we can fix everything with the power of our brains and refuse to accept the things that are outside of our control?  Or is the pressure of accepting the reality so great that denying the ultimate reality is easier than dealing with the pressure of knowing that you aren't tracking or worse, that you will miss the target.

Agile projects are the reality, whether you are practicing this discipline or not.  The only thing that is released is the only thing that could have been released.  Unfortunately, this mindset is hard for some to accept so you can either accept the reality or keep living in the dark.

Sunday, November 14, 2010

Nescafe Tasters Choice instant Coffee Reviewed


They were giving out these instant coffees at the PATH station. Just to be clear, I've never been a big fan of Tasters Choice coffee or any of the other big coffee makers however I did like Starbucks instant coffee but found the price a bit steep.

I chose a normal size mug, not an over sized mug, to pour one of these packets into as the higher ratio of water to instant grounds will make it weaker.  The coffee produced from this packet was pretty good, at least the Columbian Roast was. The body was even, low acidity but strong for an instant coffee.

Overall about as good as the Starbucks instant and at a fraction of the cost. Amazon has both brands as cheap as 70 cents per packet for the Starbucks instant compared to 17 cents for the Nescafe. Verdict: recommended as alternative to mediocre work coffee or on the go.

Getting Started: Programming Objective C on Windows

Why Learn Objective C?

Objective C has made C programming cool again and it's making a comeback. I've been interested in learning Objective C for many reasons: iPhone Development, statically compiled language with dynamic features and to brush up on my C programming.

It's been many years since I've done any C or C++ programming. If the C language gave birth to C++ then Objective C would be its sibling. Current versions of Objective C is basically the C language sandwiched with Smalltalk sprinkled with the goodness of dynamic programming and syntactic sugar.

Many people struggle writting iPhone applications in my opinion because they neglect the fact that Objective C is a first class language and like C# (.Net) or Java require time and patience to learn it first before learning the frameworks and paradigms. This would be akin to trying to learn C#, HTML & JQuery for the first time on an ASP.Net MVC project.

I will be treating Objective C like a first class language and I will be learning it on Windows first because I want to focus on the language first and not the frameworks (such as Cocoa). My first goal is to get a running development environment on Windows for Objective C programming, write a simple "Hello World" app and compile it using both gcc and a make file.

Setting up Development Environment on Windows from scratch

GNUstep is the cross platform, free & open source version of Objective C. First download and install GNUstep Core, GNUstep System, GNUstep Development Environment and your favorite text editor such as Notepad++. After installing this a group will be added to your Start menu in Windows named GNUstep, beneath it is a shortcut to a "Shell". Once open, you will be in a full command shell (BASH) you will be able to compile Objective C code files using make or gcc but we will first have to create a class file

The gcc that comes with GNUstep can compile C or Objective C apps. We will first start with a Hello World app that uses C header files and then tweak it to use Objective C header files to make sure everything is lined up and configured correctly in your development environment. Create a file called main.m and paste the following into it.

Within the GNUstep Shell navigate to the same folder and compile it (within GNUstep shell C:\YourProject would be /c/YourProject) by typing the following:

Then test the output in shell by running the app and make sure the output is correct before continuing.

Next we will modify the helloworld source to use Objective C library and make a build file for it so that it will compile. First, update main.m to below:

GNUstep provides makefiles which include the references to the libraries and folders that you will need. Create a file named GNUmakefile in our project directory and put the following into it.

Now to build it is simple, just type the following into our shell.

Some warnings should appear from the compiler but it should compile. Run the output which should be in a folder named obj and verify the output. There we go, our first Objective C app. For more info on make files within GNUstep see the reference manual.

Friday, November 12, 2010

Tips for Surviving NY Transit

Transit in the NY Metropolitan can be an exhausting nightmare or it can be a fun adventure.  Like most things in NY it all depends on your reaction to it.  Through a series of trial & error below is a list of things to do to make your way about NY area transit more enjoyable or at least less unenjoyable  ;-)

Plan ahead
Even simple trips doing from one part of Manhattan to another can turn into an hour if you get lost or have to walk 20 long blocks.  Manhattan is a deceptively large place and just because it looks like a short walk on the map doesn't mean it is.  Take the subway as many connection to get as close to your destination as possible.  Trust me, you will get plenty of exercise going up & down stairs and walking a few blocks from the subway.

Google Maps (web & mobile version) do an excellent job of providing directions & connections through NY transit but don't rely entirely on it because you will find yourself underground without a signal and if you cannot read a subway map then you will have to resort to begging complete strangers for help.

Streets in Manhattan are like a grid and they are very straight and consistent.  Numbered streets are positioned North (higher numbers) to South (lower numbers) and avenues are positioned East (lower numbers) to West (higher numbers).  You can use these numbers as a compass and easily figure out which subway to go on since most subway lines in Manhattan run North (Uptown/Bronx) to South (Downtown/Brooklyn).

Don't Rush
It's tempting when going into the subway to be coming down the stairs and hear "Ding... Ding" and think: "That's my train".  It may be the completely wrong train or the right line in the wrong direction because remember each line goes in two directions (unless you are at the end of the line).  You will find yourself on a train on occasion after rushing onto the wrong one, always double check yourself and make sure you are on the right line and going the right direction.  It's not a big deal to get off at the next stop and go the other direction.

Avoid the Bus
If you live right near a bus stop that drops you off within walking distance of your destination then you cannot complain too much.  For everyone else the unpleasantness of the stop & go driving on top of the unreliability of the bus makes it a terrible way to travel not to mention the Manhattan Bus Terminal being a daunting place to learn the NYC bus system by.  Stick to the subway for simplicity & affordability.

During rush hours avoid them empty seats
Choosing a seat with empty seats next to you just allow anyone to sit next to you and during rush hour the entire place it going to be packed and face it you don't want the smelly guy that takes up two seats sitting next to you.  Men, if your choice in seating is between an attractive young lady or an unknown quantity (and the possibility of overweight & smelly sitting next to you) you know what you are going to pick.  Ladies may choose to sit next to a young clean guy or choose the empty seat and stand the risk of sitting next to a bum rambling to himself or mole lady.

Choose the Train (heavy rail) for Long Distances
The train is blazing fast over long distances.  I swear I don't have time to even do small amounts of work before arriving at destination.  Train rides will cost about double the fair of the subway but if your time & comfort is more important than choose the train.

Sidenote: La Guardia Airport Sucks
La Guardia is an awful airport.  Commuting to it is terrible because you cannot take a train or subway without having to transfer through a slow ass city bus.  Also the terminals are disconnected which means if you get dropped off at the wrong one you cannot walk through corridors to get to your desired terminal.  Choose JFK (my 1st pick) or Newark (in NJ). Sidenote's sidenote: also JetBlue rocks if you have a chance to fly them, they make flying pleasant again).

I have a terrible sense of direction and I've gotten lost plenty of times, went the wrong way on the wrong line and wound up in Brooklyn instead of uptown, just work smart not hard in the NY transit system and you will be finding your way around in no time.

Sunday, November 07, 2010

Relocation to NY

I haven't blogged lately, mostly because over the summer I took a job at Infusion Development to work as a consultant in New York.  Development in New York is mostly centered around financial services which provides inherently more complicated business processes than most industries.

For the previous two years I had worked at Loomis in Houston and I have enjoyed my time there.  We worked with many banks and retail establishments which offered a lot of opportunity for integration and working with cash management systems.  I also had the opportunity to work with some people in IT that I really appreciated and

In my short time here, I have enjoyed myself working on a project with one of the banks, developing on a trading platform.  Some of the challenges working on a WinForms trading application are: multiple threads & concurrency, separation of concern in a traditional WinForms app and the performance on a real-time system.

Relocating a family and settling in takes time but as things return to normal I'd like to blog about some of the following things I've been thinking of:

  • Learning Objective C on Windows
  • A fluent API for UI development
  • Surviving a .Net 2.0 Project and enjoy it
Infusion is hiring Senior .Net programmers if you are interested in relocating to NYC and have a passion for development send me a message.

Monday, April 26, 2010

NDepend 3.0 analysis of NAsserter

NDepend is an effective tool for analyzing .Net assemblies and provides information so that you can have an idea of whats going on. There are use cases for this in our development cycles.  For the purposes of simplicity I'm going to show the usage based on analyzing NAsserter.

I recently posted some code to Google Code called NAsserter. NAsserter started off as a proof of concept for prototyping something I had been able to do within Unit Tests (being able to make fluent style assertions in code) except for the purpose of throwing exceptions in code. This is the first fluent API I have written.

The API for NAsserter started as a small simple class and grew bit by bit. I tried to refactor as much as it made sense to me. I didn't model my internal constructs after any other fluent library as most of them have a need for much more extensibility than this. The biggest inspirations were NUnitEx, NUnit's constraint based model and Fluent Validation. These three projects provide exactly what they aim to, in which NAsserter is not intended to overlap. NAsserter is NOT a Unit Testing or Validation framework. It's simply for throwing exceptions in a predictable manner, including the messages. Thanks to Tuna (NHibernate & Castle contributor) constructive feedback.

Upon getting a version of NAsserter (0.1) released that I am comfortable with, I proceeded to analyze it with NDepend; which I am still learning.


One of my favorite sections of the report is the assembly metrics which shows how abstract, stable, complex and well commented the code is.  I think the metrics of what you are looking for may be a little different based on if you are developing a framework (even the type of framework) or enterprise systems.  For instance, often times frameworks developers will make compromises in design for simplicity of use which is pragmatic:  use common sense.


NAsserter is a simple codebase which shows through the analysis (the only dependency is mscorlib the .Net CLR) and doesn't really do NDepend justice. NDepend is nice on large projects with a number of dependencies, especially for keeping track of different design metrics. I am still learning the tool myself and I am finding new uses for it continually. You can track your project's progress on different metrics since it keeps a baseline of the metrics. NDepend is also very helpful for code reviews to be able to have an objective analysis of code, reducing some of the human element.

Thursday, April 15, 2010

Generic Singleton Factory

Not too long after writing and blogging about a generic singleton base, I changed the code to use a Factory - a singleton factory to be specific. Below is a factory which can be used to create a singleton instance of any class. The original singleton base class implementors needed to be sealed or have unintended consequences of getting an instance of the wrong class. This caused me to reflect and conclude that the design was deceptive as it was almost in essense a factory.

Below is a refactored version which is a little more genuine. This is my first crack, and requires generics. I do not use this everywhere I use singletons but where the usage of a Factory fits better than a singleton such as when you have many implementors of the same interface and you want singleton creational behavior.

Jon Skeet's has a great article on some different singleton designs in his blog.

Wednesday, April 07, 2010

Automatically mapping objects of same derived types

I had a need to automatically map all properties from one class to another class. These two classes had the same derived type, this was by design and not by accident. FYI: this example's Unit Test uses NUnit (2.5), NBuilder, both are optional as the test below can be easily adapted.

The scenario goes like this: you have a base class called BaseTransaction with derived classes DebitTransaction and CreditTransaction. Often where there are many properties from the base class to map, it's redundant to write and tedious. This bit of reflection below iterates through each property of the base class and maps it to a new object that it creates and returns this object.

The following unit test shows the usage of this function, as well as outputs to the console showing that the bases members were in fact mapped. Each derived class has unique properties of the same name (TransactionId), neither of these were mapped - otherwise an exception would have been thrown during the reflection code (prop.SetValue...).

Thursday, April 01, 2010

DRY is dead, long live MOISTURE

DRY has become a big buzzword these days that puts emphasis on reusability. While there are some advantages to reuse, I'm going to look at the downside; having DRY applications which are rigid crack over time due to the lack of Moisture.

What is Moisture? It is the syntactic sugar that makes procedural languages like JScript, VBScript, FoxPro and T-SQL powerful and fast. Unless you've been hiding in a cave, you have started migrating from an ORM (such as NHibernate) to more future-proof constructs like Stored Procedures or DataSets.

In the past, the only downside to Stored Procedures was that Refactoring them took a lot of effort. However, JetBrains has recently announced ReProcedural to which lets you refactor code written in VBScript, Microsoft JScript or T-SQL

Once you have moved all of your business logic to stored procedures, just plan on having an average of 4 stored procedures per table (for insert, update, delete and select). In a medium sized system with 50 tables, it's completely acceptable to have an upwards of 200 stored procedures or more. At this point, your team should have enough T-SQL work to justify having a DBA letting you focus on increasing system Moisture with procedural programming

Finally, you will want to rewrite any aspects (AOP) as table triggers. For non-DBAs out there, triggers are essentially AOP for databases. For instance, if you wanted to implement logging your pointcut will either be your Stored Procedure or your Trigger.

Remember the basics of Moisture: the more OO code you can migrate to a procedural language, the better. While you can do procedural programming in C# or Java, it's not something enforceable as there is nothing stopping some n00b developer from creating an Interface or an Abstract Class. As a general rule, all methods should be public and static

April Fools!!! :-)

Wednesday, March 17, 2010

Utility function to facilitate Domain AddChild functions

As I make certain domain models more rich, one of the first things I will do is make the property of Child lists on the target domain model to a setter that is internal or public:

There's nothing wrong with this code, it's short & concise. My only problem with it is that there is a repeatable pattern here, we are always going to check to see if the child is null, we will always need to check for the nullability of the target list, etc, etc. If we could centralize this pattern, then if it changes we could change it there too. The silver lining being that if we can reduce it to one line of code and that is always a good thing :-).

Utility Function for Adding Child to Parent: Usage:

It works pretty well and I've ran unit tests against it for both generic lists and non-generic lists. I first started off thinking I could do this with delegates, but I concluded that this code was not a proper use of delegates. Feel free to sound off if I've gone completely mad or if there is a better way to do this.

Monday, February 15, 2010

Unit Testing Daos with NHibernate with SessionScopes Version 2

In a previous post I outlined how to modify Ayende's post to support contextual sessions. With Contextual Sessions in NHibernate instead of injecting a Session into each DAO you will be injecting a SessionFactory in which the caller will invoke the SessionFactory's GetCurrentSession() in order to get the session tied to the context. The previous example I mocked the SessionFactory and stubbed the GetCurrentSession() to return one session that would have been open for the life of a TestFixture.

This really isn't necessary if you bind the SessionFactory to a context. This is very easy with NHibernate and the only requirement is that you tell NHibernate through it's configuration the scope of your session context.

Something else I've thought about was that each TestFixture should only every test one DAO. The tests in said fixture should also only ever reference one DAO to be an independent test. Therefore if you are testing and a function from your DAO and need another object from persistence it would be better to call get the persisted object directly from your Session than from a separate DAO. Too often I see people trying to reuse objects in their Unit Tests which violates the integrity of the tests because they would no longer be independent.

Therefore it would be nice if the InMemoryDatabaseTest exposed the target DAO to the TestFixture to make it easier, it could also set the SessionFactory of the DAO. We can do this easily with Generics:

I have extended my existing base test fixture InMemoryDatabaseTest so that I don't break compatability with existing tests. All my new DAO TestFixtures will inherit from the new Generic version. I have also added some overloads for debugging. If you pass a true debug flag to the constructor it will output the SQL to the output Window. Also you can pass in a path to an actual SQLite file/db which will let you save the changes. This is helpful for complicated tests where you want to see what is being saved to the database and test the queries NHibernate is executing against SQLite.

BaseDao that all your DAOs inherit from to facilitate contextual sessions. This code should be in a separate assembly I call (rootnamespace).Data.Common InMemoryDatabaseTest that your test fixtures would inherit from. This code should be in a separate assmebly I call (rootnamespace).Testing.Common Usage

As you can see, the DAOs Unit Test didn't have to instantiate an instance of the target DAO since it already specified it as a Generic paramter. While this only eliminates 2 lines of code it more importantly enforces one DAO per test.

Thursday, November 19, 2009

Mapping Date & Time fields With NHibernate

Let's say you have an entity or POCO that you have mapped from NHibernate (or any ORM) and the database has separated out the Date & Time values into separate fields.  Your best best is to map these Date & Time fields into properties (DateTime for Date and TimeSpan for Time).  Then create a helper property in your POCO to add them together.  I'd like to add that I'm not a fan of separating these sorts of things in the database, but some people do this for some reason:

HBM:


POCO

In my case either of these could be null (yes another great idea) which means I had to handle the nullability however this illustrates at least in worse case scenerio what will happen.  Date & Time data types are available in SQL Server 2008 and work with NHibernate 2.1 with .Net 2.0 or above.

Monday, November 16, 2009

Associating Users & Logins in SQL Server after Database Restore

Often times when you restore a database in SQL Server from one server to the next the Logins will become disassociated with the User a specific database.  We ran into this today and another software engineer found a good script from a guy he knows:



Executing this script should find unassociated logins and reassociate them with the users in the current database

Friday, November 06, 2009

CI Done Simple with CruiseControl.Net + MSBuild

If you want to setup Continuous Integration the learning curve for automated builds can be moderate for some. CruiseControl.Net (CCNet) allows you to integrate with automated build technologies such as NAnt, MSBuild, etc.  The advantage of this is that you can specify the Visual Studio Solution so that MSBuild knows the references and source code to build.

This example assumes using TFS for source code control, which definitely isn't my favorite SCM tool but odds are if you want to keep it simple and you're not using NAnt then you're probably in a shop that uses TFS.

Sunday, October 25, 2009

Alt.Net Google Reader Bundle

Google Reader is a great way to subscribe to different RSS feeds because it enables certain social networking features on top of them.  If you are "Sharing" with other users then you will see what other users in your network liked and their comments.  It also makes it very easy to send links to people via email.

I created an ALT.Net Google Reader bundles a while back that I try to keep updated with different ALT.Net blogs that I subscribe to.  To subscribe to this bundle click the link below and then click the link "Subscribe".
http://www.google.com/reader/bundle/user/03066432769507324653/bundle/Alt.Net

You can expand the feeds to see what you are subscribing to and even remove certain feeds after you add the bundle.  If you have an ALT.Net blog and would like your blog added to this bundle just send me a message on Twitter or leave a comment here.

Tuesday, September 29, 2009

Practical use for NUNit 2.5's [TestCase]

Since NUnit 2.5, NUnit has supported a concept of Test Cases.  Briefly a test case to NUnit is a test which runs with a different set of parameters and can expect a different set of results.  This has the potential to minimize the amount of code required to write new test methods.

To this point I've been using standard [Test] attributes and since seeing this attribute in the documentation I've been thinking about uses for it.  Now that I've started using [TestCase] I've thought of some other uses for it cutting my test fixtures down to 1/2 or less the size previously.

Below is an simple example of the code without the [TestCase] using the traditional [Test] attribute:


The above code can be trimmed down to one function using the [TestCase] attribute:



The other beautiful thing about [TestCase]s is that it collapses each test case underneath a node which actually looks cleaner:



A couple of notes on the code above.  The compiler (C# here) will not allow you to use object initializers as a parameter to the [TestCase] so you cannot create a test function Validate(object myUser) and do something like below.



This is because the compiler will only allow constants in attributes, however if you really need something like this, NUnit allows a work around. This is documented here.

Sunday, September 27, 2009

Houston TechFest Samples

Houston TechFest was a lot of fun, I attended some very interesting sessions and had the opportunity to present on the topic of NHibernate.  I have uploaded the samples and they are downloadable by clicking here.  The presentation is available here.

Wednesday, September 23, 2009

Unit Testing - Mocking to test Edge Cases with NHibernate

Sometimes in code you want to test edge cases, some of these can be difficult to test even with integration tests because of database constraints, etc.  This may be a business key or unique identifier (that's not a primary key)- may be enforced or not.  The key is you make an assumption that in code you want to test for.  Mocking dependencies is the key here, to create behavior that would not otherwise be possible.

Unlike the pattern illustrated by Ayende or that I added onto here, I wanted NHibernate's SessionFactory and Session objects to return data that I could not return from the database because of unique index constraints.

In this scenerio I'm returning data from the database that matches certain values and it should always return a list that contains either 0 or 1 objects otherwise it throws an exception:


Problem is that integration tests are unlikely to uncover this error with normal data and end user testing won't uncover it either.  This is simple, but I want to make certain that the exception is correctly thrown.

The only tricky part really is that after mocking the ISessionFactory & ISession objects you need to also mock each ICriteria object returned from the Session object.  So with Rhino Mocks after telling it to expect a call to CreateCriteria that returns an ICriteria, we also need to create expectations for this result calling Add and its result calling list.  This is because fluent interfaces use method chaining which makes this part a little tedious:


This allows us to now test what would actually happen if more than one Animal objects were returned.  NHibernate makes this easy because there are interfaces for pretty much every object.

FYI: this code uses Rhino Mocks, NBuilder, NUnit & NHibernate