Thursday, April 05, 2007

Exception Raising v DBC

I was reading an article on DBC and realized that I disagree with some of the points.

In particular I think its better to specify the contract in .NET using the comment and associated exception, to me its far more meaningful for the parameter comment to say what the parameter is and an exception comment to explain anything else:

///

Gets the user for the given ID.
/// Should be > 0
/// is less than 0.
public User GetUserWithIdOf(int id, UserRepository userRepository)
{
#region Preconditions

ArgumentValidation.ThrowIfNegative(id, "id");

#endregion

This sort of approch is documented on code project.

One other thing that worries me is when people talk about using exceptions for "exceptional" circumstances. I personally buy more into the approach Microsofts "Framework Design Guidelines" book pushes for: "If a member cannot successfully do what it is designed to do, it should be considered and execution failure and an exception should be thrown".

Therefore if a repository has GetById and it can't get the object what do we do? Do we return null and leave it to the caller to decide what to do, or do we be more explicit and rename our method TryToGetById if it is not going to raise exceptions. I choose the latter and in fact NHibernate uses this sort of approach where ISession.Get does not raise an exception if it can't find the object but ISession.Load does.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Saturday, March 31, 2007

Persistence Ignorance and Associations

One issue that seems to come up regularly in the team I'm on is how to design associations between persistence ignorant domain classes, or more particularly how to do it without falling into bad design practices.

Let me provide an example of the sort of problems that come up. Let’s say we have an abstract Company class which is the base class for two concrete classes:

  1. Agency - Contains a collection of Clients.
  2. AgencyNetwork - A collection of agencies that work together.

A Client is associated with one Agency and an Agency has 1+ Clients. An AgencyNetwork is associated with 1+ Agency objects, with each Agency in 0 or 1 AgencyNetworks.

The original solution is much like this (I've simplified it to show in a class diagram):

Note here that Client is coupled to Agency and Agency is coupled to AgencyNetwork with the reference being null if the Agency is not in a AgencyNetwork. The references are not bidirectional but they may need to be.

The reason the associations are like this is that we're managing the relationship from the "one end" as its simpler. Now here is what I don't like about this design:
  1. AgencyNetwork is currently only used by one of our application so having our key Client class indirectly coupled to it seems like a very bad idea. I'd prefer our core classes, which the majority of our applications will use, to be coupled to as few non-core classes as possible.
  2. I'd prefer if our design made it clear what the real world associations were, I don't think this design does.
  3. I don't like the idea that the way you find out if an Client is in an Agency is like this: if(Client.Agency != null).
  4. As I see it in a lot of the time you'll want to use an Client without knowing about a Agency/AgencyNetwork but if your working with a Agency it's likely that the first thing you'll want to do is manage the collection of Clients.

This is my alternative soluton:




Although I think its much better this solution it is not perfect either (things never are).

In object oriented terms I prefer it as Client isn't coupled to the other two. I also think that when you get an AgencyNetwork the first thing you'll want to do is look at the list of companies in it. In addition I believe that the associations are far more natural, they reflect the real world associations far better.

The disadvantage of the second solution is that managing the relationship becomes more complex. With the first solution you could do this:

// change Clients Agency
client.Agency = newAgency;

// if the Agency is in a AgencyNetwork take it out of it
client.Agency.AgencyNetwork = null;


Personally I think this is incredibly ugly and does not reveal the intention very clearly but it is short.

With the second solution its more complex, not least as the Agency now handles the association so you have to do this (note we’re using the repository pattern here):

AgencyRepository agencyRepository = new AgencyRepository();
Agency oldAgency = agencyRepository.GetForClient(Client);

oldAgency.Remove(Client);
newAgency.Add(Client);

Although it involves more code I think this is much clearer, however where do we put this code. We cannot put this in the domain assembly as we don't want our persistence ignorant domain layer to access repositories. We'd therefore need to do it in the domain coordination layer:

public static void ChangeClientsAgency(Client client, Agency newAgency)
{
... as shown above
}


The question is thus which solution do we prefer:

a) Solution 1 - Have the one end (which will often be one of our key/core classes) manage the relationship and so enforce things that way (resulting in a lot of coupling).
b) Solution 2 - Decouple the classes, add the associations that we think make most sense and then have to explicitly manage the relationship.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Friday, March 30, 2007

Domain Driven Development Example (.NET) - Codeplex

I've setup a Codeplex project as I've been thinking about doing a simple .NET DDD example and I think it's time to go ahead with it.

I haven't even started mapping the classes to the database but I'm hoping that it will be useful, at the very least it'll give me a place to try things out.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

ORM

Interesting little ORM article at serverside : http://www.theserverside.net/tt/articles/showarticle.tss?id=ShiftinNETORMs

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Domain Driven Development Example (.NET) - Idea

I've been thinking about putting together a simple .NET based DDD example for a while and I've finally put some time in over the last few weeks.

The idea is to show one way that DDD can work with .NET/NHibernate but also to give me a chance to try things out, who knows if I'll ever get anywhere with it though!

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Associating Rules With Object States

If your developing an information management system then its quite likely you'll need to be represent and evaluate large numbers of business rules in your domain model. For example if an Order over £10,000 must be authorized by a Manager then we'll have to represent that somewhere in the domain.

Before looking at how to represent the rules its worth thinking about how you'll evaluate the rules. One option is to have an IsValid property on each domain object that has validation rules, however the question is then "valid for what"?

If we mean persistence then we should rename it as IsValidForPersistence. This might be useful as if an object was valid for its current state (e.g. Active) when it came in from the database then when we save it we will expect it to still be valid for that state.

However although IsValidForPersistence might be useful it doesn't give us all the functionality we'll need because in many cases the validation has to be state based. As an example we don't mind an unauthorized Order over £10,000 sitting in the New state, we only need it to be authorized by a Manager before it moves to the Active state.

We've solved this by using state based rule methods, so you could call order.GetBrokenRulesForTransitionTo(OrderState.Active) and get back a collection of BrokenRule objects with descriptions about the broken rules.

This works very nicely and has allowed our GUI to display a list of reasons that an object can't move to another state whilst at the same time allowing us, in the domain, to ensure that we can avoid state transitions that the object is not yet ready for.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Team System And Agile

Having used Team System for about a year now I've come to quite like it, bits of it could be improved but as a developer it is quite a nice environment to work in.

However there is a serious problem with its usage within an agile team, the problem being the outrageous cost of getting users involved.

For example we want to get our users involved early on in the requirements process and to do this we're planning to use a user story based approach. Personally I think it'll work far better than the requirements document or use case approaches that I've used in the past.

Anyway to make this process work we need a way to get our users involved and since they are at the other end of the country from us we have to look at combining software with regular phone calls.

With this in mind I've used the Process Editor bit of the Team Foundation Power Tool to create a custom user story work item and we're getting our users to trial TeamPlain so that they can see/modify the actual work items.

The idea is that they specify the work item and that it will then move through multiple states. It will start in a new state, once the users have specified acceptance tests they can move it to a signed off state, we in the development team will than handle moving it to the in progress and complete states and finally when the users get the release they can use the acceptance tests to test the functionality before moving it to a closed state (if all goes well).

I think this should work fine and, despite a few issues, TeamPlain likes a good tool for our users to play with.

The only problem, and its a huge one, is that in order for our users to interact with Team System in the way we want them to each of them will need a client access license. This will add massively to the cost of team system and goes against the aims of agile to a point that seems ridiculous.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Monday, February 05, 2007

Domain Coordination Layer

On my current project we've had a lot of success using a persistence ignorant domain with NHibernate and repositories being used to manage persistence.

The domain assembly does not reference the persistence classes in any way which has made the domain very easy to unit test but it does come at a cost.

Lets give you one example of a problem this persistence ignorance creates.

We have a Customer which has multiple Orders. Each Customer has a default FeeGroup and each new Order associated with the Customer must go in the FeeGroup to ensure that any fees are correctly used (we can later move an Order into another FeeGroup as necessary).

Our first solution might be to have an association from Customer to FeeGroup. The transitive persistence functionality in NHibernate would handle the persistence for us.

The problem with this is that Customer is a core class and FeeGroup most certainly isn’t. To emphasize this lets that in fact Customer is in CoreAssembly and FeeGroup is in FinanceAssembly, FinanceAssembly is used by a small number of applications whilst CoreAssembly is used by lots of applications.

In this case we will probably want to avoid CoreAssembly referencing FinanceAssembly, otherwise everytime we add a reference to CoreAssembly we'll have to add a reference to FinanceAssembly too.

This does however leave us with a problem. If a Customer does not know about its default FeeGroup, and if we want all new Orders to go in to the default FeeGroup, then how does the domain look up the default fee group?

This is what we need code to do:

  1. Look up the default fee group for a client using the FeeGroupRepository (Evans repository pattern).
  2. If the Customer has no default FeeGroup then create one, use the FeeGroupRepository to save it and then assign it to the Customer.
  3. Pass all the data needed to create the Order, along with the FeeGroup, into the OrderFactory.

We need somewhere to put this code. The problem is that if this logic is in the process layer then other applications cannot reuse it. It is also confusing that the FeeGroup is passed to the OrderFactory, the only way we can specify that it should be the Customers default FeeGroup is using a comment on that method. Plus we've now coupled our core Customer class to FeeGroup which is unacceptable.

The solution was to add a static OrderCreationService class. The OrderCreationService has a single static CreateOrder method that has all the logic specified above, so it lookups or creates the FeeGroup as required, then uses the OrderFactory domain class to create the Order before finally adding to the FeeGroup. It then calls into an internal method on the OrderFactory which will create the new Order.

This works well because the OrderCreationService can be in the same namespace as Customer/Order. Users will thus find it quite easily.

However the question is which assembly should we put OrderCreationService into. It can't go in the process/application layer as I don't want to move domain logic (even coordination logic) out of the domain and I also wan't the coordination logic to be used by all applications. It also can't go in our persistence ignorant domain because that will couple my domain assemblies to persistence and to each other in ways that I want to avoid.

The solution was to create new Domain.Coordination layer/assembly. This think assembly provides a coarse grained interface, with an emphasis on static classes and services/factories needed to organise the domain classes kept in the domain assemblies.

There are definitely disadvantages to my solution, one is that the Domain.Coordination layer is coupled to CoreAssembly, FinanceAssembly and any persistence assemblies involved. There isn't any easy way to avoid this, something has to be coupled to those assemblies.

Anyway although it adds a bit of complexity it has several advantages:

  1. Helps decouple our domain assemblies (at the cost of coupling the domain coordination layer itself).
  2. Helps us maintain the persistence ignorance which is important as it keeps the domain simple and makes it more testable.
  3. Ensures that coordination logic will be accessible by all applications that use our domain.
  4. Since the classes in the domain coordination layer are in the same core namespace as the other domain classes people will locate them easily.

I chose the term domain coordination as I think it emphasizes what the layer is there for.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Saturday, October 07, 2006

VSMDI Files - Continued buginess

One things really bugs me with VSTS is the VSMDI file, it causes all sorts of issues which I've now started reporting to Microsoft.

One of the most annoying issues is that you sometimes get multiple VSMDI files.

Now I'll admit that I was worried about reporting some of the bugs because they're intermittent and I haven't got reliable steps but in the case of this one I found lots of posts on the Web relating to similiar problems so I was sure it was worth reporting.

Microsofts response was to mark it as non-reproducible. Well yes, fair enough, but if quite a few of your customers are reporting it then why not leave it open and just wait till someone gets repro steps?

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Thursday, October 05, 2006

Applying Domain-Driven Design and Patterns - Boring Rant

If you haven't read Jimmy Nilssons book on DDD in .NET this will be boring, in fact its probably boring even if you have read it.

I should first say that I like the book but have issues with it as I explained in my Amazon review for it. However there's one part of the book thats annoyed me quite a bit, and I think it displays a problem that seems to happen when the authors in books don't think enough about the readers.

Its the section on "Test-Driving A Web Form" in chapter 11.

First off I won't be rushing out to unit test GUI's left right and center, especially not when it adds to the complexity so much. However its an interesting topic that could have been quite enjoyable to read about...

...except for the fact that the author of that section seemed to be more interested in force feeding the reader his views on unrelated topics.

In particular the author doesn't like prefixing I on interfaces. Fine. However it annoys me that his examples don't use the prefix despite the fact that the majority of his readers and (nearly) the entire FCL uses it. He even goes as far as to stick an entire page in the middle of his discussion describing why he doesn't use the I prefix. Its ridiculous, all he's done is confuse and sidetrack the reader with information that would have been better in an appendix (or at the end of the section, or in the bin).

Anyway I think his argument is questionable, even if every developer now stopped using the I prefix we'd still be stuck with it on all the existing interfaces. Do you really want people reading your code to have to deal with a prefix that is only used on some interfaces? I think not. Anyway interfaces are treated differently in languages that don't support multiple inheritance so I find the seperation useful.

Even if the argument wasn't weak though, and even if I felt the I prefix was the cause of global warming AND the darkness in the hearts of men, I wouldn't want it to be shoved down my throat in the middle of a discussion about something completely different!

On the flipside if you want examples of books that give you lots and lots of information in a relatively concise manner, that are enjoyable to read and that have good code examples then I'd recommend looking at Robert C Martins agile development book and Eric Evans DDD book.

Both are superb. Heck I'd rather read the Java samples carefully chosen by people like Robert Martin or Eric Evans than the C# examples in some C# books. Put it this way would they put code like this in an example:

// using A=NUnit.Framework.Assert
A.AreEqual(SrcPanel, "a> b> c ");

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Saturday, September 30, 2006

AOP

One thing that interests me a lot is AOP, I can definitely see the benefits but so far I haven't had time to try it out.
Has anyone out there used it successfully on a real project and how did it affect the complexity of the codebase and performance?

So far I haven't had a good reason to try something like Spring.NET out but I'm hopeful that I will soon. I'm also looking foward to the Aspect Oriented Refactoring book

One project that also looks interesting is:

http://dotspect.tigris.org/

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Thursday, September 28, 2006

Mini-Microsoft

If, like me, you've never heard of Mini-Microsoft then you might find this blog entry very interesting.

I'd always, naively, believed Microsoft would be a great place to work...maybe not.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

TypeMock - Designing For Testability

A while back I posted on the reasons I thought TypeMock was so useful, namely because I thought decoupling your classes to allow mock instances in wasn't a good way to design. Anyway Roy Osherove now has links to interesting posts on the topic in this blog entry.

I must say I'm still not sold on the idea that designing for test is the right way to decouple your classes in ways that are useful.

Since most of the unit testing is going to be of the domain layer let me explain my views on why TypeMock helps there.

Lets say that I want my domain layer has to call out to infrastructure code. My first thought would be is that really a good idea? If it is then I want to decouple my domain from the infrastructure as much as possible. So in that situation an interface/dependency injection might be the way to go and you might do that during testing.

However I've found that when I want to do real unit testing I'll want to mock quite a few different classes that are depended on and in many cases the depended on classes are also in the domain layer. In those situations interfaces/factories seem overkill, in fact if I put them in I'm just over-complicating things. Thats when I use TypeMock.

Another thing I've realised is that these I only do state based unit testing and have given up on the interaction based unit testing that mocking (and things like TypeMock/NMock) support. I guess I should rethink that.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, September 27, 2006

NHibernate + Generics = Explained a bit better

A friend of mine pointed out my post on "NHibernate + Generics = Small Codebase" was a bit vague so I've added this which might clarify.

What I was trying to say was that combining generics with NHibernate makes writing and testing persistence code very easy. For example here's some code that could save a persistent class using NHibernate.

   Session.Save(toSave);

You want that code to be somewhere outside your domain objects, Evans says to put them in classes called Repositories. You'd have at least one repository per aggregate root, so you are going to end up with quite a few of them.

A base class thus makes sense as all the repositories have a lot of behavior in common. However you want type safety on the methods so putting this in the base class just doesn't cut it:

   public virtual void Save(object toSave)

The solution is obvious, you just use generics with a repository base class:

   public sealed class MyRootRepository : NHibernateRepository<TMyRoot, int>
   {
      .... custom code including extra queries ...
   }

The base class can thus use the type of object its persisting (MyRoot here) and the type of ID field (int here) when it needs it.

I think there is also a big advantage when using generics for persistence testing. For example we have specific tests we want to do for all aggregate roots including concurrency/update/save. We want to do the tests to check the database AND the mapping files are correct but we write the same code each time so we use inheritance from a generic base class:

   [TestClass]
public sealed class MyRootPersistenceTests : AggregateRootPersistenceTestBase<Myroot, int>
   {

      [TestMethod]
      public void CanPersist()
      {
         TestPersistence();
      }

      [TestMethod]
      public void CanUpdate()
      {
         TestUpdate();
      }

      [TestMethod]
      [ExpectedException(typeof(StaleObjectStateException))]
      public void CanHandleConcurrency()
      {
         TestConcurrency();
      }

      # region Overridden Members

      protected override MyRoot CreateAggregateRoot()
      {
         // create and return a MyRoot
      }

      protected override void ModifyAggregateRoot(MyRoot original)
      {
         // modify original
      }

      # endregion
   }


We have similar base classes for a few other situations (non-root aggregate parts, read-only reference data). In each case the vast majority of the code is in the base classes (or other classes they call) and we just use the template method pattern by calling into the abstract members (such as CreateAggregateRoot).

Note that the base class can create an instance of the repository, because we decided to make our NHibernateRepository concrete. In addition the whole thing works because we've written an ObjectComparer class that uses reflection to compare the property values of two instances of a type. The TestPersistence in the base class thus boils down to:

  1. Get the object by calling CreateAggregateRoot
  2. Save the object to the database
  3. Reload the object from the database
  4. Use the ObjectComparer to compare the original and reloaded objects.

Unfortunately each test class must have the test methods (CanHandleConcurrency etc) because although NUnit let you have test methods on a base class VSTS doesn't. Drat.

Anyway this has proved to be very useful and has definitely been a big time saver as we've been moving code across to using NHibernate. I've found my current working style is:

  1. Use TDD to develop the new feature.
  2. If the new feature involved the addition of new fields that need to be persisted then run the persistence tests.
  3. The persistence tests should now fail because when we reload the object and pass it to ObjectComparer it will find that the original object had a value in the new field/property whilst the reloaded object will have the default value.
  4. Add the appropriate content to the mapping file so that the new field is persisted.
  5. Run the tests and they should now pass.

Oh and ignore the repository base class name and the method names, we have reasons for keeping them that way the minute.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Friday, September 08, 2006

Team System

I finally got round to reading this blog entry about the whole Mort/Elvis/Einstein thing. I must admit I'm not overly worried about Microsoft using the personas but I do agree that Rockfords article is slightly questionable.

Anyway one thing that definitely chimed with me was part way down:

There's not much value in taking customer feedback if you stop acting on it. Microsoft’s addiction to waterfall planning practices have sent a strong message to customers regarding Microsoft’s responsiveness late in waterfall development phases. Antiquated project and product management practices are hurting the perception that Microsoft is really interested in feedback. You’ve gotta be continuously responsive all the time, not just early in the game. Maybe if there was some effort to “scrum” a service release earlier than mid-2006 the product feedback center would still have the same credibility it did during the pre- and early Whidbey betas.

I couldn't agree with this more, I've been using Team System for 3 months now and two things have surprised me.

Quality
I'm not a Microsoft basher, in fact I've always been impressed they can release large scale software projects that are of a high quality. I am also happy to forgive an application for the odd crash or the odd problem. However Team System is without doubt the worst Microsoft application I have ever used. It comes down to quality, which I'll discuss later, and the fact that some of the features seem to me to be badly thought out or are very incomplete.

Its not even one area but large swathes of the features that have problems including source control, check in policies, unit testing and code analysis. In many cases they're hard to use, seem to be badly thought and are quite buggy. Here's some of the issues I seem to end up dealing with:

  1. Some files will not be checked in because I moved/renamed/did something else to the folder they were.

  2. The unit tests will fail/abort. There seem to be many reasons for this, I should really start taking screenshots and just reporting them to Microsoft even though I don't have steps to repro.

  3. I won't be allowed to check in because it wants me to run deleted tests.

  4. The code coverage will run but not report the issues as stopping me checking in.

  5. The code coverage will fail with a stack overflow exception (I had to switch off CA2214 because of that little bug, how much fun do you think I had working out it was that exact rule :))

  6. My pending changes area will show up as empty forcing me to restart.

  7. Visual Studio regularly crashes (often when I'm undoing source control check outs), in some cases it offers to send Microsoft information but in most cases even this doesn't happen.

I've reported some of these issues but some are so intermittent and bizarre that I haven't gotten round to it yet, however I'd say that on average I'm hit by atleast 1-3 crashes a week and two of the other issues per day and I know that the developer I work most closely with is also having similiar problems.

Customer Feedback
Like a lot of people I've used NUnit, FXCop, Resharper so when I came to Team System I was very excited. However as I tried to use the refactoring, unit testing, code analysis, class designer and so on I began to find a lot of limitations. What amazed me was that many of these limitations were reported to Microsoft quite some time ago. For example here's three of the issues that bug me:

Unit Testing Inheritance

Class Designer Displaying Dependencies

Compile Time Code Injection

What links these items is that the last replies from Microsoft to them are in 2005 or earlier! For all I know Microsoft are investigating and fixing these issues, for all I know they're being ignored and thats problem...there's no 2 way information sharing going on.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Monday, September 04, 2006

Rolling Back After Database Tests - TransactionScope

For a while now I've been using Roy Osherove's data rollback attribute to ensure that integration tests against the database clear up after themselves.

Unfortunately I ended up having to give up on it because in the move to using .NET 2 and NHibernate I introduced a base class that all our persistence test classes should inherit from. It had the majority of the code needed to do persist/update/concurrency unit tests and was a big time saver. Unfortunately the class used generics, since generics and ContextBoundObjects are a big no-no (see this article) and since the data roll back attribute relied on you (indirectly) deriving from ContextBoundObject I needed to look elsewhere.

In the end I chose to use a TransactionScope, I create it in the test initialize and Dispose of it in the test cleanup method. It seems to work OK though I've occassionally had odd DTC related errors which is a slightly worrying!

Equally annoying is that my test base class idea falls down slightly as VSTS doesn't allow you to put tests in a base class (as described in this feedback item). This means that although I can put the majority of the test code in the base class I need to actually define the tests in the derived class, the tests then call back to the base class which will then call to abstract methods implemented in the derived class (normal template method pattern). What a mess :)

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Wednesday, August 16, 2006

Rolling Back After Database Tests - DataRollbackAttribute

If you do a lot of integration testing against a database and find you want to clean up at the end of each test then I highly recommend you look at the DataRollbackAttribute which is discussed in this blog entry.

I particularly like the way the attribute is used, very elegant and works very nicely. You can also modify the attribute to use TransactionScope, NHibernate transactions or whatever you need.

The only slight problem with it is that some of my tests were causing odd DTC errors when I ran them after applying this attribute, however I'm hoping that it will work properly when we move using NHibernate transactions (simply because we'll have a much simpler transaction management scheme than we do now).

Having said that at some stage I need to look at Ndbunit which also seems like it might be useful.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

NHibernate + Generics = Small Codebase

My company are going to use NHibernate for a few projects we're doing. I was heavily pushing for its usage because I believe it allows OOD, DDD and TDD (all the D's). However I've been amazed to find just how easy it is to use.

Essentially myself and another developer have been putting together a team project that the existing domain classes will move into. The most time consuming part is creating the mapping files for our existing classes, but if there isn't a tool out there to do that then we can write a stupid one that does the simple stuff.

Anyway its when you put generics and NHibernate together that I think things really get good.

For example to write an integration test that tests that persistence is running well you just need to do this:

  1. Create an instance of the class your testing.
  2. Use the NHibernate session to save it to the database and then flush the session.
  3. Evict it from the session. This needs to be done because NHibernate uses an identity map so if we don't evict then it will just return the same object (from memory) when we ask for it in the next step.
  4. Get the object, by ID, from the session. Since we evicted it in the last step this will cause NHibernate to reload it from the database.
  5. Compare the two objects (I wrote a reflection based helper class that does this automatically when passed two objects).

You might ask what the point of this test is, well it verifies that my database and HBM files are correct and that everything is working end to end.

I also think its worth writing these tests because its so easy, other than the first line of code you can reuse everything from one test to another by combining NHibernate with generics. To me this is wonderful and a big advantage of moving to NHibernate.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Monday, August 14, 2006

NDepend - Analysing Your Dependencies

A while back I started reading Robert Martin's excellent Agile Software Development, Principles, Patterns, and Practices book.

The books very strong on object orientation and a large section is devoted to how to manage dependencies between different parts of your application. Whats great is he gives some metrics you can use to analyse the dependencies in your application, which is a great thing to do.

Anyway the good news is theres a tool for .NET that applies Robert Martins metrics to an arbitrary bunch of assemblies then does a good job of displaying them, namely NDepend.

Unfortunately there are a few problems. Firstly, as many sites point out, it runs over the IL so the cyclomatic complexity figures may be a bit untrustworthy (this is admitted at the Website). No biggy.

Other problems are more difficult to deal with, for example the fact that enums are treated as concrete classes during the analyses so skew the results...which can be a big problem and in fact kind of put the breaks on my evaluations of the tool.

This is probably a case where the tool needs to be changed to use more knowledge about the language its analysing.

Anyway I suggest you have a look at the tool and book, in fact might be worth getting the C# version of the book which is out now (reminds me to go buy it!).

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone

Saturday, August 12, 2006

CSLA

We've been looking at this framework at my work for a while as we believed NHibernate + CSLA could allow us to get the advantage of an approach like .netTiers but with a few advantages:

  1. No need to generate large amounts of code.
  2. We would only use the features we need.
  3. Seperate, to a large extent, the design of the domain and database.
Anyway although CSLA seems like a good framework if your not going to use the mobile objects approach, and we aren't, then it adds a lot of complexity for very little gain. In particular for a Web application I'm not sure how realistic CSLA is. In our case we didn't like the delegate based rule code, we don't need multiple level undo, we don't need dirty tracking....

Having said that the binding code and a few other bits could be useful.

One bit I did find very odd in my reading about CSLA was the fact that call your persistence code from your domain objects was justified for encapsulation reasons and to avoid using reflection as it can hurt performance.

The reflection argument seems pretty redundanct as CSLA itself uses reflection quite widely and the cost of reflection isn't likely to be noticable compared to things like database or network calls.

Likewise the encapsulation argument seemed a bit questionable, there are certainly good arguments for not putting your data access code in your domain/business objects and indeed for not accessing the data access code from your domain objects.

Anyway so far we've used CSLA pretty sparingly and even the bits we have used, like the validation framework, are slowly being engineered out.

Share This - Digg It Save to del.icio.us Stumble It! Kick It DZone