Skip to content

Jimmy Bogard
Syndicate content
Professional driver on closed road. Do not attempt.
Updated: 41 min 5 sec ago

Strengthening your domain: Encapsulated collections

3 hours 7 min ago

Previous posts in this series:

One of the common themes throughout the DDD book is that much of the nuts and bolts of structural domain-driven design is just plain good use of object-oriented programming.  This is certainly true, but DDD adds some direction to OOP, along with roles, stereotypes and patterns.  Much of the direction for building entities at the class level can, and should, come from test-driven development.  TDD is a great tool for building OO systems, as we incrementally build our design with only the behavior that is needed to pass the test.  Our big challenge then is to write good tests.

To fully harness TDD, we need to be highly attuned to the design that comes out of our tests.  For example, suppose we have our traditional Customer and Order objects.  In our world, an Order has a Customer, and a Customer can have many Orders.  We have this directionality because we can navigate this relationship from both directions in our application.  In the last post, we worked to satisfy invariants to prevent an unsupported and nonsensical state for our objects.

We can start with a fairly simple test:

[Test]
public void Should_add_the_order_to_the_customers_order_lists_when_an_order_is_created()
{
    var customer = new Customer();
    var order = new Order(customer);

    customer.Orders.ShouldContain(order);
}

At first, this test does not compile, as Customer does not yet contain an Orders member.  To make this test compile (and subsequently fail), we add an Orders list to Customer:

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public List<Order> Orders { get; set; }

    public string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}

With the Orders now exposed on Customer, we can make our test pass from the Order constructor:

public class Order
{
    public Order(Customer customer)
    {
        Customer = customer;
        customer.Orders.Add(this);
    }

And all is well in our development world, right?  Not quite.  This design exposes quite a bit of functionality that I don’t think our domain experts need, or want.  The design above allows some very interesting and very wrong scenarios:

[Test]
public void Not_supported_situations()
{
    // Removing orders?
    var customer1 = new Customer();
    var order1 = new Order(customer1);

    customer1.Orders.Remove(order1);

    // Clearing orders?
    var customer2 = new Customer();
    var order2 = new Order(customer1);

    customer2.Orders.Clear();

    // Duplicate orders?
    var customer3 = new Customer();
    var customer4 = new Customer();
    var order3 = new Order(customer3);

    customer4.Orders.Add(order3);
}

With the API I just created, I allow a number of rather bizarre scenarios, most of which make absolutely no sense to the domain experts:

  • Clearing orders
  • Removing orders
  • Adding an order from one customer to another
  • Inserting orders
  • Re-arranging orders
  • Adding an order without the Order’s Customer property being correct

This is where we have to be a little more judicious in the API we expose for our system.  All of these scenarios are possible in the API we created, but now we have some confusion on whether we should support these scenarios or not.  If I’m working in a similar area of the system, and I see that I can do a Customer.Orders.Remove operation, it’s not immediately clear that this is a scenario not actually coded for.  Worse, I don’t have the ability to correctly handle these situations if the collection is exposed directly.

Suppose I want to clear a Customer’s Orders.  It logically follows that each Order’s Customer property would be null at that point.  But I can’t hook in easily to the List<T> methods to handle these operations.  Instead of exposing the collection directly, I will expose only those operations which I support through my domain.

Moving towards intention-revealing interfaces

Let’s fix the Customer object first.  It exposes a List<T> directly, and allows wholesale replacement of that collection.  This is the complete antithesis of intention-revealing interfaces.  I will now only expose the sequence of Orders on Customer:

public class Customer
{
    private readonly IList<Order> _orders = new List<Order>();

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public IEnumerable<Order> Orders { get { return _orders; } }

    public string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}

This interface explicitly tells users of Customer two things:

  • Orders are readonly, and cannot be modified through this aggregate
  • Adding orders are done somewhere else

I now have the issue of the Order constructor needing to add itself to the Customer’s Order collection.  I want to do this:

public class Order
{
    public Order(Customer customer)
    {
        Customer = customer;
        customer.AddOrder(this);
    }

Instead of exposing the Orders collection directly, I work through a specific method to add an order.  But, I don’t want that AddOrder available everywhere, I want to only support the enforcement of the Order-Customer relationship through this explicitly defined interface.  I’ll do this by exposing an AddOrder method, but exposing it as internal:

public class Customer
{
    private readonly IList<Order> _orders = new List<Order>();

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public IEnumerable<Order> Orders { get { return _orders; } }

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }

There are many different ways I could enforce this relationship, from exposing an AddOrder method publicly on Customer or through the approach above.  But either way, I’m moving towards an intention-revealing interface, and only exposing the operations I intend to support through my application.  Additionally, I’m ensuring that all invariants of my aggregates are satisfied at the completion of the Create Order operation.  When I create an Order, the domain model takes care of the relationship between Customer and Order without any additional manipulation.

If I publicly expose a collection class, I’m opening the doors for confusion and future bugs as I’ve now allowed my system to tinker with the implementation details of the relationship.  It’s my belief that the API of my domain model should explicitly support the operations needed to fulfill the needs of the application and interaction of the UI, but nothing more.

Kick It on DotNetKicks.com
Categories: Blogs

Strengthening your domain: Aggregate Construction

Wed, 02/24/2010 - 06:12

Our application complexity has hit its tipping point, and we decide to move past anemic domain models to rich, behavioral models.  But what is this anemic domain model?  Let’s look at Fowler’s definition, now over 6 years old:

The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.

For CRUD applications, these “domain services” should number very few.  But as the number of domain services begins to grow, it should be a signal to us that we need richer behavior, in the form of Domain-Driven Design.  Building an application with DDD in mind is quite different than Model-Driven Architecture.  In MDA, we start with database table diagrams or ERDs, and build objects to match.  In DDD, we start with interactions and behaviors, and build models to match.  But one of the first issues we run into is, how do we create entities in the first place?  Our first unit test needs to create an entity, so where should it come from?

Creating Valid Aggregates

Validation can be a tricky beast in applications, as we often see validation has less to do with data than it does with commands.  For example, a Person might have a required “BirthDate” field on a screen.  But we then have the requirement that legacy, imported Persons might not have a BirthDate.  So it then becomes clear that the requirement of a BirthDate depends on who is doing the creation.

But beyond validation are the invariants of an entity.  Invariants are the essence of what it means for an entity to be an entity.  We may ask our customers, can a Person be a Person (in our system) without a BirthDate?  Yes, sometimes.  How about without a Name?  No, a Person in our system must have some identifying features, that together define this “Person”.  An Order needs an OrderNumber and a Customer.  If the business got a paper order form without customer information, they’d throw it out!  Notice this is not validation, but something else entirely.  We’re asking now, what does it mean for an Order to be an Order?  Those are its invariants.

Suppose then we have a rather simple set of logic.  We indicate our Orders as “local” if the billing province is equal to the customer’s province.  Rather easy method:

public class Order
{
    public bool IsLocal()
    {
        return Customer.Province == BillingProvince;
    }

I simply interrogate the Customer’s province against the Order’s BillingProvince.  But now I can get myself into rather odd situations:

[Test]
public void Should_be_a_local_customer_when_provinces_are_equal()
{
    var order = new Order
    {
       BillingProvince = "Ontario"
    };
    var customer = new Customer
    {
        Province = "Ontario"
    };

    var isLocal = order.IsLocal();

    isLocal.ShouldBeTrue();
}

Instead of a normal assertion pass/fail, I get a NullReferenceException!  I forgot to set the Customer on the Order object.

But wait – how was I able to create an Order without a Customer?  An Order isn’t an Order without a Customer, as our domain experts explained to us.  We could go the slightly ridiculous route, and put in null checks.

But wait – this will never happen in production.  We should just fix our test code and move on, right?  Yes, I’d agree if you were building a transaction-script based CRUD system (the 90% case).  However, if we’re doing DDD, we want to satisfy that requirement about aggregate roots, that its invariants must be satisfied with all operation.  Creating an aggregate root is an operation, and therefore in our code “new” is an operation.  Right now, invariants are decidedly not satisfied.

Let’s modify our Order class slightly:

public class Order
{
    public Order(Customer customer)
    {
        Customer = customer;
    }

We added a constructor to our Order class, so that when an Order is created, all invariants are satisfied.  Our test now needs to be modified with our new invariant in place:

[TestFixture]
public class Invariants
{
    [Test]
    public void Should_be_a_local_customer_when_provinces_are_equal()
    {
        var customer = new Customer
        {
            Province = "Ontario"
        };
        var order = new Order(customer)
        {
            BillingProvince = "Ontario"
        };

        var isLocal = order.IsLocal();

        isLocal.ShouldBeTrue();
    }
}

And now our test passes!

Summary and alternatives

Going from a data-driven approach, this will cause pain.  If we write our persistence tests first, we run into “why do I need a Customer just to test Order persistence?”  Or, why do we need a Customer to test order totalling logic?  The problem occurs further down the line when you start writing code against a domain model that doesn’t enforce its own invariants.  If invariants are only satisfied through domain services, it becomes quite tricky to understand what a true “Order” is at any time.  Should we always code assuming the Customer is there?  Should we code it only when we “need” it?

If our entity always satisfies its invariants because its design doesn’t allow invariants to be violated, the violated invariants can never occur.  We no longer need to even think about the possibility of a missing Customer, and can build our software under that enforced rule going forward.  In practice, I’ve found this approach actually requires less code, as we don’t allow ourselves to get into ridiculous scenarios that we now have to think about going forward.

But building entities through a constructor isn’t the only way to go.  We also have:

The bottom line is – if our entity needs certain information for it to be considered an entity in its essence, then don’t let it be created without its invariants satisfied!

Kick It on DotNetKicks.com
Categories: Blogs

AutoMapper for Silverlight 3.0 Alpha

Fri, 02/19/2010 - 04:31

In between workshops here at the MVP Summit, I’ve been working on pushing out an early Alpha for an AutoMapper version built against Silverlight 3.0.  Thanks to some existing patches from the community, it was pretty straightforward to get things going.  I’ve also started working against an AutoMapper github repository, which also made some other things much, much easier (which I’ll touch on soon).  To get the alpha, grab the binaries from the CodePlex site:

AutoMapper for Silverlight 3.0 Alpha

All existing features of AutoMapper 1.0 are supported, except for:

  • IDataReader
  • IListSource

Neither of which even exist in Silverlight 3.0.  Since I don’t do any Silverlight development, I labeled this one as “Alpha” as I’ll need to rely on folks in the wild to let me know if it actually works or not.

Supporting two runtimes

Before this whole conversion process, I had almost zero experience with Silverlight 3.0.  I vaguely remembered that there was a separate runtime, but it’s really interesting how it all works out.  To get AutoMapper working with Silverlight, I had several big obstacles:

  • Some assemblies don’t exist in Silverlight
  • Some types don’t exist in Silverlight
  • Some types have only partial members defined
  • Some types only have some method overloads defined

Some goals I have is that going foward:

  • Any feature added to AutoMapper will also get added to the Silverlight version
  • Unit tests are executed against the Silverlight version
  • Any test added to AutoMapper will also get added to the Silverlight version
Project setup

To support two runtimes against basically one codebase, I opted for a model where I create Silverlight class libraries, then use linked files to keep the source the same.  Linked files allow me to keep only one source code file on disk (and in source control), but reference the same file from two projects.  I created a new project, AutoMapper.Silverlight, and a new unit tests project as well.  Some files weren’t needed as the feature wouldn’t be supported (such as IDataReader), so I just didn’t link that file in.

When things don’t line up

If a whole file isn’t supported, that’s fine, I just don’t add it.  But what if the API is different?  For example, Silverlight has no TypeDescriptor class.  In those cases, I relied on conditional compilation to provide two implementations in one file:

        private static TypeConverter GetTypeConverter(ResolutionContext context)
        {
#if !SILVERLIGHT
            return TypeDescriptor.GetConverter(context.SourceType);
#else
            var attributes = context.SourceType.GetCustomAttributes(typeof(TypeConverterAttribute), false);

            if (attributes.Length != 1)
                return new TypeConverter();

            var converterAttribute = (TypeConverterAttribute)attributes[0];
            var converterType = Type.GetType(converterAttribute.ConverterTypeName);

            if (converterType == null)
                return new TypeConverter();

            return Activator.CreateInstance(converterType) as TypeConverter;
#endif
        }

Because I opened this file from the regular project, the Silverlight code is grayed out.  Opening the file from the Silverlight project makes all that extra code available, while the top part is commented out.  For places where I just couldn’t support features, I’d just leave them out:

        public static Func<IEnumerable<IObjectMapper>> AllMappers = () => new IObjectMapper[]
        {
#if !SILVERLIGHT
            new DataReaderMapper(),
#endif
            new TypeMapMapper(TypeMapObjectMapperRegistry.AllMappers()),
            new StringMapper(),
            new FlagsEnumMapper(),
            new EnumMapper(),
            new ArrayMapper(),
            new EnumerableToDictionaryMapper(),
            new DictionaryMapper(),
#if !SILVERLIGHT
            new ListSourceMapper(),
#endif
            new EnumerableMapper(),
            new AssignableMapper(),
            new TypeConverterMapper(),
            new NullableMapper()
        };
    }

It’s slightly ugly, but the places where I have to do this are very small.  Luckily, things are reasonably factored out that individual features are usually individual classes.

Third-party libraries

AutoMapper uses proxy classes to support mapping to interfaces.  Originally, I went with LinFu to do this dynamic proxy stuff because it was small, targeted and focused on what I needed to do.  Unfortunately, there is not a Silverlight version, so I switched to Castle Dynamic Proxy to get things going.

It was a very straightforward switch, as the APIs are quite similar.  The only big fix I had to do was update the IL Merge business, and make sure that I excluded the right types so that interface mapping worked when everything was merged up.

Testing

Silverlight unit testing is…weird.  A lot of the documentation out there talks about executing unit tests in a Silverlight application, which is not what I’m interested in.  For NUnit, I merely create a regular class library, and test runners run the test in whatever environment they want.  I needed to find an NUnit version supported for Silverlight, and that was not easy to find.  I went through around three or four different builds out there before I found one I liked:

http://wesmcclure.tumblr.com/post/152727000

I also use NBehave, but I didn’t really feel like porting NBehave over as well, so I just grabbed the source files I needed and included them directly in my testing project.

Executing the tests from NAnt was also completely straightforward, and worked as soon as my TestDriven.NET worked.

Packaging

Based on community feedback, I built the Silverlight-based AutoMapper assembly as a new assembly name, “AutoMapper.Silverlight.dll”.  The only other work I needed to do was duplicate the packaging NAnt tasks, and make sure I included the relevant Silverlight assemblies into my source repository so that the automated build would work.  Installing Silverlight on a build machine is just a bad idea.

Final thoughts

The conversion was smoother than I thought it would be.  The biggest hurdles I had were just getting the unit tests running.  The unit testing framework I use doesn’t have a supported Silverlight build, so I had to do quite a bit of hunting to find one that works.  But other than that, linked files and conditional compilation made things quite easy to do.  Also, playing around on github with easy branching and merging made adding intermittent patches to master very easy to do.  In fact, I was even able to cherry pick a single commit to push back to master from a Silverlight branch…but my git experience should wait for another post.

Thanks again to everyone that sent me patches to get Silverlight working with AutoMapper.

Kick It on DotNetKicks.com
Categories: Blogs

Strengthening your domain: a primer

Thu, 02/04/2010 - 04:41

Recently, I talked some about the idea of an intentionally anemic domain model, under the name of “Persistence Model”.  While a Persistence Model is great for a large percentage of projects, you may eventually want to move more behavior into the domain.  That doesn’t mean a bevy of domain services doing the actual work, however.  A strong domain means that our objects become more behavioral, and less as solely data-holders.

But before we get into some of the patterns, what are some of the goals we want to achieve with a stronger domain?  And how do we get there, what should we be looking for?

Code smells

A lot of DDD is just plain good OO programming.  Unit tests and code smells are the best indication that our domain is wrong, along with conversations with our domain experts.  In systems that start to move beyond merely CRUD, specific code smells start to surface that should indicate that our system is starting to accumulate behavior, but it just might not be in the right place.  In a behavior-rich, but anemic domain, the domain is surrounded by a multitude of services that do the actual work, and fiddle with state on our domain objects.  The domain objects contain state to be persisted, but it’s not the domain objects themselves exposing any operations.

But this is just code smell!  Lots of code smells indicate that our domain is not as rich as at could be.  The behavior is out there, but just needs to be moved around.  Some smells I look for include:

  • Primitive Obsession
  • Data Class
  • Inappropriate Intimacy
  • Lazy Class
  • Feature Envy
  • Middle Man

All these are smells between classes, where usually a domain service is waaaay to concerned with a set of entities, when behavior could just be moved down into those entities

Aggregate Roots

One of the most quoted, but most misunderstood ideas in DDD is the concept of aggregate roots.  But what is this aggregate root?  Is it just an entity with a screen in front of it?  A row in a database?  Evans defined a set of rules for Aggregates:

  • The root Entity has global identity and is ultimately responsible for checking invariants
  • Root Entities have global identity.  Entities inside the boundary have local identity, unique only within the Aggregate.
  • Nothing outside the Aggregate boundary can hold a reference to anything inside, except to the root Entity.  The root Entity can hand references to the internal Entities to other objects, but they can only use them transiently (within a single method or block).
  • Only Aggregate Roots can be obtained directly with database queries.  Everything else must be done through traversal.
  • Objects within the Aggregate can hold references to other Aggregate roots.
  • A delete operation must remove everything within the Aggregate boundary all at once
  • When a change to any object within the Aggregate boundary is committed, all invariants of the whole Aggregate must be satisfied.

It’s a lot, but I generally think of Aggregate roots as consistency boundaries.  When I interact with an Aggregate, its invariants must always be satisfied.  Keeping invariants satisfied strengthens the design and responsibility of the objects, as the logic that defines the Aggregate is then self-contained.

Strategic Design

We may not like it, but not all of our system’s model will ever reach our vision of perfection.  Which is fine, as a perfect model across our entire system would be prohibitively expensive, with little ROI on all that work.  Instead, we have to focus on specific areas of the core domain that provide the most value to the customer.  The better our core domain model, the better our system represents the conceptual model we’ve defined with our customers, and the better we will be able to serve their needs.

Unfortunately, all the interesting Strategic Design chapters are after the basic DDD patterns in the book, so that many folks get lost discussing repositories, entities, aggregates and so on.  But in recent interviews, Evans mentions that these later discussions are more important than the earlier ones.  The bottom line is that we have to choose carefully where we spend our time refining our domain model.  Some areas will not be as refined as others, but that’s perfectly acceptable.  The trick is to find which areas will give us the most value for our time spent in refactoring, refinement and modeling.

Finally, it’s worth noting that there is no “best” design.  There is only the “best design given our current understanding”.  Software development is a process of discovery, where concepts that seemed unimportant or hidden may suddenly become obvious and critical later.  That’s still normal, and not a negative thing.  Lots of concepts around an idea will be thrown around, but only the most important ones will rise to the top, and sometimes that just takes time.

Looking ahead

So you’ve decided to do DDD, but all you’ve done is establish good names for objects that sit on top of database tables.  Not really an improvement, and probably a lot of work.  You look at some DDD sample applications, but they all seem overly complex for what seems like over-engineered CRUD applications.  The last true DDD system I handed off to another team, they would have been at a loss if I just gave them software to look at.  Instead, software diagrams, code, whiteboarding, and a lot of conversation about the core domain were what allowed us to have a successful handoff.  With sample applications built on things like the Northwind or AdventureWorks database, you won’t see that critical tipping point of domain complexity that makes DDD required for long-term success.

In the next few posts, I’ll highlight some common DDD patterns that can help move your core domain model from one of data-driven, anemic models, to rich, behavioral models.

Kick It on DotNetKicks.com
Categories: Blogs

AutoMapper 1.0 RTW

Tue, 02/02/2010 - 00:44

AutoMapper is now officially 1.0.  You can go grab the latest binaries here:

AutoMapper 1.0 RTW

Here are the release notes:

New Features
  • Changing the null substitute method name and allow any type of null substitute
  • Consolidating custom constructor configuration to just one
  • Adding UseValue option for member mappings when you want to just map from a single custom value
  • Added ValueFormatter<T>
Enhancements
  • Adding custom mapping action objects (in addition to just functions)
  • Removing configuration validation from dynamic mapping
  • Adding overloads for mapping to existing objects for dynamic mapping
  • Modified ITypeConverter to only use ResolutionContext as the input
  • Added TypeConverter to ease generic scenarios
  • Custom value resolvers now have access to the current resolution context
  • Switching the MapFrom from using Expression to just Func, but with the return type retained
  • Some performance improvements around caching and sealing (only for Initialize scenarios)
  • Fixed profiles so you don't have to provide a name (defaults to type name)
Bugs Fixed
  • Fixed bug where a zero-length sequence would throw an exception
  • Applying patch to fix duplicate CreateMap call issue
  • Fixing bug where type map resolution did not attempt to find a map for the underlying member type
  • Fixed bug where destination collections were not cleared before mapping
  • Integrating patch to fix ambiguous match exceptions on multiple IEnumerable implementors
  • Fixed bug where read-only string destination properties had to be marked as ignored
  • Applied patch to fix issue where the DataReader mapper blew up on nullable fields
  • Fixing bug where a bi-directional relationship with an array was messing up
  • Fixed bug where type-specific formatters were not found correctly at the global level

I tried to get all the documentation done…and failed.  Instead, I’m building up a comprehensive set of examples first.  So what’s up for the next release?  Here’s my current plan of action:

  1. Move source to github – DVCS better suited for OSS anyway
  2. Get build/deployment/TeamCity.CodeBetter migrated to github
  3. Add in patches for SL 3.0, CF and Mono (and integrate into the build)
  4. Look at v.next

And as always, if you have any questions, feel free to post them up on StackOverflow or put them on the mailing list.  The mailing list shows up in my inbox, while the SO posts show up in my feed reader, so I may not personally answer SO posts right away (but others tend to first).  Enjoy!

Kick It on DotNetKicks.com
Categories: Blogs

Evolutionary Architecture

Fri, 01/29/2010 - 05:47

A popular cause the Agile folks like to rally against is the idea of a Big Design Up Front (BDUF).  But much like Waterfall, the people doing BDUF will hardly admit that it’s BDUF that they’re doing.  Instead, you’re much more likely to get a bevy of really convincing cautionary tales of what might happen if you don’t do a certain design.  With enough experience under their belt, the architect slips into a “Just-In-Case” design mode, where the myriad of pain points encountered in the past leave a design that’s hardened against every possible difficulty that might come up.

Instead of a well architected design, you’ll have one that’s over-abstracted, over-engineered, over-complicated and very difficult for the next developer to come on board and understand.  But there’s an alternative approach.  The better choice instead of BDUF is a collection of design and architecture techniques that both delay decisions until they’re absolutely necessary, and refactoring practices to evolve our design when assumptions are proved incorrect.

Technique #1: YAGNI

YAGNI stands for “You Aren’t Gonna Need It”.  It’s a generally philosophy of waiting until code actually needs to be written before writing it.  Instead of guessing or projecting on future needs, abstractions or features, the need must present itself in a concrete manner.  This idea can be abused as a way of dismissing true needs for abstractions, so it can take some trust and negotiation in a team when disagreements arise on whether a need has arisen.

The benefit of YAGNI is that you don’t develop features that you might not need.  If you only design based on needs currently evident in the codebase, you’ll never fall into the trap of over-design.  After a design has changed passed the YAGNI tipping point, it can be tempting to castigate yourself, asking “why didn’t we do that sooner”?  Because you didn’t need it sooner.  The trick is to find the right tipping point to guide the next step in design.

Technique #2: Pain-Driven Development

Another common over-engineering technique is refactoring areas that may be ugly, but don’t actually present any problems.  The antidote for refactorbation and speculative design is pain-driven development.  The concept is simple: if it doesn’t hurt, it doesn’t need fixing.  If it hurts, fix it!  The bottom line is that not all areas of your application will have the same sophistication and attention to detail in its design.  But that’s normal, every project works under constraints and you have to focus your time on the most critical areas.

The most critical areas tend to be the ones that change the most.  In Feathers’ Legacy Code book, he recommends refactoring code only when it requires change.  If we only refactor when code needs to change, it naturally leads to the most-changed areas having the best design.  If the most-changed areas are where the most features are added, it tends to follow that the design needs to be more robust in those areas.  By paying attention to pain, we can gauge how much time and effort we need to address in changing a design.  A design may not be ideal, but if it’s not causing much pain, there’s not much ROI on “fixing” the problem.

If you view pain as a cost or a debt, then a design improvement must be measured on how much pain the fix solves, rather than how much better it makes us feel or lets us flex our intellectual muscles.  For long-lasting success, it’s important that we spend our time improving areas that will have the most long-term impact.  Paying attention to pain is a great technique for doing so.

Corollary to Pain-Driven Development

Sometimes a pain can be so slight, but so endemic, that you become numb to pain.  An alternative solution doesn’t seem like it will be that much better, since you’ve become adjusted to the more difficult design or tool.  This tends to close your mind to opportunities that the new design or tool provides.  For example, we used the HBM NHibernate mapping files for a long time because we were all quite familiar with using them, and didn’t cause that much pain.  However, Fluent NHibernate opened new doors that our numbness to the HBM pain was actually an opportunity cost because we couldn’t take advantage of things like conventions to drastically reduce the amount of manual mapping code we needed.

So while the current design may not incur too much pain, we still have to be aware of the opportunities alternative designs might afford us.

Technique #3: Iterative Design

Another big issue I’ve seen with long-lived codebases is that although good design concepts are introduced, they are sparsely, almost randomly applied to the outside observer.  Improving the architecture of a system is good, but leaving a trail of decaying, older designs still in the codebase can cripple further innovation.  When we encounter a system-wide pain, we don’t just fix it in one or two spots.  Instead, we estimate the cost to apply the fix system-wide.  Only once we’ve applied the design system-wide will we try to apply the next iteration in our design.

The benefits to this approach are several.  With several older designs in our system in varying degrees in the evolution of our system, it becomes harder and harder to determine what the “right” design is.  If we have a system-wide concept that we only improve one spot at a time, we wind up with a looooong trail of various designs, and it becomes that much harder to find what the next step is.  When it comes to system-wide architecture and design, the more examples we have of the current design, the better our next choice will be.

Other Techniques

I could go on forever on other techniques, such as DRY, Responsibility-Driven Design, Convention over Configuration, Last Responsible Moment, Simplest Thing that Could Possibly Work and more.  Since some decisions are not easily reversible, we would like to wait until we have as much information as possible before making a long-lasting, costly to reverse decision.  When it comes to choosing between something like Rails or ASP.NET MVC, it would be only responsible to ask as many questions as possible before we make our final decision.  Or choosing between Active Record or the Domain Model pattern.  Are we in that 5% slice that actually needs DDD?  Or is it just 5% of our current application that might require DDD?  These are tough questions to answer, and there’s not always all the information you need to know where to go.

In my experience, I’ve found that choosing the simplest thing that could possibly work is a great starting point, and applying iterative design as we go tends to produce the best final result.

Kick It on DotNetKicks.com
Categories: Blogs

Context and Best Practices

Tue, 01/26/2010 - 16:25

Last night, I had a Skype/SharedView session with a buddy in Arkansas trying to apply DDD and “best practices” to an application he was building.  He wanted to use all the ALT.NET tools he’s heard so much about, such as NHibernate, StructureMap and so on.  The problem came when he went to go look at the sample applications for “Floogle Architecture”, and was basically stopped dead in his tracks.  His question to me was, “do I really have to do all this?  It seems like a little overkill”.  He had looked at several reference applications for every different Floogle Architecture out there, and all confused more than enlightened.

Back when I was getting started trying to apply design principles to my work, I also yearned for that golden reference application that would just tell me what I needed to do, or at least show me what I shouldn’t do.  I remember looking at JP Boodhoo’s application he built after a Nuthin But Dot Net course, and I had the same thoughts.  “Do I really have to do all this?  It seems like a little overkill.”  What my buddy and I were missing was context.

Earlier that day, I had a Q&A session with another buddy in town that’s been developing Rails apps to production for around 4 years.  Over the course of the past couple of years or so, I’ve also built up a set of mental best practices when it comes to building ASP.NET MVC applications.  But something had been nagging me.  Rails folks have built large, testable, scalable applications with far far less moving parts.  Why do I need all these moving parts, indirections, abstractions and so on to be successful, when plenty of other folks are successful without them?  Talking with these two folks in one day reminded me (again): Context is king.

The Right Way versus the Better Way

My .NET buddy was building a small application.  It had something like 4 entities and less than 10 screens.  It was a small application built for a specific purpose, and wasn’t really going to get much bigger.  The Floogle Architecture reference applications are built with a much different context .  They could be for applications with hundreds of controllers, dozens upon dozens of entities, and very complex screens.  However, all of that context is missing in each respective reference application.

One of the sticking points from Eric Evans when describing DDD was that DDD was never meant to be applied to every solution.  It’s hard, it’s complex, and it takes a lot of work and collaboration.  In fact, I’ve heard quoted that something like 95% of every application built is not complex enough to warrant a DDD solution.  So why is every application I build using the most complex DDD architecture?  Am I special?  Do I live solely in that 5%, or have I just decided to pick one architecture and apply it globally, no matter the context?

When reviewing my Rails buddy’s actual production Rails app, I was struck by how little code there was, and how flat the architecture is.  He had Model, Views and Controllers, and that’s it!.  All these pieces that I put in place to support complexity, such as a service layer, dependency injection, factories, indirection, facades, the list goes on, were just not needed in his projects.  That’s not to say that the Rails app wasn’t complex.  It had complex querying, validation, caching and so on, but it just didn’t need a lot of code to do so.  Rails apps don’t even have the concept of a project, yet all Floogle Architecture examples highlight the need for proper layer separation through project structure.

Instead of focusing on the “Right Way” to build an application, I should have focused on the “Better Way”.  Sometimes the better way to build an application is to pick the absolute simplest architecture imaginable.  Sometimes I don’t need DDD.  Sometimes I should just use ActiveRecord, because I just don’t have that domain complexity.  When I taught a class for ASP.NET MVC recently, I threw out all my default usage patterns, because building from scratch would pretty much guarantee I built the minimum I actually needed for the context at hand.

Default Architectures

One of the books that heavily influenced my understanding of DDD was Jimmy Nilsson’s book.  In it, he talks about a “new default architecture”.  So I developed an architecture, and applied it pretty much without any thought to every. single. project I worked on.  It works well because I know it and understand it, I know its limitations and its constraints, and I know where it can bend complexity-wise.  Over the years, this default architecture has grown and grown to basically handle every complexity I’ve ever seen.  It’s now very flexible…but very difficult to understand.  Pick any reference DDD architecture out there, and you’ll see the same thing.

And that’s where my .NET buddy went wrong.  He picked what he thought was a default MVC architecture, when instead it was a reference DDD architecture.  His first question should have been, “do I need DDD?”.  In his case, decidedly not.  In in most cases, decidedly not.  When talked with my Rails buddy and mentioned the word “Entity”, I was met with a blank stare.  When I sketched out the flow of control in our default architecture, all the pieces we had to develop, his (polite) response was “That looks…hard…”.  Yes, yes it is hard.  It was completely necessary for the context in which we first developed it, but not for every context.

So why do I try and apply that architecture to every context?  Because I’m lousy at predicting complexity.  However, Rails folks have happily developed large systems to production without all the pieces I decided I needed for every project.  Instead of looking for a “Default Architecture”, I should instead be looking for the “Better Architecture Choice for This Context”.

Starting Small

In the upcoming conversations with my .NET buddy, I’m going to have him throw out all the default architectures he’s looked at.  They are interesting from a patterns/style perspective, but utterly useless if you don’t understand the context behind the decisions that brought the samples to that point.  And for his case, he just doesn’t need them.

Instead, he needs things like “how do I integrate NHibernate?” and “why should I use a DI framework?”.  All the rest can be built up as needed, in a YAGNI fashion, when (or if) the application and the business requirements demand the need for DDD and a complex architecture.

Kick It on DotNetKicks.com
Categories: Blogs

Advanced StructureMap: Diagnosing problems

Fri, 01/22/2010 - 06:21

So you’ve set up StructureMap, got all your registries in a row, go to run the application, and you’re greeted by a rather unfortunate message:

StructureMap.StructureMapException : StructureMap Exception Code:  202
No Default Instance defined for PluginFamily

That’s just one of the issues we can run into.  If you’re doing more advanced things like nested containers, lifecycle management, external plugin folders for dynamic loading, you’re bound to run into binding and other bugs at runtime.  One of the things I like about StructureMap over other containers I’ve tried is the level of support for diagnosis, configuration validation, and testing.

When using any configuration tool, whether it’s IoC container configuration, Web.config or other persistent mechanism for application configuration, you will run into problems.  The first step to diagnosing issues is to write tests.

Testing StructureMap configuration

The easiest way to test your StructureMap configuration is to use the ObjectFactory.AssertConfigurationIsValid() method in a test:

ObjectFactory.Initialize(init =>
{
    init.AddRegistry<HandlerRegistry>();
});

ObjectFactory.AssertConfigurationIsValid();

Internally, StructureMap will loop through all of your registered instances and try to instantiate them.  This can catch 99% of your registration problems, as you might have forgotten a registry somewhere or an instance isn’t defined for something.  The key to remember is that StructureMap can only validate plugin types it knows about.  Just like AutoMapper, it can’t divine all the ways you’re using ObjectFactory.GetInstance() in your codebase.  So typically, AssertConfigurationIsValid() is our first line of defense.

The next way to test is for specific registries.  Suppose we’ve defined some custom registry:

    public class HandlerRegistry : Registry
    {
        public HandlerRegistry()
        {
            Scan(cfg =>
            {
                // etc

If we have some custom registration logic (very likely), then we can then test that registry in isolation from the rest of our configuration.  This is what I do when I’m doing lots of meta-programming to hook up open generic types of things, and in general building highly de-coupled, SOLID stuff ;)

Side note: things like ConnectImplementationsToTypesClosing() should be built in to every IoC container registration.  It’s one of the things I can point to on our current project and say, “that enabled some of our success”.  If we had to register/build these things manually, we wouldn’t have tried to build the architecture we wound up doing, which let us scale our development very easily.

To test a single registry in isolation, you simply need a Container object:

[Test]
public void Should_connect_delete_handler_by_registry()
{
    var container = new Container(new HandlerRegistry());

    var handler = container.GetInstance<IHandler<DeleteEntityCommand<Customer>>>();

    handler.ShouldBeInstanceOf<DeleteEntityCommandHandler<Customer>>();
}

I instantiate a new Container object, but I pass in the instance of my custom registry.  From there, I can then use the Container directly to get an instance.  With registry-specific tests, I can ensure some of my more complex (and insanely powerful) registration is hooked up correctly.  If you’re using a container beyond just hooking up Foo to IFoo, I highly recommend doing registry-specific testing.  It’s much easier to test-drive a registry in isolation than it is to try and catch things at runtime.

Popping open the hood

Sometimes, you’ll get a “No default instance defined” exception, and in those cases, it’s best to just pop open the hood of StructureMap, and see what do I have?

ObjectFactory.Initialize(init =>
{
    init.AddRegistry<HandlerRegistry>();
});

Debug.WriteLine(ObjectFactory.WhatDoIHave());

Wow, there’s a method, “WhatDoIHave()”.  It’s on both ObjectFactory, and Container (ObjectFactory is merely a wrapper around a Container object).  This method returns a nicely formatting string showing everything in our container:

=======================================================================================
PluginType                                                                             
---------------------------------------------------------------------------------------
IHandler`1<DeleteEntityCommand`1<TEntity>> (IHandler`1<DeleteEntityCommand`1<TEntity>>)
Scoped as:  String

Well, there’s a lot more information here, but it basically lists out each registered plugin type and configured instances.  If you see a blank in the configured instances, that’s something that is registered, but doesn’t have a concrete instance.

Lifecycle issues

One of the major features of modern IoC containers is the ability to provide lifecycle management.  This means that we can use our container to control the lifetime of our instance, singleton, per-request, HttpContext, etc. etc.  That’s an extremely powerful tool, but one that cuts very, very deep if it’s not hooked up right.  Unfortunately, it’s also not one that’s easy or even possible to unit test in some cases.  Lifecycle configuration in your container is application behavior, and like things such as web.config, config stored in DB, external XML configuration etc. can only really be verified with the whole app up and going.

Before understanding lifecycle issues, it’s critical that you fully understand the lifecycle of the code calling ObjectFactory/Container.GetInstance().  Whenever I’ve had problems with lifecycle, it’s because I just misunderstood, didn’t understand, or was completely ignorant of the thread lifecycle of whatever was trying to build my lifecycle-configured instance.  My WCF understanding was wrong, and my hand-coded lifecycle management totally screwed up things that were found only after it went to production.  It’s really no different than if you wanted to start storing things in a static cache, but now need to deal with multiple threads, who gets what instance, and so on.

So back to debugging lifecycle issues.  In practice, when things don’t work, I do a healthy dose of logging + GetHashCode() to put out messages showing exactly what gets what instance.  About a year ago, I had to debug a gnarly lifecycle problem.  One thing I found is that it gets much, much harder if you’re instantiating things yourself and get away from DI however, as some old code we had put too many moving parts into play, making it that much harder to understand what came from where.  So my preference is to push as much instantiation into the container as you can.  That said, it’s not for everyone, so you’ll have to decide how much magic juju you’re comfortable with.

That aside, here’s an example of what I like to do:

public class DeleteCustomerCommandHandler : IHandler<DeleteCustomerCommand>
{
    private readonly ICustomerRepository _customerRepository;

    public DeleteCustomerCommandHandler(ICustomerRepository customerRepository)
    {
        Debug.WriteLine("Received instance of ICustomerRepository in DeleteCustomerCommandHandler: " 
            + customerRepository.GetHashCode());
        _customerRepository = customerRepository;
    }

It’s a primitive tool, but I use it to both build and debug lifecycle issues.  It could be Debug, or it could be any logger or whatever to be able to see basically the instance ID from GetHashCode().  I would see log messages of mismatched hash codes, things being instantiated more than I thought they should, and so on.  Whenever I had lifecycle issues, it was because the instantiator had one lifecycle, and the plugin type had another conflicting lifecycle configuration.

Now, this is just my way of debugging lifecycle issues.  If there’s some other ways of doing so, I’d love to hear about it.  I’m pretty sure this could be done also with AOP/profiling tools too.

Wrapping it up

IoC containers are magic juju boxes.  But they don’t have to be, if you have the right tools to test and diagnose problems.  If you do wind up drinking the container kool-aid, be prepared to have something go wrong at some time.  Like other sharp tools, it can really destroy a lot of time if you don’t have a good plan for diagnosing these issues.  And if nothing works, you can always go to the mailing list of your respected project (as long as your project is active and OSS for the most part) for some free help.

Kick It on DotNetKicks.com
Categories: Blogs

My picture of an MVC-WebForms marriage

Tue, 01/19/2010 - 03:25

Like it or not, WebForms is not going away.  Fortune 50 companies use it for their public facing, mission critical websites, and I can’t really see many of these folks tossing away years of work simply because MVC is the new shiny.  Talking with some industry folks, I see a lot of fear/misunderstanding around the MVC/WebForms story going forward.

One thing that Jeffrey at Headspring has convinced me of recently is that there should be a convergence of these two models at some point in the future.  On a recent large project, we’ve had areas where it just made sense to use WebForms.  For us, it was a 3rd party reporting control.  Making the transition there was tough, however, as many things I counted on in MVC just weren’t there any more.  However, recent strides in ASP.NET 4.0 have eliminated many of the existing headaches.

My vision of an MVC-WebForms marriage is one of a seamless harmony, one where I can go back and forth between MVC and WebForms without much issue between the two.  So what is needed to make this marriage last?

Model Binding/Strongly-Typed pages

One of the big pains going from MVC to WebForms is the lack of model binding.  I don’t like poking into controls to get values, nor do I enjoy poking into the querystring/forms collections to manually munge dictionaries.

In addition to model binding would be pages where I could strongly-type the Page class, so that I didn’t have to manually pull junk out of controls.  I could see this done in a variety of ways, whether it’s an overloaded Page_Load event, a different Page base class or whatever.

Shared HtmlHelpers and MasterPages

I’d like to easily generate links from MVC to WebForms, and vice-versa.  Additionally, I don’t want to create a new Master Page for WebForms pages.  I haven’t tried to mix both, but it would be nice to be able to share a common template for both sets of pages.  If I get HtmlHelpers, then I can easily use Url.Action, Html.ActionLink and so on.

Routing

This is already in ASP.NET 4.0, nothing else needed here.  Since I can create routes for WebForms, I can use the route-based URL generators in MVC land to generate a link from an MVC to WebForms page.  Of course, I can always hard-code the .ASPX URL.

There are still situations in every-day work that WebForms is the right way to go.  I like MVC as a pattern more than the presenter/front controller of WebForms, and that’s a conscious choice I make.  But for those wanting to mix technologies, it’s still a little ways off before these can both live together in harmony, if only for those times when I absolutely must use both.

Kick It on DotNetKicks.com
Categories: Blogs

Starting fresh

Mon, 01/18/2010 - 17:12

While prepping for the Headspring MVC Boot Camp last week, I had a couple of choices for getting the examples project up and going.  I wanted the examples to use an actual domain model, a real IoC tool, and a real ORM underneath the covers.  Getting these pieces up and going isn’t necessarily a trivial affair, and time spent doing that is time taken away from preparing the other parts of the course.  So I had two options: The first option would be to take an existing application and pare away the pieces I don’t need.  The second option would be to bite the bullet and just start from scratch.

So what did I wind up doing?  (Drumroll please)  Start from scratch.

And it was sooooooo liberating.  With our existing applications, there’s always one piece or another that doesn’t fit quite right, but you don’t change because “it’s how things are done” or “it already works”.  That’s great for a lot of solutions, but I’m now seeing is a poor choice for micro-design solutions.  For example, I don’t really want to design templated HTML builders for every project, nor do I want to design an object-object mapper every time either.  Those types of pieces can be abstracted into mini-frameworks to consume.

But then you have things like “how to use NHibernate”, the default Repository design, the “right way” to read from files and so on.  For those pieces, I just tossed out everything and started over.  As in, let’s completely re-evaluate how I use these 3rd-party libraries and how I’ve solved these problems in the past.  I wound up with a completely different design than I’ve used before, and one that I like better than ones I’ve used in the past.  Had I merely incrementally improved my existing approach, I wouldn’t have arrived at the point I used in the class.

Incremental design doesn’t just mean making small changes to one class.  Incremental design isn’t merely incremental change.  Sometimes, you just need to throw everything out, build on what you’ve learned, and take a clean approach to get to a better final design.

Existing code is baggage, be careful how much you pull from previous projects and existing work.  While it can be tempting to try and set a high starting point, it may set you back in the long run.  On our current project, we held ourselves back for quite a while by sticking with designs we did not consciously choose in the first place.  Once we got over our fear of change, we landed in a much better place than where we started.

However liberating this was, it’s still not one I’d do on every project.  For smaller projects, it’s great to have an existing infrastructure in place so you can start delivering value on day 1.  But for longer-term projects, where only innovation will keep your velocity from stagnating or even dropping over time, we found that only by throwing out our existing prejudices and assumptions could we have the right state of mind to truly embrace change.

Kick It on DotNetKicks.com
Categories: Blogs

Poor use of DI versus need for DI

Mon, 01/18/2010 - 16:19

Surprise surprise, but Uncle Bob got the twitterverse all riled up with another opinionated post, “Dependency Injection Inversion”.  His basic advice from the post on DI tools is:

I think these frameworks are great tools. But I also think you should carefully restrict how and where you use them.

Couldn’t agree more!  Every call to Container.GetInstance should be carefully, carefully thought out.  In fact, our goal should be to reduce the number of calls to the container to hopefully exactly one.  But a slight problem with the example he gives to show that DI is not necessary in all cases:  It’s so simplistic that it no longer represents any real-world code using DI.

Uncle Bob also prefers hand-rolled mocks, which may be an artifact of the crappiness of Java mocking tools, which in turn is a reflection of how far behind Java the language is behind C#.  He also points out:

I don’t want lots of concrete [Container] dependencies scattered through my code.

Couldn’t agree more!  That’s why we limit the container calls in our application as much as possible.  If I have a bunch of container calls in my code, I’m doing something wrong.  When I read his post, I thought that they must have been looking at the MVC framework source code, one which was built with IoC hooks, but not with the Dependency Inversion Principle in mind.  If I have to tell MVC that I’m using an IoC tool, it takes quite a bit of work to configure all of the places where things get instantiated manually to work.  I often have to write new classes just to support IoC.  Whether he meant to or not, Uncle Bob’s entire post was a straw man argument.  He argues against bad use of IoC, but never shows good use of IoC.  Which may mean that he’s never built or seen an application built well with IoC.

If you want to see an application written with DIP, IoC and Dependency Injection in mind, check out FubuMVC.  One of its core principles from the get-go was “turtles, all the way down”, basically meaning that a container will be used, and you cannot use the application without an IoC tool.  Guess what?  The design is much cleaner for it.

If I want to use an IoC tool in my application, this is something that should be configured once and only once.  If I have to plug a bunch of hooks just to say, “Yes, I am using an IoC tool”, then I haven’t really improved anything for the end user, have I?  Instead, I’ve made my application favor configuration over conventions, forcing more coding and more moving parts to figure out, making it more difficult to configure as needed.

So while it’s a great read and has a lot of great points, all that post showed me was that poor use of DI leads to a poor DI experience.

Kick It on DotNetKicks.com
Categories: Blogs

Advanced StructureMap: custom registration conventions for partially closed types

Thu, 01/07/2010 - 18:59

A while back, I highlighted an issue we ran into where I had basically partially closed generic types.  A common pattern in message- and command-based architectures is the concept of a handler for a message:

public interface IHandler<TEvent>
{
    void Handle(TEvent args);
}

It’s a pattern with many names, but the basic concept is to separate the execution of a command from the representation of a command.  We use it with our ActionResult objects, command messages and lots of other places where creating a parameter object separate from the method using the parameter object provides a great benefit.  But as we used this pattern more and more, we would start to see duplication around certain types of commands.  For example, we might have a command to delete a customer:

public class DeleteCustomerCommand
{
    public DeleteCustomerCommand(Customer customer)
    {
        Customer = customer;
    }

    public Customer Customer { get; private set; }
}

And the implementation is fairly straightforward:

public class DeleteCustomerCommandHandler : IHandler<DeleteCustomerCommand>
{
    private readonly ICustomerRepository _customerRepository;

    public DeleteCustomerCommandHandler(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public void Handle(DeleteCustomerCommand args)
    {
        _customerRepository.Delete(args.Customer);
    }
}

That’s all fine and dandy, but now I have to create another handler for every. single. entity. type. in. the. world.  That’s duplication I’d like to avoid, especially since it provides absolutely zero value (other than extra code I have to maintain).  Instead, I’d like to define a generalized command:

public class DeleteCommand<TEntity>
{
    public DeleteCommand(TEntity entity)
    {
        Entity = entity;
    }

    public TEntity Entity { get; private set; }
}

Now I only need to define a generic handler for this command:

public class DeleteEntityCommandHandler<TEntity> : IHandler<DeleteEntityCommand<TEntity>>
{
    private readonly IRepository<TEntity> _repository;

    public DeleteEntityCommandHandler(IRepository<TEntity> repository)
    {
        _repository = repository;
    }

    public void Handle(DeleteEntityCommand<TEntity> args)
    {
        _repository.Delete(args.Entity);
    }
}

Up to this point, I’ve shown nothing new that I didn’t already have in that previous open generics post.  The trick now is to hook up the right handler to the right message.  In the last StructureMap post, I showed how to hook up IHandler<T> to the concrete implementation.  But in this case, I don’t have a concrete implementation.  I will request an IHandler<DeleteEntityCommand<Customer>> or Order or whatever, and I need to wire up a new concrete type, DeleteEntityCommandHandler<Customer> (or Order or whatever).

Because I have the issue where I don’t know the concrete type until it’s requested, I need to tell my IoC Container of choice (StructureMap) how to handle these requests.

Creating a custom registration convention

Quick note on StructureMap – internally, concrete types are matched up to requested types through configuration.  StructureMap does a great job at reducing the amount of configuration through registration conventions, registries and configuration, but I still have to match up every concrete service type to a requested type.  StructureMap (I believe) doesn’t let you wait until a type is requested to find its implementation, it already needs to know it beforehand.

So how does that affect me?  For one, I only have one implementation, but it’s generic.  I could literally have as many closed generic implementations as there are entities in my system, because each will get its own (correct) repository implementation.

The interesting thing about the “ConnectImplementationsToTypesClosing” method I highlighted last time is that this is actually just a helper method to use an existing IRegistrationConvention (previously TypeScanner in 2.5.3 and earlier).  The IRegistrationConvention is a fairly simple interface:

public interface IRegistrationConvention
{
    void Process(Type type, Registry registry);
}

During the scanning process, StructureMap will call any convention I add, passing in the type to check and a Registry object.  If the type seems interesting to me, I’ll register the interface and implementation in the Registry object.  So what do we need to do here?

Basically, we want to look for all subclasses of Entity, and register the delete command handler for that entity type.  To do so, it will require some open generics magic:

public class DeleteCommandRegistrationConvention : IRegistrationConvention
{
    private static readonly Type _openDeleteCommandType = typeof(DeleteEntityCommand<>);
    private static readonly Type _openHandlerInterfaceType = typeof(IHandler<>);
    private static readonly Type _openDeleteCommandHandlerType = typeof(DeleteEntityCommandHandler<>);

    public void Process(Type type, Registry registry)
    {
        if (!type.IsAbstract && typeof(Entity).IsAssignableFrom(type))
        {
            Type closedDeleteCommandType = _openDeleteCommandType.MakeGenericType(type);
            Type closedHandlerInterfaceType = _openHandlerInterfaceType.MakeGenericType(closedDeleteCommandType);
            Type closedDeleteCommandHandlerType = _openDeleteCommandHandlerType.MakeGenericType(type);

            registry.For(closedHandlerInterfaceType).Use(closedDeleteCommandHandlerType);
        }
    }
}

First, I create some static members for all the open generic types I care about.  Notably, the open command type, the open handler interface type, and the open command handler type.  What I want to do is hook up all requests for IHandler<DeleteEntityCommand<Foo>> to the closed type DeleteEntityCommandHandler<Foo>.  In the Process method, I look for all non-abstract subclasses of Entity, and close all the open types.  Finally, I instruct StructureMap to wire up the closed interface (IHandler<>) to the closed implementation (DeleteEntityCommandHandler<>).

Hooking up our custom registration convention

In the last article, I hooked up the IHandler implementations.  We’ll need to keep that, but additionally register not only the convention we created, but the repositories we use as part of the concrete handler:

public class HandlerRegistry : Registry
{
    public HandlerRegistry()
    {
        Scan(cfg =>
        {
            cfg.TheCallingAssembly();
            cfg.IncludeNamespaceContainingType<OrderCanceledEvent>();
            cfg.ConnectImplementationsToTypesClosing(typeof(IHandler<>));
            cfg.ConnectImplementationsToTypesClosing(typeof(IRepository<>));
            
            cfg.Convention<DeleteCommandRegistrationConvention>();
            cfg.WithDefaultConventions();
        });
    }
}

To add a convention, I use the “Convention” method and pass in the convention type.  To hook up the repositories, I add both the line to connect implementations for IRepository<>, as well as the “WithDefaultConventions”, which matches up ICustomerRepository to CustomerRepository.  I don’t need that last part for this example, but is almost always included in most of my scanning operations.

With this in place, my test now passes:

[Test]
public void Should_connect_delete_handler()
{
    ObjectFactory.Initialize(init =>
    {
        init.AddRegistry<HandlerRegistry>();
    });

    ObjectFactory.AssertConfigurationIsValid();

    var handler = ObjectFactory.GetInstance<IHandler<DeleteEntityCommand<Customer>>>();

    handler.ShouldBeInstanceOf<DeleteEntityCommandHandler<Customer>>();
}

It’s a lot of angle-bracket tax, but you never actually see this many angle-brackets.  My application will push commands out, and a rather brainless command processor will locate handlers for the command, and execute them.  With StructureMap (and IoC in general), I can start to really reduce duplication when that duplication is around the type varying, by prudent application of generics.  Here, I’m not using generics for type safety, but to reinforce the DRY principle.

With a powerful IoC tool, I don’t have to compromise on my command processing design just because I have complex message/handler shapes.  Instead, the command processor stays simple, and lets my IoC registration encapsulate all of the wiring.

Kick It on DotNetKicks.com
Categories: Blogs

MVC Bootcamp next week

Wed, 01/06/2010 - 16:54

Next week, I’ll be teaching a 3-day course on ASP.NET MVC, as part of Headspring’s ASP.NET MVC Boot Camp.  The material touches on a lot of the ASP.NET MVC features we use day-to-day, as well as looking at how we use ASP.NET MVC.  Topics will include (but not be limited to):

  • History/Overview of ASP.NET MVC
  • Separated solution structure
  • Basic & customized routes
  • Customized route handlers
  • Controller selection
  • customized controller factories
  • Controller & Action patterns & anti-patterns
  • Read-only views
  • Data-entry views
  • Presentation Model
  • Advanced ActionResults
  • Action filters and ActionFilterAttribute
  • Server-side validation
  • JQuery integration
  • Deployment and installation
  • Advanced View Helpers
  • AJAX with ASP.NET MVC
  • T4 Templating
  • Connecting with data access, messaging, etc.

We’ve really put MVC through its paces over the past couple of years, so I’m excited about sharing what we’ve learned (at least everything I can fit in 3 days).  You can call us to enroll: (877) 459-2260.  Hope to see you there!

Kick It on DotNetKicks.com
Categories: Blogs

UI Automation tools snake oil?

Mon, 01/04/2010 - 16:03

Michael Feathers posted a thoughtful piece describing the general problems of UI testing tools and the industry in general.  In general, I’d agree here.  Automation tool vendors, as with almost every tool vendor out there, are eager to solve perceived software development problems.  Unfortunately, these tools usually only address symptoms of larger problems.

With UI testing tools, this is no different.  When we started out authoring UI tests for a large MVC application, we had a few large goals in mind.  The tests needed to be:

  • Stable
  • Understandable
  • Maintainable
  • Valuable

To achieve these goals, we needed to do exactly what we do when we write code using TDD, design for testability.  I won’t go into everything we did, there’s already a whole screencast on that.  However, Michael does bring up some key points:

  • UI tests should test the UI layer
  • Architect your system so that you can test all of your business logic separate from the UI layer

That’s what we’ve done, and it’s been very successful.  We have UI tests, around 500 of them, and we’re not staying up until all hours of the night keeping them working.  We also have subcutaneous tests, that work in a layer right below the UI layer, that allow us to send a UI message into our system and check what comes out on the other side, whether it’s business rule violations or entities modified.

All of our testability enhancements came from design for testability.  We use strongly-typed views.  We don’t have any business/domain logic in controllers, only UI controller logic.  Separating your architecture into layers isn’t for portability, it’s for separation of concerns.  Once we started designing for testability in the large, and not just the unit level, we were able to maximize the value of automated tests, both at the UI, integration and unit level.

If anything, this is another example of the need for a developer to work on their spidey sense for vendor product demos.  We rail on MS for drag-and-drop demos, but it’s every tool vendor that employs this technique.  Just like every other product sold in the world, it’s up to the buyer to be critical of the true value a tool can bring.

Kick It on DotNetKicks.com
Categories: Blogs

AutoMapper DSL design post-mortem

Wed, 12/23/2009 - 07:28

As I move towards the 1.0 release of AutoMapper, I’m already running in to things I wish I had done differently.  I still will probably fix all of these eventually, but none of these design issues should prevent a release, especially since it’s not any public functionality.  A lot of it came from trying out designs in the open, but it can be difficult to change direction once it’s out in the open and in production.  The Fluent NHibernate guys have changed their API quite a bit up to release, for better or worse, and I wasn’t too keen to follow that same path.

That said, in no particular order:

Static gateway

Everything in AutoMapper drives through a static class, “Mapper”.  Both configuration and the mapping engine can be accessed through this one class, so you have a responsibility of:

  • Configuring the global settings
  • Configuring individual mappings
  • Performing mappings
  • Managing configuration and mapping engine instances

The first three are too much for one class, but it’s the last one that’s gotten me into the most trouble.  Writing thread-safe code is hard, and I’ve had to rely on bug reports from the field to make sure it works correctly in a multi-threaded environment.  This design mostly came from inspiration from StructureMap, unbeknownst to me that its creators had already ditched this design (even though its creator works in the same town :P).  I had already been warned by my boss, Jeffrey, to ditch the static-central design.

I did eventually ditch it, but only to create a static facade.  Instead, I should have gone the NHibernate route for configuration, where configuration objects are just regular objects, and it’s up to you to decide how you want these things to stick around.  In the future, I’m thinking of obsoleting the public static methods and going more of the NHibernate route, where you use the configuration object as a factory object to create the engine.

Ad-hoc versus nested closure for configuration

If you check out Fluent NHibernate, a configuration object is created through a nested closure:

return Fluently.Configure(configuration)
    .Mappings(cfg =>
    {
        cfg.HbmMappings.AddFromAssemblyOf<Customer>();
        cfg.FluentMappings.AddFromAssemblyOf<Customer>();
    }).BuildConfiguration();

See that whole lambda block with the “cfg” object?  That’s a nested closure.  What’s nice about that pattern is that it allows me to collect all the configuration, basically record it, and then act upon after you’re done.  Compare it to “Mapper.CreateMap”, I don’t know when you’re done creating mappings.

One other thing Fluent NHibernate does is that it actually returns the configuration object, for you to do what you want with it.  Because NHibernate needs to support all sorts of deployment scenarios, they’ve basically left it up to you to manage that instance as you want.  For most installations, Configuration (and SessionFactory) is static/singleton.  The same applies to the corresponding AutoMapper objects, except I’ve put in code to manage these internal objects, that I’d love to delete.

Not to mention that I could pre-optimize all of the mapping algorithms at the end of the configuration operation, making things speedy from the get-go.  With method chaining, you never really know that a configuration operation is finished, unless you put in some hokey “Finalize()” method or something.

Semantic model design

In an internal DSL, the semantic model is basically the domain model of the DSL.  To simplify things early, I let the population model be the same as the operational model.  That is, when you call methods in the configuration operations of AutoMapper, you’re literally setting up the configuration objects.  This works for simple scenarios, but you can run into problems later.  For example, if you don’t make the piece setting up the “ConstructServicesWith” in AutoMapper as basically the first thing, your subsequent setup won’t get this configuration.

With a combined operational/population model, it makes it impossible to perform a better two-step configuration process, where you first record the configuration, and then apply it in the right order to the operational model.  Luckily, I used explicit interface implementation to not bleed the two APIs publicly, but all my configuration objects implement both a population and operational interface.

It’s a subtle thing, but moving towards a nested closure model for creating configuration (as already exists in a limited form with AutoMapper.Initialize) makes doing a separated population/operation model a much stronger proposition.

The wacky Configure method on Profile

It’s wacky, and was already recognized as a bad design in StructureMap when I put it into AutoMapper.  In AutoMapper Profiles, you inherit from the Profile object, which provides Object Scoping for creating profile-specific maps.  If you haven’t noticed by now, Martin Fowler’s DSL-WIP collection is practically the resource for DSL design.  So why did I have this wacky Configure() method that you have to override?  Well, besides it’s what Fowler had in his example, I’m forced into this corner because I didn’t separate the operational and population interface of the semantic model.

When a Profile object is created, I need to perform some initialization on it before any configuration calls are made.  So, you have this one method to override, instead of just doing everything in the constructor.  Small issue, but something I’ll almost surely change in the future.

None of these design changes will affect the public API much, as I’d likely continue the existing API and provide a migration path if I do decide to make any big changes.  The nice thing about the current design is that it’s very, very simple to get started.  However, this simplicity tends to demo well, but doesn’t scale in real-world settings.  As I move towards 2.0, I’ll make sure I balance a better DSL design, but keep the essence of the existing simplicity.

Kick It on DotNetKicks.com
Categories: Blogs

Advanced StructureMap: connecting implementations to open generic types

Fri, 12/18/2009 - 06:03

One pattern we’re starting to see more and more is the idea of connecting messages to handlers.  These messages might be domain command messages, ActionResult messages, and more.  Beyond messaging implementations, we start to see a more basic pattern start to emerge.  We have some interface describing a contract that happens to be generic:

public interface IFooService<T>
{
    void DoSomething(int value, T foo);
}

Now, if we weren’t doing IoC, and we needed a specific FooService for some type T, we’d have to know which type to get.  But you might start to see situations where you need an IFooService<T>, but you don’t really care about the T specifically:

public class SomethingThatUsesFoo<T>
{
    private readonly IFooService<T> _service;

    public SomethingThatUsesFoo(IFooService<T> service)
    {
        _service = service;
    }

    public void SomethingSpecific(T value)
    {
        _service.DoSomething(4, value);
    }
}

As you start to build more and more generic components, building out common infrastructure components, you’ll start to build more common services like these, that coordinate between a messages and their handlers.  In most cases like these, we’re not using generics for type safety, but rather for metadata to match up input types to output services.  A more concrete example on a real project looks like this:

public interface IHandler<TEvent> 
{
    void Handle(TEvent args);
}

This is an interface for domain events, where we’ll have handlers like:

public class OrderCanceledEvent
    : IHandler<OrderCanceledMessage>
{
    public void Handle(OrderCanceledMessage args)
    {
        // send an email or something
    }
}

Now the trick is, how do we instruct our Inversion of Control container to locate the right handler for the right event?  If you’re using StructureMap, it’s dirt, dirt simple.

Configuring StructureMap

Because we’re using StructureMap, we’ll be using a custom Registry to do our configuration.  To connect implementations, we want to make sure that any time we ask StructureMap for an IHandler<T>, it finds the concrete type of handler T.  In the above example, our common message routing code will ask for an IHandler<OrderCanceledMessage>, and the type located needs to be OrderCanceledEvent, because OrderCanceledEvent implements the IHandler<OrderCanceledMessage>.

Our Registry winds up being very simple:

public class HandlerRegistry : Registry
{
    public HandlerRegistry()
    {
        Scan(cfg =>
        {
            cfg.TheCallingAssembly();
            cfg.IncludeNamespaceContainingType<OrderCanceledEvent>();
            cfg.ConnectImplementationsToTypesClosing(typeof(IHandler<>));
        });
    }
}

To connect implementations to our open generic type of IHandler<T>, we use the ConnectImplementationsToTypesClosing method.  The other two are just directions telling StructureMap where to look for my handlers.  Typically, my registration code lives in the same assembly as the actual interfaces I’m registering, but you can also register by name.

But that’s it!  Very simple, one line to connect all of the handlers to their implementations.  I can verify this with a simple test:

[Test]
public void Should_connect_types()
{
    ObjectFactory.Initialize(init =>
    {
        init.AddRegistry<HandlerRegistry>();
    });

    ObjectFactory.AssertConfigurationIsValid();

    Debug.WriteLine(ObjectFactory.WhatDoIHave());

    var handler = ObjectFactory.GetInstance<IHandler<OrderCanceledMessage>>();

    handler.ShouldBeInstanceOf<OrderCanceledEvent>();
}

This test passes, and all is well in IoC land.

Embracing the container

At some point, users of IoC learn to stop caring and love the bomb container.  In our system, we have no less than ten usages of this method, meaning we have refactored a lot of common plumbing and coordinators into our infrastructure layer.  We can easily add new handlers, mappers, repositories, providers, commands, builders, invokers, etc., all with one line of configuration for each open type (NOT one per derived type/implementation).  It certainly opens the doors to new possibilities of separation of concerns between different pieces, we just happen to lean on the type system to route our information around.

Something to note here is that at no time did I need to describe the implementors.  StructureMap’s scanner merely found implementations of types closing IHandler<T>, and connected that concrete type to the requested type of IHandler<SpecificType>.  I’ve taken a look at the other containers, and frankly, I haven’t found any that match this level of simplicity in configuration.  But I’m not an expert on the other containers, so I’d love to be proven wrong!

Regardless, I absolutely love this pattern of usage in IoC.  It promotes a level of SOLID design that’s pretty tough to beat.  When folks talk about IoC only being useful in large or complex projects, I just don’t understand it.  Usages like this give me Separation of Concerns from the get-go, at almost zero cost.  If only other frameworks were built with this in mind

Kick It on DotNetKicks.com
Categories: Blogs

Enabling IoC in ASP.NET ActionResults (or, a better ActionResult)

Sat, 12/12/2009 - 18:25

One of the more interesting abstractions in ASP.NET MVC is the concept of an action result.  Instead of calling a method to direct the result of calling an action, such as frameworks like Rails allows:

   def create
      @book = Book.new(params[:book])
      if @book.save
            redirect_to :action => 'list'
      else
            @subjects = Subject.find(:all)
            render :action => 'new'
      end
   end

Instead, the return value of an action directs the MVC pipeline on what to do next:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    return View();
}

Instead of displaying the view when the View method is called, the command to render a view is packaged up into a ViewResult object, containing all of the information needed to render a view.  This is the basic command pattern, and each derived ActionResult is a different command.  There are quite a few subclasses of ActionResult, each representing a different command for the MVC pipeline:

  • JsonResult
  • ViewResult
  • RedirectResult
  • FileResult
  • etc

If you want custom processing of the result of an action, a custom ActionResult is what you’re looking for.  We have quite a few in our applications, including:

  • Streaming a CSV version of the current screen
  • Executing a domain command
  • Executing a delete

And a few more.  While the abstraction of a parameter object to represent a command is a fantastic idea, the design of the ActionResult type is hindered by too many responsibilities.  Namely, an ActionResult is responsible for:

  • Representing the parameter object of a command
  • Executing the command

It’s that second responsibility that can hinder some more interesting scenarios.  Because the controller action needs to instantiate a parameter object as the result of an action, I’m often reduced to sub-optimal service location to do the actual work of the executing action.  For example, the delete action result might look something like:

public class DeleteRequestResult<TModel> : ActionResult
{
    private readonly TModel _model;
    private readonly Func<ActionResult> _successRedirect;

    public DeleteRequestResult(TModel model, Func<ActionResult> successRedirect)
    {
        _model = model;
        _successRedirect = successRedirect;
    }

    public TModel Model { get { return _model; } }
    public Func<ActionResult> SuccessRedirect { get { return _successRedirect; } }
    
    public override void ExecuteResult(ControllerContext context)
    {
        // Service location, boooooo!
        var repository = IoC.GetInstance<IRepository<TModel>>();
        var logger = IoC.GetInstance<IDomainLogger>();

        repository.Delete(Model);
        logger.LogDelete(Model);

        var redirectResult = SuccessRedirect();

        redirectResult.ExecuteResult(context);
    }
}

I have to resort to service location (blech) to load up the right dependencies to do the actual work of processing a delete request.  However, instead of relying on the ActionResult to be responsible for executing the command, I’ll instead allow something else take over that responsibility.

Separating the ActionResult concerns

First, I need to define an abstraction of something that can execute an ActionResult.  That sounds like an IActionResultInvoker to me:

public interface IActionResultInvoker<TActionResult>
    where TActionResult : ActionResult
{
    void ExecuteResult(TActionResult actionResult, ControllerContext context);
}

The signature is very similar to ActionResult, but this time, it’s a separate object that receives the parameter object (the ActionResult), the ControllerContext, and actually performs the work.  Next, I need to now direct the default action invoker to invoke action results through my abstraction, instead of going through the regular action result itself.  However, because all of the built-in action results aren’t going to change, I need to handle that scenario.  To accomplish this, I’ll create a new ActionResult type:

public abstract class BetterActionResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        throw new NotImplementedException("Should be executed with an IActionResultInvoker");
    }
}

That should be enough to provide some notification when we’re developing if we haven’t hooked things up correctly.  Next, I’ll need the default action invoker overrides:

public class IoCActionInvoker : ControllerActionInvoker
{
    private readonly IContainer _container;

    public IoCActionInvoker(IContainer container)
    {
        _container = container;
    }

    protected override void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
    {
        if (actionResult is BetterActionResult)
        {
            // Close the IActionResultInvoker<> open generic type
            var actionResultInvokerType = typeof (IActionResultInvoker<>).MakeGenericType(actionResult.GetType());

            // Get the invoker from the container
            var actionResultInvoker = _container.GetInstance(actionResultInvokerType);

            // Get the generic ExecuteResult method
            var executeResultMethod = actionResultInvokerType.GetMethod("ExecuteResult");

            // Call the ExecuteResult method
            executeResultMethod.Invoke(actionResultInvoker, new object[] { actionResult, controllerContext });
        }
        else
        {
            base.InvokeActionResult(controllerContext, actionResult);
        }
    }
}

It’s a lot of code, but what I’m basically doing here is looking for derived BetterActionResult action results, and using my StructureMap container to load up the correct IActionResultInvoker for that derived ActionResult type.  In the example above, I use just basic reflection for calling the ExecuteResult method, but in practice, I’ll use caching and an optimized mechanism for reflection.

Connecting the action invoker to the MVC pipeline

Now, I could have used a looser-typed signature for IActionResultInvoker, and not needed to do this reflection business.  However, it’s critical that I load up the correct IActionResultInvoker for my derived BetterActionResult.  Using generics is a great way to use the type system for routing to the correct handler.  To replace the existing action invoker, I have a couple of choices.  One simple way of doing so is to modify the controller factory (that I’m already overriding for using IoC to instantiate my controllers):

public class ControllerFactory : DefaultControllerFactory
{
    private readonly IContainer _container;

    public ControllerFactory(IContainer container)
    {
        _container = container;
    }

    protected override IController GetControllerInstance(Type controllerType)
    {
        if (controllerType == null)
            return null;

        var controller = (Controller)_container.GetInstance(controllerType);

        controller.ActionInvoker = _container.GetInstance<IoCActionInvoker>();

        return controller;
    }
}

My custom controller factory is already hooked up using a technique like this one, I don’t have to do anything extra to make sure my action invoker gets executed.  I just overrode the method I needed, hooked up the action invoker on controller construction time, and I’m ready to go.

The next piece is to actually define my custom action invoker, and refactor my existing DeleteRequestResult type.

Defining a new invoker and action result

First, I’ll need a new ActionResult type for my original representation of a delete request.  This time, I’ll only have the parameters needed to perform the action, and my action invoker will take care of the rest.  The custom action result type now becomes very simple:

public class DeleteRequestResult<TModel> : BetterActionResult
{
    public DeleteRequestResult(TModel model, Func<ActionResult> successRedirect)
    {
        Model = model;
        SuccessRedirect = successRedirect;
    }

    public TModel Model { get; private set; }
    public Func<ActionResult> SuccessRedirect { get; private set; }
}

I’m no longer mixing the concerns of parameter object and command execution any more.  Instead, I’ll define a new custom action invoker:

public class DeleteRequestResultInvoker<TModel> 
    : IActionResultInvoker<DeleteRequestResult<TModel>>
{
    private readonly IRepository<TModel> _repository;
    private readonly IDomainLogger _logger;

    public DeleteRequestResultInvoker(IRepository<TModel> repository, IDomainLogger logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public void ExecuteResult(DeleteRequestResult<TModel> actionResult, ControllerContext context)
    {
        _repository.Delete(actionResult.Model);
        _logger.LogDelete(actionResult.Model);

        var redirectResult = actionResult.SuccessRedirect();

        redirectResult.ExecuteResult(context);
    }
}

Now, when my IoCActionInvoker looks for an action invoker for DeleteRequestResult<TModel>, it will find my custom action invoker, instantiate it with IoC, and use its ExecuteResult method.  The controller action becomes pretty small now:

public DeleteRequestResult<Product> Delete(Product productId)
{
    return new DeleteRequestResult<Product>(productId, () => RedirectToAction("Index"));
}

When I go to test this action now, I only need to make sure that the product supplied is correct and the success redirect is correct.  Because deletions don’t really change in our domain, we abstracted deletions into a separate ActionResult and IActionResultInvoker.

Wrapping it up

The piece I didn’t show here is how to hook up your IoC container to tell it that when it looks for an IActionResultInvoker<DeleteRequestResult<TModel>>, it loads up the DeleteRequestResultInvoker<TModel>.  That code is different for every container, so I’ll go into that piece in a future post.

The interesting part about this pattern is that I’m able to separate the concerns of a parameter object representing the results of an action, and the actual processing of that parameter object.  These two concerns usually have different reasons for change, and I’d rather not rely on things like service location for opaque dependency resolution in the execution of the ActionResult.  Because our IoC registration discovers new invokers quite easily, I never really need to add any new code for new action result invokers.  I merely need to create a new BetterActionResult type, define an invoker, and my IoC container does the rest.

The custom ActionResult made it easy to represent common execution patterns, in a way that doesn’t pollute my controllers with duplication and enables much easier testing.  Just as I don’t test a ViewResult for the contents of a view, in my example, I just make sure the custom ActionResult gets the correct parameters.  While many areas in MVC are designed for IoC scenarios in mind, others are not.  However, with some creative changes, we can enable places like ActionResult execution pipeline for powerful IoC scenarios.

Kick It on DotNetKicks.com
Categories: Blogs

InfoQ interview on ASP.NET MVC in Action up

Wed, 12/09/2009 - 15:53

Last week, Jeffrey, Ben and I were interviewed by Jon Arild Tørresdal at InfoQ to talk about our recent book ASP.NET MVC in Action.  I’ve always loved the InfoQ interviews (as well as their articles), as they asked us really great questions.  Not the normal “do you like ASP.NET MVC or do you like like ASP.NET MVC”?  You can check out the interview here.

In addition to the interview, we also put up a free chapter and a discount code for 35% off the book.  Thanks again to the InfoQ team for the interview, and as always, a great website with great content!

Kick It on DotNetKicks.com
Categories: Blogs

Organizing ASP.NET MVC solutions

Wed, 12/09/2009 - 04:27

Recently, a question came up on Twitter around your favorite project structure/solution organizing for ASP.NET MVC projects.  I’ve toyed around with quite a few different strategies for structuring projects, and I’m currently settled around one that gives me the most flexibility.  It’s extremely simple:

image

That’s it, two projects.  So what goes in each project?  Let’s first look at the UI project.  The UI project contains only website content and contains no code.  And I mean no code.  This includes:

  • No controllers
  • No models
  • No Global.asax.cs
  • NO CODE AT ALL

Why no code?  Because when the UI project contains only UI content and no code, my UI project now matches the deployment structure.  It contains:

  • Views
  • CSS
  • Images
  • Global.asax
  • Web.config
  • Reference to the Core project

Since my UI project structure matches my deployment structure, it makes it a lot easier to figure out how the deployment should work.  With controllers, models and so on in the mix, it becomes more difficult to see what gets included for deployment (the Content, Scripts and Views folder) versus what is left out.  We can then organize two different concerns separately: our content and our code.

So where does code go?  That’s the other project.  I call it “Core”, but it can be anything.  All code goes in one project, that includes our persistence model, view model, controllers, repositories, ORM mapping definitions, EVERYTHING.

Organizing the code

As far as organizing the code – I prefer keeping things simple.  If I had my druthers, the UI project wouldn’t compile at all – it would just be a folder, holding content.  Its “bin” folder would merely get populated by the output of the Core project.

Otherwise, I use folders to organize code.  Projects are okay for organization, but they’re pretty rigid and tend to lock you in to layers and structure that are quite, quite difficult to change.  I’ve already been burned a couple of times on large projects making a mistake in my project structure, and found that this approach tends not to scale.  I’ve even run into teams with upwards of 100 projects, with only a half-dozen actual deploy targets!  Remember, compile time is largely a function of the number of projects.  1000 files in a single project will compile much much faster than 100 files in 10 projects.  At least an order of magnitude faster in cases I’ve seen.

Another issue I ran into was the difficulty in re-organizing code if you’re locked into a project structure.  Besides just a sloooooooow Ctrl+F5 experience, it can be quite frustrating to realize you’re going to hose your entire source control log history because you want to move a file to a different project.  In one recent hair-pulling re-organization experience, we basically lost our entire log history because we couldn’t do basic source control commands for a re-organization.  This is exacerbated with source control systems like TFS which embed source control information in the actual project files.  In our case, we had to delete all of our projects and re-create them by hand.  Moving folders is waaaaaaay easier than dealing with projects and dependencies.  You will want to re-organize your code, in a major, major way at some point.

If you’re having problems with layering your codebase – projects are a great way of dealing with this problem.  It enforces dependencies quite nicely, basically forcing you to follow certain rules.  However, once you get to the point where you’re starting to create a “Common” project, a “Configuration” project, a “Mappings” project and so on, consider rolling things back up into one project.  Continuing down the project path will introduce friction in just basic everyday coding tasks, so at some point, it’s just not worth it.

So why not just do one UI project?  Put all the code in there, and get the absolute fastest and the most flexible experience?  Content structure is a completely different concern with completely different reasons for change than organizing code.  However you decide to organize your code, keeping the code out of the UI project ensures that you don’t mix code and content organization.

Kick It on DotNetKicks.com
Categories: Blogs

LINQ query operators and null lists

Wed, 12/09/2009 - 01:42

One of my pet peeves with the LINQ extension methods is their inability to handle null source lists.  For example, this will throw an ArgumentNullException:

[Test]
public void Should_handle_nulls()
{
    List<int> ints = null;

    ints.Any(num => num < 0).ShouldBeFalse();
}

Now I know what you’re saying – why not check for null, or not allow the list to be null in the first place?  After all, the Framework Design Guidelines book recommends that methods and properties that return collection types never be null.  This is so you can merely check for empty collections, and not force users to have null checks everywhere.  That’s all fine and dandy…until you’re forced to interact with systems that don’t play nice.  Especially around serialization libraries, we find places where they don’t abide by this suggestion.

Instead, we have to add a rather annoying, but necessary extension method:

public static IEnumerable<TSource> NullToEmpty<TSource>(
    this IEnumerable<TSource> source)
{
    if (source == null)
        return Enumerable.Empty<TSource>();

    return source;
}

And now my test will pass, as long as I make sure and convert these values properly:

[Test]
public void Should_handle_nulls()
{
    List<int> ints = null;

    ints.NullToEmpty().Any(num => num < 0).ShouldBeFalse();
}

So yes, it’s annoying, and I’d rather the LINQ operators just ignore null collections, or replace them with Enumerable.Empty().  Until then, we just have to use this annoying extension method.

Kick It on DotNetKicks.com
Categories: Blogs