Brainstorming: Events

By Ryan at January 20, 2010 17:28
Filed Under: Development

While working on my side project, I’ve spent a lot of time trying to work out the best design. Keep in mind that this is more of a hobby for me, so I’m not trying to rush to publish a prototype to get VC.

I’ve worked in the enterprise application development space for several years, so I’m plenty familiar with separations of concerns. I realized, however, that there’s no good solution for handling the ancillary, “can the current user do X” and “if the current user does X, then do Y”. I’ve addressed this issue a number of ways in the past, none of which was particularly elegant. For instance, I’ve used AOP for cross-cutting concerns, but I found it too hard to test and not quite explicit enough.

So, I realized that these “meta-domain” concerns really aren’t concerns for the domain objects themselves. For instance, the User entity doesn’t care if a link is displayed on the user profile page based on security. In this case we could have a security manager that deals with this, but what if this decision isn’t just based on security, but also user reputation, user history and user profile settings? Do I suddenly need to couple my view-model to all of these managers/services? Do I have to have all of these redundant dependencies for every page? What if I forget one? How do I easily test what will happen?

These are all questions that I felt lacked a good answer. As a response, I created a library that is capable of registering “events” and “event” handlers. These aren’t traditional events, but more like “domain events” in that their scope is the entire domain.

Now, sure, there are other ways of accomplishing this, but my particular set of requirements calls for multiple actions to take place when certain events are fired. I also need to know if I can execute a given event, which makes them more than just fire-and-forget.

I had several requirements for my design: it had to be easy to use and understand, it had to play well with an IoC container, it had to be testable and it had to be as type-safe as possible. What I came up with seems to have accomplished all of these, though I haven’t put it to use just yet.

Here’s a snippet from one of the tests that illustrates one of the use cases. The AddNew method is defined on the IMockEventHandler interface. This returns a ValidationResult indicating whether or not the AddNew event can be called in the given MockContext based on all IMockEventHandler objects.

   1:  var result = eventManager.For<IMockEventHandler>()
   2:                           .In( new MockContext() )
   3:                           .Where( x => x.GetType().FullName.Contains( "Mock" ) )
   4:                           .Where( x => x.EventSourceType == null )
   5:                           .Validate( x => x.AddNew( "s" ) );

Typically the Where criteria won’t exist, they’re just there for flexibility.

So from the code snippet you can see some of the opportunities it presents. Say I have the following:
   1:  public interface IOrder {
   2:      void ShipOrder( string orderNumber );
   3:  }

   1:  public interface IOrderEventHandler {
   2:      HandlerResult ShipOrder( string orderNumber );
   3:  }

I expect to call something like this:
   1:  var result = eventManager.For<IOrderEventHandler>()
   2:                           .In( currentContext )
   3:                           .TryExecute( x => x.ShipOrder( orderNumber ), exec => { 
   4:                              currentOrder.ShipOrder( orderNumber );
   5:                            });

This will execute the given code if, and only if, the HandlerResult of the ShipOrder event handler returns HandlerResult.Success. The variable, result, will hold the HandlerResult so I can take action based on the result (throw an exception, rollback a transaction, etc.)

Now, from the UI perspective, we can have a special UI event handler:
   1:  public interface IOrderUIEventHandler {
   2:      HandlerResult DisplayDelete();
   3:  }

In the backing model, I can lazy load the permissions:
   1:  public CanDisplayDelete { 
   2:     get {
   3:        if( _displayDelete == null ) {
   4:           _displayDelete = false;
   5:           var result = eventManager.For<IOrderUIEventHandler>()
   6:                                    .In( currentContext )
   7:                                    .Validate( x => x.DisplayDelete() );
   8:           
   9:           if( result == HandlerResult.Success ) {
  10:              _displayDelete = true;
  11:           }
  12:        }
  13:        return _displayDelete;
  14:     }
  15:  }

The key, of course, is for the event manager to be extremely fast. I have tuned the hell out of it from a library persepective, but until I get it in a real application, I don’t have much to go on, but I expect the performance to be negligible. The only area where I need to be cautious is in the design of the event handlers themselves.

I also expect to fine-tune the syntax as it's a little "wordy" for me. I expect that I should be able to optimize the syntax down to a single-line evaluation:
   1:  eventManager.Validate( x => x.DisplayDelete() );

As I said, once I start using it, I'll be more apt to tune it.

EDIT: To be clear, this design is meant to address a particular problem: there may be a lot of entities interested in particular events and the decisions made may require input from multiple sources. This is not meant to delegate all functionality or business logic to event handlers.

Current Progress and The Epiphany

By Ryan at December 03, 2009 11:09
Filed Under: Development

It's been about two and a half weeks since my last post.  My project is coming along nicely; I've written a total of about 100 lines of code.  I've spent at least an hour, every day, working on some aspect of the site.  I guess my point is to illustrate how much planning needs to occur before you even write a single line of code.

I think of every application as the creation of building blocks for my next application.  Given this, I tend to labor over the details to ensure that I'm creating a solid framework and not just a one-off web site. While I'd agree with anyone that labeled me as neurotic or obsessive-compulsive, I think this kind of mentality bodes well for a programmer.  

I see programming as a craft, and, as such, I'm always looking for ways to better myself.  In an effort to "future-proof" my design, I'm forced to bring in new technologies and push myself out of my comfort zone (though I'm never really comfortable stagnating.)


One example of this is my epiphany with regards to test-driven development (TDD) (or behavior-driven development.)  See, I find myself stuck in traffic for at least an hour every night.  During this time, my radio is either off or playing a programming-related podcast.  As of late, I've listened to all my podcasts, so it's just me, the road, and my thoughts (and thousands of other motorists).

So, as I'm working through a particular aspect of the framework of my application in my head, it suddenly clicks: this is a perfect place for TDD.  You see, my mind kept wanting to traverse the tree of functionality all the way to the leaf nodes, but right now I only really need to set the stage/build the trunk for those nodes.  I was spending all of my brain power trying to decide how to flesh out the entire design, when I had a solid starting point that could/should be the focus right now.

When following the single-responsibility and open-closed principles TDD is just a perfect fit.  You can create your "trunk" and then mock out all of the nodes.  You create the nodes later and test them independently.  Suddenly, it all made sense.

You see, prior to now, my development workflow was never compatible with the TDD workflow.  I was always trying to make sure I had all my nodes in good order, then put the trunk together (or some amalgamation of that.)  While I've always fully embraced unit testing, I never bought into the test-first pattern.  But, it occurred to me, that it's not "test-first" its more "behavior-first" or "foundation-first."

This epiphany would have never struck me if I hadn't spent the last couple of weeks writing some test code and trying out Moq for the first time.  Once I started to see what these tools offered, I realized the development friction would actually be lessened by viewing the application's development with a TDD bent.  Then, with enough mind-numbing focus during my time in traffic, all of the puzzle pieces fell into place.

I have to say, this new perspective has added a new level of excitement to my development; it's empowering.

With that, I've settled on a tech stack:

  • MS Windows Server 2008 R2
  • MS SqlServer 2008
  • ASP.NET MVC 2 (beta for now)
  • nHibernate
  • Fluent nHibernate
  • Moq
  • MS Testing Framework (I like the integration with the IDE)
Now, my choice to use nHibernate is the topic of another discussion.  I have always been firmly against OR/Ms, but nHibernate impressed me so much that I decided I couldn't go wrong - as long as I take to the time to understand how nHibernate is expected to be used.  

I will say that I started down the LINQ path with great enthusiasm, but it really had all of the bad elements of an ORM and none of the good.  I can't live in a world with out POCOs, sorry.  I will not "work around" any library - they are supposed to help make things easier, not bleed their abstraction all over your code. *stepping off my soapbox*

Perhaps I'll go into my decision to use nHibernate after I get some hours behind the wheel so I can reflect on my decision.

 

 

Finding Balance

By Ryan at November 17, 2009 13:09
Filed Under: Development

I am moving forward with a side-project that I hope some demographic will find useful.  I think it's important to note that I'm not motivated by money; I'm not trying to turn any kind of profit.  This project is just for my own satisfaction and to keep my skills sharp and current.

I have to imagine that a lot of startups fail because they focus on the "becoming a millionaire/getting bought" goal instead of the, more important, goal of providing a useful user experience.  I think the greatest sense of accomplishment comes from people choosing to use your application.  It's a big "thanks, we needed this" kind of pat on the back.

I'd argue that even if nobody uses it, it's still worth building.  I expect to learn a lot about transforming an idea on paper into a fully-functional website that's fit for public consumption.  I've had plenty of experience with this in the past, but with other people's ideas, never my own.

As it stands, I'm about 3 weeks into the project and I haven't written a line of code.  Thus far, it's been about planning, use cases, wireframes, domain-name choice, etc.  These are the types of things you need to be willing to devote yourself to if you plan on being successful (not that I have a success yet.)  I find a lot of people want to either hit the ground running and throw together a prototype that evolves into something that people want to use, that inevitably needs to be rewritten at the cost of a great deal of pain in data migration and other assorted idiosyncrasies.  Then there's the other type who want to have a vast landscape of foundation code perfectly architected before producing anything that any normal human being could appreciate.  The key, as always, is finding a balance.

Outside of the balance of design and time-to-market, is the balance of friends, family, work and free time.  It's really had to stay committed to a side-project when you find yourself trying to keep all of the spinning plates from crashing to the ground.  Having a pregnant wife and a 4 year old daughter make this even more challenging.

Again, it's about finding balance and making sure that you're happy doing whatever it is you decided to to do.  If you're not happy to be working on a side-project, then that's called work, and you already do that 9-5.  To be successful, it really needs to be a hobby that others just happen to be able to enjoy.  And, if you make money along the way, good for you.  You can always exceed the expectation that nothing will come from your work, the same can't be said about wanting to become an "instant" millionaire.

 

 

About Me

thumbnail I'm a software developer currently employed by Pearson (PSO/PSON)* where I work with, my passion, .NET.  I have (close to) two decades of programming experience and I'm constantly trying to learn new languages, technologies, practices, etc.

 

Disclaimer

* Emerle.net is owned and operated by Ryan Emerle. The views expressed on this blog are his personal opinion and do not necessarily reflect the views of his employer or clients.

The same holds true for comments posted to Emerle.net; they are the comment posters' personal opinion and do not necessarily reflect Ryan Emerle's views or the views of Ryan's employer or clients.