CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeremy D. Miller -- The Shade Tree Developer

Under the hood and working with .Net, TDD, Software Design, and Agile Stuff
  • Let's see, if I...

    ...am facing a hard problem, that seems like it must be a common scenario, I should probably...

    Write an all new logging tool?  Um, no.

    Reinvent Sql?  Um, no

    Use IL generation?  Immediately stop whatever it is you're trying to do

     

     

    The correct course of action Grasshopper is to GOOGLE IT FIRST!!!!  If it seems like a function that should be in the .Net framework, it is.  If you think that somebody has to have already done this, they have.

     

    Listening to a friend, who shall go nameless to protect the victim's privacy, gripe about some co-irkers.  I like my job.
     

  • Before you use an IoC tool, some concepts to know first

     
    JEREMY’s NOTE:  I’m trying to rewrite the StructureMap documentation today, and I’m going to blog most of it out here as I finish it until Brendan tells me to stop polluting the main feed.  This article is intended to be an introduction to the concepts behind an IoC tool for folks with little or no previous exposure.  Feedback will be very much appreciated.
     
     
    From my original release back in June 2004:  StructureMap is a Inversion of Control (IoC) slash Dependency Injection framework that can be used to improve the architectural qualities of an object oriented system by reducing the mechanical costs of good design techniques.  Using StructureMap does not in any way improve your architecture per se, it simply strives to make the mechanics of a good Object Oriented Design cheaper to implement.  Additionally, StructureMap allows you to efficiently exploit a well designed Object Oriented architecture to provide extensibility mechanisms, flexible deployment options, and self validating configuration and deployment.

    Over the years a series of concepts and principles have been discovered and developed to describe well-structured Object Oriented systems.  To most effectively use StructureMap, or any other IoC tool for that matter, your system needs to be designed with these principles first:

    To sum it all up, well designed Object Oriented systems are composed of many objects that work with each other to accomplish to goals of the system.  We want our systems to be decomposed into cohesive classes that perform a well defined responsibility within the system, rather than monolithic “God” classes that do too much.  A cohesive class will have to be dependent upon other classes to perform services outside of its own tightly defined responsibility.  In IoC speak, we call the collaborating objects dependencies

     

    Dependencies

    For example, in my current system we have a class called AddressEditController that governs the creation and editing of Address entities in our web based UI.  The AddressEditController needs to validate user input and persist or load data.  Those are two distinct responsibilities, so AddressEditController has dependencies on other objects for these services. 

        public class AddressEditController : Controller

        {

            // AddressEditController uses IValidator to validate user input

            // and IRepository to load and save Address information

            private readonly IValidator _validator;

            private IRepository _repository;

     

        }

    So here’s some facts about AddressEditController:

    • AddressEditController depends on IValidator and IRepository 
    • AddressEditController cannot function unless it has both an IValidator and an IRepository
    • From the concepts section above, for best results, the AddressEditController should be loosely coupled to its dependencies by knowing as little about the inner workings of the real IValidator and IRepository
    • The real IRepository is a Gateway into NHibernate. The concrete Repository class cannot be used without its own dependency trail of external configuration, a Singleton to keep track of an expensive resource, and some NHibernate bootstrapping code. 

    Just calling a new() constructor on its dependencies isn’t the best design for our AddressEditController.  Creating a concrete Validator class is very possible, but what if we want to selectively replace the implementation of IValidator later?  That’s only somewhat likely, but the dependency on Repository is a much larger concern.  I might have semantic decoupling between AddressEditController and Repository, but if AddressEditController calls new Repository() itself, AddressEditController will not be able to function without all that NHibernate bootstrapping.  I do not want a piece of my user interface to be tightly coupled to the existence of the persistence layer. 

    In other scenarios, creating the dependencies may involve more than just calling new() on the dependencies (don’t believe me?  Go try to create an HttpContext object).

    AddressEditController is responsible for the workflow around editing Address entities in the UI.  It shouldn’t be concerned with NHibernate configuration and whatnot.  One way to solve this problem is to move the responsibility for building its dependencies to somewhere external to AddressEditController

     

    Inversion of Control and Dependency Injection

    In many cases, I don’t want my classes to have to be aware of how their dependencies are created or located.  I don’t want controller classes to even care that they’re using an object that is created via Microsoft’s Provider infrastructure, or a Singleton, or needs configuration data.  My class should only know the public interfaces of its dependencies.  I can make that true by applying “Inversion of Control.”  Instead of doing:

            public AddressEditController()

            {

                _validator = new Validator();

                _repository = new Repository();

            }

    where AddressEditController calls linearly through to the constructors on Validator and Repository, we can invert the control to make the creator of AddressEditController responsible for building the dependencies and “pushing” them into AddressEditController

        public class AddressEditController : Controller

        {

             private readonly IValidator _validator;

            private IRepository _repository;

     

            public AddressEditController(IValidator validator, IRepository repository)

            {

                _validator = validator;

                _repository = repository;

            }

        }

    The code sample above uses a form of Inversion of Control called Dependency Injection to push in the dependencies via a constructor function.  Of course, at some point, something needs to know how to create the entire chain of dependencies and do all of that Dependency Injection.  StructureMap supports a pattern known as Service Locator:

                // Creates an AddressEditController with all of its dependencies

                AddressEditController controller = ObjectFactory.GetInstance<AddressEditController>();

    ObjectFactory is a StructureMap class that serves as a well known place to go and find any service that you need.  When the AddressEditController is created and returned by ObjectFactory, it should be completely ready to go.  There’s another important concept to understand before you use StructureMap. 

     

    Auto Wiring

    Every "real" IoC container supports the concept of "Auto Wiring."  Auto Wiring simply means that StructureMap can figure out dependency chains for you without a lot of explicit configuration.  When you ask for AddressEditController, there is more going on than just AddressEditController and its two dependencies.  The Repository class itself has its own dependencies.

            [DefaultConstructor]

            public Repository(ISessionSource source) : this(source.CreateSession())

            {

     

            }

    In turn, the concrete version of ISessionSource above has its own dependencies:

            public SessionSource(IDictionary<string, string> properties, PersistenceModel model)

            {

                _configuration = new Configuration();

                _configuration.AddProperties(properties);

     

                model.Configure(_configuration);

     

                _sessionFactory = _configuration.BuildSessionFactory();

            }

    which starts to get interesting because SessionSource needs some information like connection strings that have to come in from Xml configuration: 

    <StructureMap MementoStyle="Attribute">

      <DefaultInstance

        PluginType="ShadeTree.DomainModel.ISessionSource,ShadeTree.DomainModel"

        PluggedType="ShadeTree.DomainModel.SessionSource,ShadeTree.DomainModel">

        <properties>

          <Pair Key="connection.provider" Value="NHibernate.Connection.DriverConnectionProvider" />

          <Pair Key="connection.driver_class" Value="NHibernate.Driver.SqlClientDriver" />

          <Pair Key="dialect" Value="NHibernate.Dialect.MsSql2000Dialect" />

          <Pair Key="hibernate.dialect" Value="NHibernate.Dialect.MsSql2000Dialect" />

          <Pair Key="use_outer_join" Value="true" />

          <Pair Key="connection.connection_string" Value="a connection string that I’m certainly not giving out to you!" />

          <Pair Key="show_sql" Value="true" />

        </properties>

      </DefaultInstance>

    </StructureMap>

    Here’s some of the configuration for the other services that the entire EditAddressController needs:

                ForRequestedType<IValidator>().TheDefaultIsConcreteType<Validator>();

                ForRequestedType<IRepository>().TheDefaultIsConcreteType<Repository>().CacheBy(InstanceScope.Hybrid);

                ForRequestedType<PersistenceModel>().TheDefaultIsConcreteType<DovetailPersistenceModel>();

    At no point did I specify that EditAddressController needs an IRepository that needs an ISessionSource that needs 2-3 other things, but yet when I call:

                // Creates an AddressEditController with all of its dependencies

                AddressEditController controller = ObjectFactory.GetInstance<AddressEditController>();

    StructureMap will construct EditAddressController that had a new instance of Repository that had a new instance of SessionSource that had an IDictionary<string, string> object and a new instance of DovetailPersistenceModel.  I don’t have to explicitly tell StructureMap to do that for me because it uses its “Auto Wiring” feature to examine the dependencies of each concrete class and act accordingly.  StructureMap does need to know what to do with each type of object it encounters.  When it tries to build the Repository class StructureMap sees the constructor argument for ISessionSource on Repository, and knows to build and inject a new SessionSource object (and so on as deep as you need to go).

  • The all positive post

    I'm a month into our new project and working with a lot of new technologies.  When I moved from the desktop back to the web I got some condolences from friends, but it's always fun to do different things and web development with .Net is much different than when I left.  I thought I'd take a timeout from the EF controversy and mention the things that I do like:

    • Doing backend development  with .Net again.  It was interesting(?) to do server side Java last year, but I'm happy to be back.

    • Linq for NHibernate.  We're not pushing it that hard, but it's doing everything I wanted it for.  We're setup to swap out our normal Repository with an InMemoryRepository that relies on Linq to Objects behind the scenes.  I think that's going to end up being huge for testability.  I really like being able to put the query logic directly into business layer code instead of being hidden away deep in the bowels of one off Repositories or services -- without sacrificing testability in the domain and service layers.

    • jQuery is amazing.  The whole "unobtrusive JavaScript" thing is brilliant.  I was a JavaScript whiz in the early days of IE 4 & 5, but the elegance of the jQuery solution for tabs as an example, blows away the drudgery of my old JavaScript TabManager class.

    • We're utilizing some of the new stuff in RhinoMocks 3.5.  I love some of the new features like the Arrance, Act, and Assert style testing.  We've started writing some of our own specific BDD style context superclasses for testing Controllers in the MVC framework, and the new RhinoMocks plays very well into this strategy.

    • BDD.  I resisted it for awhile because, quoting a friend who shall remain nameless, "TDD, but with 'Should' instead of 'Assert.'"  Ok, the shift to "Should" from "Assert" is actually worthy on its own merit, but I think BDD and its concentration on semantics and context is a better way to organize and express tests (specifications).  I even think that BDD does really help in the design process.

    • The ASP.NET MVC framework is okay.  I didn't like the way it did some things, and I think the testability out of the box isn't what it could be.  However, it was an easy matter to write our own infrastructure on top of the MVC that took the testability pain and some repetitive grunt work away.  The fact that it was not only possible, but easy to change its behavior is a major point in the positive column for me on MVC.  I love that you can get the code for it too.  I don't think we could have rapidly done the things we did if all we had was Reflector.  The things in the MVC that I'm still unhappy with I would blame on ASP.NET in general rather than the MVC itself. 

    • QUnit for JavaScript unit testing.  Very cool, and a touch easier to use than jsUnit.  I love the model.

    • WatiN for web testing.  We're gambling a bit that its FireFox support is going to be satisfactory, but otherwise, I think WatiN has been exceptionally smooth to use.  The fact that it's callable from .Net code is letting us do some Lambda-fu to closely hook up our tests to the underlying model of the web pages.

    • C# 3.5.  We're barely using Linq, but all the features they stuck in there to support Linq are making a huge splash in our code.  There are so many times when a judicious extension method eliminates some grunt work or makes code easier to read.  Lambda expressions make a lot of code declarative.  Object initializers tighten up the code and make unit testing more efficient.
  • I'm speaking at Agile Austin on Tuesday

    I'm giving a talk this coming Tueday at Agile Austin on "How does design get done on an Agile Project?" that's free to everyone.  I'll post the slides here afterwards.  See you there.

     

    From the website: 

    Description     
    Agile projects have a reputation in many circles as cowboy coding or purely “code n’fix.”  While there might not be an explicitly defined “Architecture” or “Design” phase or activity, design is still an integral part of any successful Agile project.  This talk will discuss the questions of when, how, and by whom is design accomplished.  Jeremy will present the Agile and Lean design philosophies for simple design, delayed commitment, and enabling change.  Specifically, he will talk about enabling Continuous Design, why evolutionary design adds value over strictly upfront design, and how to get it done without incurring unnecessary code and design thrash in later stages of the project. This talk will be useful to all roles on agile project and product efforts, including project and program managers as well because it touches on flexible and incremental delivery

     

  • Spicing up our NHibernate Fluent Interface with pluggable conventions

    I'm adding pluggable type conventions to our NHibernate mapping Fluent Interface today:

     

        public interface ITypeConvention
    {
    bool CanHandle(Type type);
    void AlterMap(IProperty property);

    }

    public interface IProperty
    {
    void AddAlteration(Action action);
    void UseThisType() where T : IUserType;
    void SetAttributeOnPropertyElement(string name, string key);
    }
     
    Anyway, one of the design ideas we can steal from Ruby on Rails is the convention over configuration philosophy.  Part of the efficiency gain I think we make by moving from hbm.xml configuration to the FI is taking advantage of conventions tied to object types.  We've made the FI smart enough to respond to some class and property types.  The code above is going to make these conventions pluggable.  Today, I'm adding a custom IUserType for our Value Objects.  I'm creating the hook above to plug in a rule that says that any property subclassing type ValueObject will be mapped using this new IUserType.  
     
    Here's some examples of conventions: 
    • You're trying to create a mapping for a class that subclasses DomainEntity?  Why don't I just automatically set up the identifier node for you pointing to the Id property.  I'll add property mappings for all those common audit trail columns too.
    • You got an enumeration type?  I'll just stick in an EntityStringType for you.
     
     
    More results, less code, and fewer lines of XmHell. 

     


  • Does our addiction on visual tooling harm the rate of innovation in the .Net world?

    Here's a peripheral argument to the current EF ruckus:  Is the focus on visual tooling hindering the rate of innovation in the .Net world?  At the ALT.NET event in Seattle, we started with a fishbowl session on polyglot programming (basically, using different languages and even writing little languages for the particular tasks that they're best suited for).  One of the attendees thought polyglot programming was a bad idea because of all the tooling that each new language was going to require.  True, but hopefully false.  High ceremony languages like C# and Java require more tooling like ReSharper and IntelliJ to be efficient than lower ceremony languages or terser languages.  What if the alternative languages were usable for some specialized task without a lot of new tooling?  Think about scripting languages or external DSL's that are tuned for specific purposes and really don't require Intellisense and wizardry to be useful.

    Think about it, visual tools and user interfaces are expensive to build, but yet we automatically assume that a tool is "better" if it comes with Visual Studio integration and other visual goodies.  Part of the cost of anything new Microsoft builds is a wizard tool or a VS plugin.  That cost inevitably detracts from the development of whatever framework or technology that the wizard is meant to help.  It's an idle thought, but what if the Entity Framework team had focused on a textual DSL tool for configuration and modeling that was easy to use instead of relying on the more mechanically expensive designers?  Or made the Xml mapping simple enough that you didn't feel like the designer was necessary?  Is it possible that they would have had more than enough time to make the structural changes in EF to allow for a Persistence Ignorance option in the first rollout?  Instead of the wasteful arguments about the design of EF, I might be a happy, card carrying member of the "Entity Framework Mafia."

    All I'm really trying to say is that I think we could gain some benefits by downgrading our reliance on visual tooling and software factories and Visual Studio plugins in favor of API's that are terser, easier to read, and easier to consume.   My thesis is mostly based on my belief that language oriented programming techniques will often provide a greater return on investment than the comparable effort to develop visual tooling.  Or we could just concentrate on making better API's I suppose.

    As an aside, a couple years ago I spent quite a bit of time trying to write a user interface tool to help users write the StructureMap Xml configuration.  It was a mountain of work, and I gave up after becoming discouraged by the number of edge cases I needed to handle in the UI.  A couple releases later I focused on DRY'ing up the Xml configuration to streamline it, bulked up the diagnostics, and added the Fluent Interface style of configuration.  I'd argue that the Fluent Interface and Xml configuration improvements did enough to make the configuration easier that the UI tool is completely unnecessary.  I certainly haven't felt like I've needed it in my daily work.  Now, I'd really like to get that very nice, early September day I wasted trying to write my StructureMap wizard instead of site seeing on the "Miracle Mile" in Chicago and going to the Field Museum.  Priorities.

    That last paragraph is partially meant as a warning for the Unity team because they've got a visual editor on their CodePlex release plan.  Trust me guys, there's better ways to add value to Unity than spending the necessary resources to write a visual wizard to write configuration.

    A year or so ago (I couldn't find the link), Ayende made the statement that any framework that required a wizard must have a terrible API.  Assuming that he really did say that, and I'm not making that up, ditto from me.  Don't believe me?  Pick any of the bigger 3rd party WinForms control libraries and try to configure their grid control without a designer. 

    One of my beefs about WPF (I do actually like WPF overall) is that the Xaml markup and object structure is clearly optimized for tooling rather than programmatic usage.  It's certainly possible to do dynamic layouts and DSL things with WPF, but it's clearly not the way WPF is meant to be used and it showed.  That's really too bad because the actual technology behind the scenes seemed to be rock solid (once we wrote our Fluent Interface for dynamic forms it worked very well).


    Just think, if we weren't spending so much time as a community trying to build visual tools to make up for bad API design, how much more time we could have for "is the var keyword the work of the devil, or merely an occasional way to make code more readable?"

     

    Now discuss. 

  • StructureMap 2.4.9 Preview Release is available

    A preview release of StructureMap 2.5 is available now at http://sourceforge.net/projects/structuremap.  The code is completely baked (minus some convenience methods I'm going to throw in), but I'm lagging on the documentation (life has been intruding on my side project time lately).  I'll make the full and official release as soon the documentation is done.  This release marks a large scale re-architecture of StructureMap and has taken it very far from its roots as a simple tool to build objects from an Xml representation.  As such, I'm completely rewriting the documentation and website as well.  I'm hoping to include quite a few samples of usage.

    The new functionality in StructureMap 2.5:

    * The ability to use StructureMap with ZERO Xml or attributes by default 

    * The ability to add services at runtime.  You can now programmatically add an entire Assembly at runtime for modular applications that might not want all services to be loaded at startup.

    * An auto mocking container based on Rhino Mocks 3.5.  I was a doubter on the validity of AMC, but I'm sold now that I've used it 

    * More sophisticated auto wiring rules

    * Supporting NameValueCollection and IDictionary<Key, Value> types

    * Far more extensibility

    * Interception and post processing hooks for you AOP enthusiasts.  StructureMap will NOT include its own AOP engine, but will allow you to use the runtime AOP technique of your choice.

    * More configuration options in both Xml and the Fluent Interface.  Usability tweaks for the Fluent Interface.

    * More options for modular configuration (mix and match Xml configuration or Registry's at will) -- which basically had to trigger:

    * Completely revamped diagnostics, including the Environment Testing support

    * Transparent creation of concrete types that are not explicitly registered

    * Create objects with explicit arguments passed to the container

    * Use the underlying Container independently of ObjectFactory

    * Pluggable auto registration

    * StructureMap is now strong named (thanks to Steve Harman)

    * Pull configuration from the App.config (thanks to Josh Flanagan)

    * Generics fixes (thanks to Derrick Rapp) 

     

     

    Anyway, I've got some documentation to go write.... 


  • It's either puke worthy or elegant

    protected static T redirectTo<T, CONTROLLER>(Expression<Func<CONTROLLER, object>> expression) where T : ViewModel, new()
    {
    return new T() {Override = new ControllerRedirectResult<CONTROLLER>(expression)};
    }

    Just a wee bit of code we're using in our MVC Controller base class.  I'm happy with what it *does,* but tell me that isn't butt ugly code.  I think the angle bracket and generic constraint noise tax is like the governor on school buses that keeps them from going over 65 miles an hour.  Anders' way of telling you that you're going too far and time to back off.  Anyway, the usage of the stuff above isn't that bad, and the unit testing is pretty easy.

    Comments are welcome.  This kind of thing bothers me in the sense that later developers are gonna scream WTF! when they find it in the code.
     


     

  • Working faster and fewer mapping errors with NHibernate

    EDIT:  To access the codebase below, the user name is "guest" and the password is blank.  http://codebetter.com/blogs/jeremy.miller/archive/2008/02/01/access-to-the-storyteller-source-code.aspx

     

     

    Yesterday, David Laribee related some problems he experienced with refactorings in his domain model leading to some breaking problems with NHibernate mappings.  Specifically, the issues are:

    1. Changing the property names of a domain model can break the NHibernate mapping
    2. Changing the database fields can break the NHibernate mappings

    David went on to bemoan the absence of a quick way to validate NHibernate mappings.  Ayende popped in with the suggestion that the presence of integrated tests around the NHibernate usage would spot mapping problems.  Other folks mentioned that there's a new ReSharper plugin to validate and refactor NHibernate mappings.  I'll circle back to the refactoring plugin in a while. 

    First I want to talk about quick ways to validate NHibernate mappings.  Ayende is right of course about the integrated tests against the individual queries, but I'm going to suggest that that isn't the most efficient answer to the question of validating the mappings.  The bigger integration tests will tell you that something is wrong, but from experience they'll be harder to diagnose because there is so much more going on than simple property checking, and they provide a slow feedback cycle because of how much stuff is going on.  What would be nice is a way to walk right up to a mapping and specify which properties on a class are supposed to be persisted and how.

    I thought I would come out of my blogging retirement and show an example of the Chad and Jeremy approach to testing NHibernate mappings:

            
    
            [SetUp]
            public void SetUp()
            {
                // Ensure that the StructureMap configuration is bootstrapped
                // In our case, this includes everything we need setup to 
                // execute NHibernate (mappings + ISessionFactory configuration)
                // This will be pretty application specific here
                Bootstrapper.RestartStructureMap();
            }
            
            [Test]
            public void SaveAndLoadCustomerContact()
            {
                new PersistenceSpecification<CustomerContact>()
                    .CheckProperty(x => x.Name, "Frank")
                    .CheckProperty(x => x.Email, "Email")
                    .CheckProperty(x => x.Extension, 123)
                    .CheckProperty(x => x.FaxNumber, "111-111-1111")
                    .CheckProperty(x => x.TelephoneNumber, "222-222-2222")
                    .CheckProperty(x => x.Title, "Mr.")
                    .VerifyTheMappings();
            }
            

    All this test does is ensure that the 6 properties of the CustomerContact class (Name, Email, Extension, FaxNumber, TelephoneNumber, Title) are mapped in NHibernate.  We have some other methods for checking to many and many to one type relationships. 

    Behind the scenes the PersistenceSpecification<T> class:

    1.  Creates a new instance of T
    2. Uses the lambda expressions and suggested values in the calls to CheckProperty to load values into the new instance of T
    3. Grabs our IRepository out of StructureMap (of course), and saves the object
    4. Grabs a second IRepository out of StructureMap
    5. Fetches a second copy of the same T out of the second IRepository
    6. Verifies that all of the specified properties in the specification were saved and loaded.  If any single property does not match between the first T and the second T, the test will fail.

    Here's the implementation of the PersistenceSpecification.VerifyTheMappings() method:

            public void VerifyTheMappings()
            {
                // Create the initial copy
                var first = new T();
    
                // Set the "suggested" properties, including references
                // to other entities and possibly collections
                _allProperties.ForEach(p => p.SetValue(first));
    
                // Save the first copy
                _repository.Save(first);
    
                // Get a completely different IRepository
                var secondRepository = createRepository();
    
                // "Find" the same entity from the second IRepository
                var second = secondRepository.Find<T>(first.Id);
    
                // Validate that each specified property and value
                // made the round trip
                // It's a bit naive right now because it fails on the first failure
                _allProperties.ForEach(p => p.CheckValue(second));
            }
        

    The advantage of this testing is that it gives a (relatively) fast feedback cycle focused specifically on the mappings.  Tools that check the hbm.xml mappings can only verify that what's there is correctly formed.  The mapping tests above will catch missing mappings and desired behavior.  At a bare minimum, you really should have at least one smoke test in your CI build that simply tries to create an NHibernate ISession object from your configuration.  Let that test run and possibly fail the build before wasting any time on integrated tests that can't succeed.

    Now, the ReSharper plugin for NHibernate sounds pretty cool.  I definitely want little or no friction in renaming or adding properties in my Domain Model classes (why I absolutely despise codegen your business object solutions).  We beat the refactoring problem by eliminating HBM.XML.  As part of my New Year's resolution to eliminate my exposure to angle bracket hell, we've created the beginning of a Fluent Interface API to express NHibernate mappings.  Using copious amounts of Generics (I guess .Net code just "wants" to have lots of angle brackets) and lambda expressions, we're able to express NHibernate mappings in a completely compiler-checked, ReSharper-able way.  Since we switched to the FI, we've experienced far less trouble with mapping problems.  Here's a couple of examples:

        // Simple class with properties and a single "to-many" relationship
        public class CustomerContactMap : ClassMap<CustomerContact>
        {
            public CustomerContactMap()
            {
                Map(x => x.Name);
                Map(x => x.Email);
                Map(x => x.Extension);
                Map(x => x.FaxNumber);
                Map(x => x.TelephoneNumber);
                Map(x => x.Title);
                References(x => x.Customer);
            }
        }
        
        // Class with a "Component"
        public class CustomerDeliveryAddressMap : ClassMap<CustomerDeliveryAddress>
        {
            public CustomerDeliveryAddressMap()
            {
                Map(x => x.Name);
                References(x => x.Customer);
                Component<Address>(x => x.Address, m =>
                   {
                       m.Map(x => x.AddressLine1);
                       m.Map(x => x.AddressLine2);
                       m.Map(x => x.AddressLine3);
                       m.Map(x => x.CityName);
                       m.Map(x => x.CountryName);
                       m.References(x => x.State);
                       m.References(x => x.PostalCode);
                   });
            }
        }
        
        // Class with some "has many" relationships
        public class CustomerMap : ClassMap<Customer>
        {
            public CustomerMap()
            {
                HasMany<CustomerContact>(x => x.Contacts).CascadeAll();
                HasMany<CustomerJob>(x => x.Jobs).CascadeAll();
                HasMany<CustomerDeliveryAddress>(x => x.DeliveryAddresses).CascadeAll();
    
                Map(x => x.Name);
                Map(x => x.LookupName);
                Map(x => x.IsGeneric);
                Map(x => x.RequiresPurchaseOrder);
                Map(x => x.Retired);
            }
        }
        
        
            

    With this approach, and backed up with the little PersistenceSpecification tests, we can happily change class names and property names with relative confidence.  Besides, the simple usage of Intellisense plus compiler safe code cuts down on the number of mapping errors.  We're more or less greenfield at the moment, so we can get away with generating the database from our NHibernate mappings on demand, but you can specify specific table and column names in the language above for brownfield scenarios.  I'd very confidently say that we're faster with this approach than we would be with HBM.XML.

    If you're interested, the complete code for everything I talked about is in the ShadeTree.DomainModel project in the StoryTeller codebase (and effectively released under the Apache 2.0 license). The code is at http://storyteller.tigris.org/svn/storyteller/trunk/. Use the src\ShadeTree.sln for this stuff. I don't know that we'll ever get around to a fully supported release of this stuff, but I wanted to throw out the idea anyway. At this point I'm only extending this code when we need something new for our current project.  A lot of the advantages of this approach are tied to application specific conventions and also by tieing the forward generation of the database structure to validation rules.

     

    As for IoC container testing...

    I'll overlook the fact that my friend David also implicitly implied that an IoC container not named StructureMap was the de facto standard. Bil Simser posted a little snippet of code to smoke test the configuration of one of those other IoC containers.  StructureMap has had quite a bit of diagnostic support since version 0.85 (StructureMapDoctor.exe), but StructureMap 2.5 will add the ability to do this:

            [SetUp]
            public void SmokeTestStructureMapConfiguration()
            {
                ObjectFactory.AssertConfigurationIsValid();
            }
            

    This will attempt to build every possible configured instance in StructureMap, perform any designated environment tests (like trying to connect to a database), and generate a complete report of all errors encountered by StructureMap.  If you're aggressive about managing all external services and configuration into your IoC container, this diagnostic test can go a long way towards detecting environmental and configuration errors of a code installation.

  • A bad argument

    I browsed blogs for the first time in a couple weeks the other day.  Somewhere in a static typed vs dynamic typed languages argument post some clown said (paraphrasing), "we don't need no stinkin' Ruby because we can do metaprogramming in C# with IL generation."  Yeah you can, and I have as a matter of fact, but it's painful and not even remotely time effective for anything but highly reusable, simple code.  I started to say in a conversation today that the author of that statement should be beaten with a stick for that comment, but seeing as the author was obviously a masochist, that seemed like sending the wrong type of signal.

     


  • StructureMap 2.5 will be released on June 23rd

    Several people have asked, and I'm getting anxious to get it out.  I've got just a couple little coding tasks to do, then about a week of writing docs, examples, and tutorial thingies.  I originally planned to make this release in .Net 2.0, but I gave in and switched the code over to .Net 3.5. 

  • I'm maturing as a developer

    Yesterday I sat down in the morning to spike something with the new ASP.NET MVC thingie.  I was going to adapt a Javascript grid I wrote a couple years ago with Prototype and repurpose that code for the new requirements.  After 5 minutes of googling, I ditched my code and went with some off the shelf jQuery plugins, and promptly found some other plugins that will serve just fine.  Jeremy of 5 years ago would have rolled his own.

    p.s. yeah, jQuery rocks and all, but the jQuery *community* and *project* is what's totally awesome to me.
     


     

  • The Open/Closed Principle on MSDN

    My latest article entitled The Open Closed Principle is available in the June 2008 edition of MSDN Magazine.  I tried to present both the motivation for following the OCP and some design strategies (besides the obvious Plugin example) and related principles to bring your design closer to being "Open for Extension, but Closed for Modification." 

    If you've never heard of the Open/Closed Principle, think of doing an addition to an existing house.  What sounds easier, laying all new bricks for an all new room, or changing the layout of existing rooms with a reciprocating saw?  An Open/Closed design allows us to extend the system with new code instead of having to potentially screw up existing code that works today. 

    Lastly, if you've read about the OCP before and think the OCP == "Plugin Pattern," go give the article a read, because that's not the entire story.

    This is the first in a bi-monthly series of articles called Patterns in Practice on software design fundamentals.  The next article (Object Role Stereotypes/Responsibility Driven Design) is already completed, but I'd be perfectly happy to take requests.  I think the next two leading candidates are "design vectors" (i.e. better designed code by moving in the direction of this, that, or the other) and treating Inversion of Control as a design pattern independently of IoC tools.

    Related Posts to the Article:

     

  • We're talking past each other on the Entity Framework

    Yeah, I know everyone is tired of the Entity Framework argument, but maybe we can start a real discussion.  I've seen two very different conversations about the Entity Framework from the data centric folks (pro) and the DDD/TDD/OOP folks (con).  It's not even a real argument, because we're concerned about very different things that aren't even in real opposition.  I'm completely agnostic about the Entity Data Model and the farther reaching, universal data access goals of the EF.  I'm strictly concerned with the EF's poor applicability for evolutionary design, Domain Driven Design, testability, and separation of concerns.  The EF seems to have all the major bases all covered in terms of functionality, it's just the *way* that it implements this behavior that concerns me.

    The problem with the blogging from last week is that it's two different conversations!  The "pro-EF" folks seem to be giddy about the functionality and features of the EF.  I'm steamed about what I feel to be the poor usability of the EF.  I do fully understand that the EF is about so much more than O/R mapping, I just don't think that their vision for data access adds more value than the harm that EF will do to my architecture by being intrusive.  The cool thing is that the EF team *can* actually make both camps happy.  There is absolutely no technical reason that the EF cannot deliver all of this utopian EDM goodness AND make the necessary structural changes to allow for real Persistence Ignorance to address my concerns about its usability. 

    The only real argument is their priority queue.  I obviously think the EF team needs to get a full Persistence Ignorant story in place before adding any other new functionality.

    For the record, I'm somewhat dubious about the actual usefulness of the Entity Data Model, but I will very seriously consider using the Entity Framework the minute that the EF team ships a real Persistence Ignorant option (which HAS to include transparent lazy loading) and a streamlined mapping configuration story (i.e. I want the conceptual model completely hidden away).  Until then, all that impressive sounding EDM stuff does not justify what I feel are severe compromises in my application architecture that do not occur with other persistence solutions. 


  • What Dan Simmons forgot to tell you about the Entity Framework

    Dan Simmons from the Entity Framework team at Microsoft made a nice post comparing the Entity Framework to other existing tools.  I wanted to pick a little bone with his comparison to NHibernate.  I don't think he said anything inaccurate, and he was very fair minded, but he left out the crucial fact in any consideration of using NHibernate versus the Entity Framework.  The Entity Framework is very intrusive into your application, but NHibernate is not.  NHibernate lets me use POCO's to model the business process in a database agnostic way.  The Entity Framework wants me to bake EF infrastructure directly into my business objects.

    The major problem I have with the Entity Framework is very apparent in Dan Simmon's post.  The EF team, and its advocates in the blogosphere, are strictly focused on data.  The last I checked, an application, system, or service usually consists of more than just getting data in and out of a database.  Some of that other stuff is quite challenging as well.  I'd prefer to be able to make that other stuff work in peace without data access infrastructure concerns bleeding into my business classes. 

    I would really like to challenge the EF team and the EF cheerleaders to be more cognizant of the entire application architecture instead of focusing strictly on the grubby details of data access. 

More Posts Next page »

This Blog

Syndication

News

All opinions expressed here constitute my (Jeremy D. Miller's) personal opinion, and do not necessarily represent the opinion of any other organization or person, including (but not limited to) my fellow employees, my employer, its clients or their agents.

About Me

"Best Of" Compendium

StructureMap (Dependency Injection for .Net)

StoryTeller (Supercharged Fit)

Build your own Cab

TestDriven

MVP