MVCommand - Hello World

I recently decided to pull down MVCommand, which is a front controller implementation built on top of ASP.NET MVC that uses individual Command objects (or a set of Command objects) to process requests.  It was created by an old co-worker of mine, Erik Peterson.  You can read more about his implementation here and here.

I was interested in the project because I am of the opinion that a controller handling multiple actions seems like its doing too much and this solution addresses that issue.  It also seems like a shorter tail solution than picking up FubuMVC, while accomplishing many of the same things that FubuMVC is trying to accomplish.

I wanted to see how easy it was to use MVCommand and I was impressed at how simple it was to get it going.  The app I created is about as simple as simple gets... but I really just wanted to see how much effort was involved in getting something set up to use MVCommand.

Getting MVCommand:

The first thing I did was pull down MVCommand from Erik's github profile.  There is a version specific to ASP.NET MVC 2, so I grabbed that.  But there's also a version that plays with the 1st version of ASP.NET MVC, so if you're still using that version, you can download the MVCommand trunk and you'll be set.  Compile it into a DLL, or just open the solution and follow the steps below.

Creating A New Project:

The next thing I did was create a new ASP.NET MVC, since MVCommand still uses the same project structure - views are stored in the Views folder, Models in the Model folder, etc.  Add a new reference either to MVCommand project if it's in your solution, or the DLL you compiled from the previous step.

Setting Up Your Front Controller:

Instead of having many controllers that relate to different routes in your MVC application, MVCommand handles all requests through a single controller.  That controller determines which command, or set of commands, to run based on the route and executes them.

Setting up the controller used to handle this is a cinch.


   1:      [HandleError]
   2:      public class ConfigController : CommandController
   3:      {
   4:          public override Type[] CommandTypes
   5:          {
   6:              get
   7:              {
   8:                  var temp = typeof (ConfigController).Assembly.GetTypes().Where(x => typeof (ICommand).IsAssignableFrom(x) && !x.IsInterface).ToArray();
   9:                  return temp;
  10:              }
  11:          }
  12:   
  13:          public override Type BindableCommandType
  14:          {
  15:              get { throw new NotImplementedException(); }
  16:          }
  17:      }

CommandController is an abstract class provided by MVCommand.  It forces you to implement two properties - CommandTypes and BindableCommandType.  BindableCommandType is too advanced for this post, but the CommandTypes array is just a collection of all the commands in your project.  You can set this up however you like, whether it be manually adding them, using an IoC tool, or just running through the assembly types and returning all of the Command objects, as I did above.  In the end, you just want to have a list of all the Types in the assembly that are Commands.

Setting Up Your Front Controller Factory:

After you've created your front controller, you have to create a new controller factory - the class responsible for returning the correct controller.  Again, since ASP.NET MVC's controller factory will return whatever controller corresponds to the request, we need to override that behavior and have our default controller used for every request.

Again, this is pretty simple.


   1:  public class ConfigControllerFactory : CommandControllerFactory
   2:  {
   3:       public override IController CreateController(RequestContext requestContext, string controllerName)
   4:       {
   5:            var commandController = new ConfigController();
   6:            return commandController;
   7:       }
   8:  }


CommandControllerFactory is an abstract class in the MVCommand project. Create your own controller factory class and inherit CommandControllerFactory.  The overridden method implementation should just create your front controller.

In order to let ASP.NET MVC know that you want to use your custom controller factory instead of the default one, you have to add this line to your global.asax file in the Application_Start method:

   1:  ControllerBuilder.Current.SetControllerFactory(typeof(ConfigControllerFactory));

Setting up an IoC Container for Service Location:

MVCommand uses Microsoft Patterns and Practices Service Location to create instances of the commands it executes.  The MS Service Locator is an abstract service location tool which lets you use any IoC container and service locator in your code without hardcoding references to the IoC in your code.

I used StructureMap as my IoC container in my application.  I'm not going to get into setting up the StructureMap container because you find that elsewhere.  But once you have the container, you do have to tell Microsoft's Service Locator how to use it to, well, locate your services :)

To do that, I created a class called StructureMapServiceLocator that overrides ServiceLocatorImplBase.  This base class is what MS Service Locator uses to find your classes, so you basically have to fill in the overriden methods with calls to your StructureMap container that retrieves instances of the requested type.  It looks like this:

   1:      public class StructureMapServiceLocator : ServiceLocatorImplBase
   2:      {
   3:          private readonly IContainer _container;
   4:   
   5:          public StructureMapServiceLocator(IContainer container)
   6:          {
   7:              _container = container;
   8:          }
   9:   
  10:          public IContainer Container { get { return _container; } }
  11:   
  12:          protected override object DoGetInstance(Type serviceType, string key)
  13:          {
  14:              return  string.IsNullOrEmpty(key)
  15:                         ? _container.GetInstance(serviceType)
  16:                         : _container.GetInstance(serviceType, key);
  17:          }
  18:   
  19:          protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
  20:          {
  21:              return _container.GetAllInstances(serviceType).Cast<object>().AsEnumerable();
  22:          }
  23:   
  24:          public override TService GetInstance<TService>()
  25:          {
  26:              return _container.GetInstance<TService>();
  27:          }
  28:   
  29:          public override TService GetInstance<TService>(string key)
  30:          {
  31:              return _container.GetInstance<TService>(key);
  32:          }
  33:   
  34:          public override IEnumerable<TService> GetAllInstances<TService>()
  35:          {
  36:              return _container.GetAllInstances<TService>();
  37:          }
  38:      }

And just like with your overriden controller factory, you have to tell the MS Service Locator to use your StructureMap service locator in the global.asax file:

   1:  var serviceLocator = new StructureMapServiceLocator(container);
   2:  ServiceLocator.SetLocatorProvider(() => serviceLocator);

Creating Your First Command:

By default, MVCommand runs all of the commands in a namespace that relates to your route.  This behavior can be overriden by providing a dictionary that maps commands to a route, but that's beyond the scope of this post.

The main route is below:

   1:  routes.MapRoute(
   2:                  "Default", // Route name
   3:                  "{context}/{event}/{id}", // URL with parameters
   4:                  new {controller = "Command", action = "DefaultAction", id = ""}             // Parameter defaults
   5:                  );

(note that the second token of the url has been renamed from 'action' to 'event' - you will need to rename that token as well)

In the case of this route, MVCommand will run all the commands where the namespace ends with 'Context.Event'.  So for example, in my example, I called this url: http://localhost:1162/home/helloworld and the command whose namespace ends with *whatever*.Home.HelloWorld.  If there's multiple commands in that namespace, it'll run them all.

For my insanely simple example, I created a new Command simply called Command2 with hard-coded return value of my name and age.

   1:  namespace MVCommand.HelloWorld.Commands.Home.HelloWorld
   2:  {
   3:      public class Command2 : ICommand
   4:      {
   5:          public object Execute()
   6:          {
   7:              return new HelloWorldModel {Age = 31, Person = "Dan" };
   8:          }
   9:      }
  10:  }

(note that the namespace ends with Home.HelloWorld')

This class implements the ICommand interface that is part of the MVCommand framework.  This is insanely simple, but you could do any processing necessary in this class, whether it be hitting a database or whatever the case may be.

The returned object is set in the ViewData dictionary.

Using The Returned Model In The View:

The last piece of the puzzle is getting the data that was returned from the Command and using it in your View.  I created a HelloWorld.aspx view and made it inherit from an MVCommand helper class ViewBasePage<T> where T is the model.  This just creates a property named Model with the object that is returned from your command.

   1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MVCommand.Views.ViewBasePage<MVCommand.HelloWorld.Models.HelloWorldModel>" %>
   2:   
   3:  <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
   4:      HelloWorld
   5:  </asp:Content>
   6:   
   7:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   8:   
   9:      <h2>HelloWorld</h2>
  10:   
  11:      <p>
  12:          Hello, <%: Model.Person%>.<br />
  13:          You are <%: Model.Age %> years old.<br />    
  14:      </p>
  15:      
  16:   
  17:  </asp:Content>


Wrapping It Up:

That's about it.  As you can see, it's pretty easy to get up and running with MVCommand.  Just set up a front controller and new controller factory to create instances of that controller.  Then, set up your IoC container and service location.  Then, start creating commands and views and go to town!

Hopefully that is enough to get you started with MVCommand. Download it and start playing around.

I hope to do more posts in the future about MVCommand.  I know there are other things to go over, such as using the Command dictionary instead of namespacing to determine which commands to run for a request.  And how to get and use form data and querystring values in your Commands.  Look for those posts at a later date.

Til then... don't hesitate to leave comments with questions, or if you noticed I royally screwed something up.   It wouldn't surprise me if I missed something, mis-typed something or otherwise had some sort of brain fart while writing this up.  So thanks in advance for the feedback.

Book Review: Code Complete

I've been trying to be constantly reading a book for about the past year and a half now.  And in addition, I started a dev book group where I work, where we pick a book and read it a certain amount each week and then meet for an hour to discuss that section - whether it be making decisions on whether this is something we want to do as a department, or how we can apply the topic to our projects, etc.

The latest book we just finished was Code Complete.  I feel like I was long overdue reading this one as I've heard a few times in the past that this was one of those required reading books on programming.  Actually, on more than one occasion, I've been asking during a job interview what books I've read and liked the most and after giving my list, the interviewer has said "all great books... the only one I'd add is Code Complete".  So I was pretty excited to finally read through this one.

I've broken up my review into a section of positives, negatives and then a summary.  I find that helpful because sometimes reviews get too verbose and will be filled with double speak such as "the paragraph on *whatever* was great, except ..." .  So I'm going to try to avoid that and just talk about what I liked, what I didn't.

POSITIVE:

I can't stress enough how much good information this book is packed with.  There's a ton of information to digest about a wide range of topics - from how to organize and comment your code to team dynamics, estimation tipis and even programmer human characteristics - this book does a great job of taking a good 1000ft.view of a lot of aspects of software development and also gives a lot of "read this next" resources for topics that you might want to delve deeper into.  McConnell (the author) does a pretty good of using case studies to back up his points.  And while some of the information is a little out of date in the book (happens often in these types of books... the software industry just moves too fast), a lot of the information is plenty applicable no matter what language you develop in, type of development you do, etc.

NEGATIVE:

First off - this book is long... REALLY long.  We actually skipped a few chapters early on during the book group and it still felt like the book would never end.  That's a bit nitpicky though as the Lord Of The Rings trilogy is long as hell, but it's a great read   I think the biggest disappointment to me was that a lot of the information put forth was stuff that you learn your first few years in professional software development and it just becomes common sense.  More often than not, I found myself (and I believe some of the others in the group) saying "these are great points - but I already knew this" or "these are great points - but this is common sense".  And then, of course, the problem with a 1000ft. view that I mentioned earlier is that if you find yourself interested in one of the ideas that he presents, you would love to learn more, but it's just not there.  That's not a problem with this book in particular... but I guess my preference is with more directed learning books.  Books that take a smaller array of topics and really delve into them in greater detail.

SUMMARY:

I'm not sure I'd ever read this one again.  Like I said, it just contains too much information that I already knew.. and I don't even pretend to be a software guru by any stretch of the imagination.

However, this book is far from worthless.  I think this book should be required reading in a college course on programming, or the first book a young developer reads before ever working on their first project.  This is type of stuff that you can either learn organically by being in the industry for a while and seeing it all come to life in both good and bad ways in your projects, or you can just read this book and enter the industry with this knowledge in hand.  It'll put you on level playing ground with people who take the long path.

I also think this is one of those books that would be a checkmark in the thumbs up column if a prospective new employee had mentioned reading it.  It would be a sign that the developer was equipped with knowledge of good programming practices and ideas (of course - whether they apply them is a different story, but you'd rarely get that out of an interview anyway).

Bottom line... new developers should be forced to read this book.  Older developers probably already know most of what it contains.  But it was nice to get some of this knowledge reiterated (much like how I re-read The Pragmatic Programmer every year or two just to get rejuvenated) and also have the case studies to back up the information with statistics.  It's one thing to do something a certain way because it works for you, and even better when it turns out that it works for the entire industry :)

Linq To Sql Web App Lifetime Management - Take 1

I was asked to help another project team at work to come up with a good way to manage Linq To Sql data contexts on their project.  Their current situation is that they open and use a datacontext wherever needed, but often run into problems where they're trying to save entities with expired contexts or opening too many connections to the database to grab the same record multiple times.  They're not fully utilizing the datacontext's features such as the Identity Map or Unit Of Work.

I haven't had much experience with Linq prior to being asked to help, but I knew the basics.  For the rest, I decided to do a bunch of blog reading on the subject to help out with my implementation.  My criteria for a good solution was the following:

Ease Of Use / Clean Syntax
I figured this one was self-explanatory.  First, I didn't want to get into a huge architecture if I didn't have to and furthermore, I figured that if it wasn't easy to implement and use, no one would want to do the work to implement it.

Unit Testable:
I like to do unit testing and wanted to be able to write tests that didn't actually hit the database.  I wanted to be able to write mock versions of the implementation instead for tests so I could control them during my tests.

Unit Of Work/Lifetime Management:
This was to solve the problem that they came to with me in the first place.  Microsoft, as well as common sense, indicate that you should really only have one datacontext around per request for web applications.  This seems to make sense since the datacontext already is built like a unit of work (it records all changes to entities, inserts and deletes and waits until SubmitChanges() to actually persist them to the database).

Validation Of Entities:
Another concern the team had was how to validate entities before saving them.  Their current implementation was to create partial classes for each entity and create custom attributes to perform validation.  I did not include my solution as part of the prototype I came up, but I actually suggested they pull the validation out into separate Specification objects - this way, they can keep the entity classes to solely what Microsoft provides them and the Specification objects can be reused, as well as making more explicit the business rules around a valid entity - something I learned from reading Eric Evans' DDD book.

What I came up with was pretty simple. I mostly just took a lot of what other bloggers were suggesting and stripped out a lot of stuff I didn't think was necessary at the moment.  Not that I felt others were over-complicating the matter, but they were showing examples of things they needed for their projects which may not necessarily be needed in this one.  And taking the YAGNI approach, I felt like I should keep it as simple as possible, knowing that I could add in the desired features later if necessary.

So, finally, here is the design I came up with...

   1:  public class UnitOfWork : IUnitOfWork
   2:  {
   3:       private readonly EntityClassesDataContext context;
   4:   
   5:       public UnitOfWork()
   6:       {
   7:            context = new EntityClassesDataContext();
   8:       }
   9:   
  10:       public Table<T> GetTable<T>() where T : class
  11:       {
  12:            return context.GetTable<T>();
  13:       }
  14:   
  15:       public void SubmitChanges()
  16:       {
  17:            context.SubmitChanges();
  18:       }
  19:  }

This UnitOfWork class just wraps the DataContext and implements an IUnitOfWork interface which can then be used in the rest of the system, so that we can mock it during tests.  It just provides the ability to get a table (which can then be queried, or inserted to/deleted from) and run SubmitChanges().  I considered having SubmitChanges() be run automatically at the end of each request, but I felt like that was dangerous as you may not want all changes submitted - I want to make it more explicit and require programmers to call that function when they wanted their changes persisted.

   1:  public class UnitOfWorkFactory
   2:  {
   3:       private const string HTTP_CONTEXT_KEY = "SFT.UnitOfWork.Factory.Context.Key";
   4:   
   5:       public static IUnitOfWork GetUnitOfWork()
   6:       {
   7:            if (HttpContext.Current != null)
   8:            {
   9:                 if (!HttpContext.Current.Items.Contains(HTTP_CONTEXT_KEY))
  10:                 {
  11:                      HttpContext.Current.Items.Add(HTTP_CONTEXT_KEY, Activator.CreateInstance(typeof(UnitOfWork)));
  12:                 }
  13:                 return (IUnitOfWork)HttpContext.Current.Items[HTTP_CONTEXT_KEY];
  14:            }
  15:            throw new Exception("No current HttpContext found.");
  16:       }
  17:  }

This factory is used to get the current UnitOfWork which is stored in HttpContext's Items collection.  It's pretty simple.  If you ask for the current UnitOfWork and it hasn't been created for the current request yet, it creates it and puts into the Items collection.  Then, it returns it.  Otherwise, if it already exists, it returns the one that's in the Item's collection already.  From what I read, this should guarantee that you always use the single, per-request DataContext which means you take advantage of the Identity Map (instead of loading the same entity from the db multiple times) and have all your changes in a request tracked.

   1:  public DefaultPresenter(IDefaultView view) : this(view, UnitOfWorkFactory.GetUnitOfWork(), new DebtorRepository())
   2:  {
   3:  }
   4:   
   5:  public DefaultPresenter(IDefaultView view, IUnitOfWork unitOfWork, IDebtorRepository repository)
   6:  {
   7:       this.view = view;
   8:       this.unitOfWork = unitOfWork;
   9:       this.repository = repository;
  10:  }

And this is how I used the factory in my prototype.  Dependency injection allows for unit testing because in the unit tests, I can use the 2nd constructor and pass in a mock of the IUnitOfWork, but in production, I can use the above constructor which calls on the UnitOfWork factory to get the concrete UnitOfWork class that wraps the Linq datacontext.

I know that IoC containers would get me down to one constructor, but for the purposes of the prototype, I didn't want to do the extra work.  However, itt's probably something I would suggest if this is used in an actual project.

The last thing which I won't post is that I use Repositories for getting data.  I do that cut down on the duplication of queries across the codebase and also to abstract out the Table classes that come with the datacontext since they're not easily mocked for testing.  I read about ways that you could mock them out and provide data from an in-memory data store during testing, but when I'm testing the presenters, I don't want to have to worry about all the overhead of setting that up in my test, so I'd rather just put it behind an IRepository interface.  When it comes time to test the Repository classes, I can focus on how to write the tables with an in-memory data collection.

And that's it.  I would love some feedback as this is my first time taking up something like this.  Is there any obvious, or not-so-obvious flaw in this design that I'm missing?  Are there any ways it could be improved?  Your comments would be greatly appreciated.

Delegates => Lambdas, Pt. 4: .NET Helpers (The Final Episode)

This is a series I created on my company's internal intranet for a few young developers.  However, I thought it might be useful to anyone, so I wanted to make it public.


Ok - this is the last part of my series about delegates and lambdas.  Finally.  But I wanted to mention a few helpers that .NET provides to make it easier to use delegates and lambdas in your code.

If you remember back to the first post of the series, I mentioned that to declare a delegate to be used as a parameter or anything else, you had to do this:

   1:  delegate bool Filter(TeamDTO team);

Well - .NET makes it slightly less tedious with the use of three framework classes, namely Action<T>, Predicate<T> and Func<T>. Let's look at an example of each.

Action<T>:

This class encapsulates a delegate that takes one parameter and does not return a value. Meaning, it is a contract that specifies one input parameter, the type of which is specified as a generic, and a void return type. This is useful for a variety of scenarios, but let me show you just one.

If you've noticed, when you create a List<T>, one of the methods on that list that is built-in for .NET is ForEach(Action action). Using that, you can build for-each loops using delegates/lambdas. See below:

   1:  private readonly List<TeamDTO> allTeams = new List<TeamDTO>
   2:                                            {
   3:                                                new TeamDTO("Flyers", "East"),
   4:                                                new TeamDTO("Blackhawks", "West"),
   5:                                                new TeamDTO("Blue Jackets", "West"),
   6:                                                new TeamDTO("Capitals", "East")
   7:                                            };
   8:   
   9:  Action<TeamDTO> printTeam = x => Response.Write(x.TeamName);
  10:  allTeams.ForEach(printTeam);

Or, you can just inline it all with a lambda expression like this:

   1:  allTeams.ForEach(x => Response.Write(x.TeamName));

By the way, Action<T> also comes in a few additional flavors, those being Action<T1, T2>, Action<T1, T2, T3> and Action<T1, T2, T3, T4>.  As you can probably guess, this just allows you to use them to define up to 4 input parameter types - the return value in all situations is still void.

Predicate<T>:

This is another .NET class representing another standard delegate situation.  This one takes one parameter and returns a boolean value.  This is actually PERFECT for our filter situation.  Instead of having to create a delegate like the one at the top of this post, we can use this in it's place, since it does the same thing (takes in one argument, it's generic, but we can specify we want it to be of type TeamDTO and returns a boolean value).  So let's see it in action:

   1:  private static IList<TeamDTO> SelectTeamsByFilter(IEnumerable<TeamDTO> teams, Predicate<TeamDTO> filter)
   2:  {
   3:       var filteredTeams = new List<TeamDTO>();
   4:       foreach (TeamDTO team in teams)
   5:       {
   6:            if (filter(team))
   7:            {
   8:                 filteredTeams.Add(team);
   9:            }
  10:       }
  11:   
  12:       return filteredTeams;
  13:  }

Compare this piece of code to the one in the first post of the series and you see that I just replaced the delegate object I created with the Predicate - why re-invent what .NET already has?

Func<T>:

This one actually comes in a bunch of different flavors and is arguably the most powerful.  And actually, if you look at the MSDN documentation, Func<T> is actually not even the correct form of the delegate - but this is how it's used in conversation.  The actual name is Func<TResult>.  And hopefully by now you're catching on and can guess what that means.  Func<TResult> allows you to specify a delegate with no input parameters and a return value of TResult.  Like Action<T>, Func<TResult> has variations that allow you to specify up to 4 input parameters, in addition to the return type.  So you have Func<TResult>, Func<T, TResult>, Func<T1, T2, TResult>, Func<T1, T2, T3, TResult> and Func<T1, T2, T3, T4, TResult>.   Keep in mind if you use these that the last value will be the return value in any situation.

As a really simple example, imagine I wanted a function that printed all of the team names in a list.  Here it is:

   1:  Func<TeamDTO, string> printTeamName = x => x.TeamName;
   2:  foreach (TeamDTO team in allTeams)
   3:  {
   4:       printTeamName(team);
   5:  }

The first line defines a Func<T, TResult> that accepts a TeamDTO object and returns a string.  Then the lambda shows that x is the input parameter and on the other side of the => is the return statement x.TeamName.  The other part is just a for-loop which invokes the delegate.

So that's it for my series on delegates and lambda expressions.  But it won't be the last time you hear about them.  A lot of the examples in these posts were scholastic in nature, but they probably left you thinking that aside from being neat, where was the benefit?  Where all of these helpers, and delegates in general, become really powerful is when you combine them with other features of .NET.  So expect to see more of these in future posts.  But hopefully these gave you a few ideas about where you could benefit from the use of delegates, or at least help your understanding about what exactly is going on when you type code into your IDE of choice.

Any questions/comments/feedback? Feel free to comment any of the posts.

Delegates => Lambdas, Pt. 3: Lambda Expressions

This is a series I created on my company's internal intranet for a few young developers.  However, I thought it might be useful to anyone, so I wanted to make it public.


In my last post, I explained how to use anonymous methods, or inline delegates, to remove a bunch of unnecessary code from your class.  This post is going to explain how lambda expressions are really just a syntatic helper to aid in the removal of more 'extra' code and to make anonymous methods a little more readable.

And that's really what lambda expressions are - cleaner ways to write anonymous methods/inline delegates.

Let's look at our example from last time.  To handle two different filtering scenarios, we had this:

   1:  IList<TeamDTO> allTeams = new List<TeamDTO>
   2:                                            {
   3:                                                new TeamDTO("Flyers", "East"),
   4:                                                new TeamDTO("Blackhawks", "West"),
   5:                                                new TeamDTO("Blue Jackets", "West"),
   6:                                                new TeamDTO("Capitals", "East")
   7:                                            };
   8:   
   9:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, delegate(TeamDTO team) { return team.Conference == "East"; });
  10:   
  11:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, delegate(TeamDTO team) { return team.TeamName.StartsWith("B"); });

This isn't bad, but you still have to use the delegate keyword and declare a function, complete with parentheses and curly braces inline. That can get hard to match up pretty quickly. So here are these same lines using lambda expressions:

   1:  IList<TeamDTO> allTeams = new List<TeamDTO>
   2:                                            {
   3:                                                new TeamDTO("Flyers", "East"),
   4:                                                new TeamDTO("Blackhawks", "West"),
   5:                                                new TeamDTO("Blue Jackets", "West"),
   6:                                                new TeamDTO("Capitals", "East")
   7:                                            };
   8:   
   9:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, team => team.Conference == "East");
  10:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, team => team.TeamName.StartsWith("B"));

As I said earlier, this is really just a cleaner way to write the delegate. The left side of the lambda expression declares the inputs. You will often see these as x. That's just a convention. I chose team because I think it's more descriptive. The right side of the lambda expression holds the statement block, or function body. Pretty simple - lambda expressions are delegates. Nothing to be afraid of.

A few notes about lambda expressions before this post is over.

When a lambda expression's body contains only one line of code, you don't need a return - the result of that line of code is assumed to be the return value. So above, the line evaluates to a boolean, so that is considered the return value. That said - you CAN write lambda expressions containing multiple lines of code, but you then have to include the return keyword and wrap your expression body in curly braces. Here's a quick example:

   1:  return SelectTeamsByFilter(allTeams, team => {
   2:                                                           int count = team.TeamName.Length;
   3:                                                           return count == 10;
   4:                                                       });

Not super realistic, it filters by teams whose name is ten characters long.

Also - lambda expressions can take zero parameters. In that case, you use an empty set of parentheses on the left side like this:

   1:  () => SomeMethod()

And they can also take multiple inputs. For example, if you wanted to compare two teams:

   1:  (team1, team2) => team1.TeamName == team2.TeamName

So there you go. Lambda expressions are nothing more than clean ways to write delegates. And delegates are a really powerful and useful feature to allow you to separate a method from its implementation.

There's going to be one more post in this series. It's a bit of a tangent rather than a continuation, but I wanted to introduce a few classes that .NET provides to help facilitate the use of delegates in your code. So look for that in the next couple of days.

Delegates => Lambdas, Pt. 2: Anonymous Methods == Inline Delegates

This is a series I created on my company's internal intranet for a few young developers.  However, I thought it might be useful to anyone, so I wanted to make it public.


In my last post, I introduced delegates and briefly showed you how to use them, along with explaining a few of the benefits.  At the same time, there were some drawbacks as well that I probably didn't mention, but may have hinted at.

I suggest you look at that post again to refresh your memory about how delegates are declared and used.  The first thing you might notice that is a little less than ideal about the last example is that you still need to declare a function for each of your filters - IsEasternConferenceTeam, TeamNameStartsWithB, etc.  At that point, why don't you just call them directly in your code instead of passing them into another function?

This is where anonymous methods come in.  Anonymous methods allow you to declare methods inline using the delegate keyword.  This cuts down on unnecessary private functions bulking up your code.

Let's take a look at an example.  As a quick refresher, in the last post, we had this for filtering:

   1:  private static bool IsEasternConferenceTeam(TeamDTO team)
   2:  {
   3:       return team.Conference == "East";
   4:  }
   5:   
   6:  private static bool TeamNameStartsWithB(TeamDTO team)
   7:  {
   8:       return team.TeamName.StartsWith("B");
   9:  }
  10:   
  11:  IList<TeamDTO> allTeams = new List<TeamDTO>
  12:                                            {
  13:                                                new TeamDTO("Flyers", "East"),
  14:                                                new TeamDTO("Blackhawks", "West"),
  15:                                                new TeamDTO("Blue Jackets", "West"),
  16:                                                new TeamDTO("Capitals", "East")
  17:                                            };
  18:   
  19:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, IsEasternConferenceTeam); // will return a list wtih Flyers and Capitals
  20:   
  21:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, TeamNameStartsWithB); // will return a list with Blackhawks and Blue Jackets

Those two functions at the top are really just different filters. Seems a little bulky. So with anonymous methods we can do this instead:

   1:  IList<TeamDTO> allTeams = new List<TeamDTO>
   2:                                            {
   3:                                                new TeamDTO("Flyers", "East"),
   4:                                                new TeamDTO("Blackhawks", "West"),
   5:                                                new TeamDTO("Blue Jackets", "West"),
   6:                                                new TeamDTO("Capitals", "East")
   7:                                            };
   8:   
   9:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, delegate(TeamDTO team) { return team.Conference == "East"; });
  10:   
  11:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, delegate(TeamDTO team) { return team.TeamName.StartsWith("B"); });

Now - we can get rid of those functions.  And we can write whatever types of filters we want inline in code wherever we need to filter things.

Again - notice that as long as long as the contract is fulfilled for this delegate (TeamDTO input, boolean output), there will be no complaints from the compiler.  And just like I mentioned before, these functions can actually do as much as work as you'd like them to - they don't need to be just one line.  Of course, when you get into writing them inline like this, big functions that do a lot of heavy lifting quickly become hard to format.  But for quick one-liners, I think this is awesome.  And imagine, like I mentioned in my last post, how easy it is now for consumers of this code to write new filters?

The next step is from anonymous methods to lambdas.

Delegates => Lambdas, Pt. 1: What's A Delegate?

This is a series I created on my company's internal intranet for a few young developers.  However, I thought it might be useful to anyone, so I wanted to make it public.


I'm going to take the next few blog posts to explain lambda expressions (and delegates) - something we use every day as LINQ users.  But it's important to know what they are and why they're useful, beyond just knowing that the way to get a DB record matching a certain Id is by writing x => x.Id == 42.  Hopefully these posts will start to get some thoughts going about other ways that lambdas could be used.

To understand lambdas, it's important to understand what came before them  - namely, delegates.  So this first post is going to explain what delegates are.  But first a quick history lesson - when I say "what came before them", I'm talking about the history of .NET only.  Delegates and lambdas have been around for a long time.  They've been in the computer realm since LISP, Python has them and Ruby actually relies heavily on them.  And function pointers have been around forever as well.  So .NET is late to the party.

There are a few ways to think about delegates.  A delegate is a pointer to a function, meaning you can create an instance of an object that is really a function and you can invoke that function through the instance.  Another way to think about them, and the way that seems to resonate with me the most, is that a delegate is similar to an interface, but pertaining to functions - it defines a template or a contract.  You create a delegate and it says "any function that conforms to my standard will take in these inputs and produce this type of return value".  Let's look at an example.

 

   1:  delegate bool Filter(TeamDTO team);

There's your delegate definition.  It looks like any other function definition, except for the delegate keyword.  What this delegate is doing is defining a template for any function that has a boolean return value and takes a TeamDTO object as a parameter.  Any function that does those two things will fulfill this template.  The name Filter is useful to explain what type of functions this should be applied to, but it could be named anything because it's an type definition.

So what's so useful about this?  Well - you can imagine that at different times, you might want to filter a list based on different criteria.  In my example, I'm going with hockey teams (as usual).  Maybe at one point in the application, I want to get only the teams in the Eastern Conference.  Another time, I might want to only get the teams whose name starts with the letter B.  The ideas are endless.  Without delegates, this is achievable - you just have to create a bunch of different functions called FilterByWhatever and implement the same thing over and over again.  Furthermore, what if I release this code to the public as a class library and a user wants to do a search that I haven't written a function for?  With the delegate in place, we can write a function like this:

 
   1:  public static IList<TeamDTO> SelectTeamsByFilter(IEnumerable<TeamDTO> teams, Filter filter)
   2:  {
   3:       var filteredTeams = new List<TeamDTO>();
   4:       foreach(TeamDTO team in teams)
   5:       {
   6:            if(filter(team))
   7:            {
   8:                 filteredTeams.Add(team);
   9:            }
  10:       }
  11:   
  12:       return filteredTeams;
  13:  }

Notice that the 2nd parameter of that function is an instance of our delegate.  With that in place, we can pass in a function that satisfies the delegate definition and invoke it within the SelectTeamsByFilter function.  You can see that I've done just that in the IF statement.

So for the two examples above, what if I wanted to be able to filter a list of teams by their conference?  Or only teams that start with the letter B?  You can just create functions that satisfy the contract of the delegate (accept a TeamDTO as a parameter and return a boolean).  And then pass them into the SelectTeamsByFilter function like so:

   1:  private static bool IsEasternConferenceTeam(TeamDTO team)
   2:  {
   3:       return team.Conference == "East";
   4:  }
   5:   
   6:  private static bool TeamNameStartsWithB(TeamDTO team)
   7:  {
   8:       return team.TeamName.StartsWith("B");
   9:  }
  10:   
  11:  IList<TeamDTO> allTeams = new List<TeamDTO>
  12:                                            {
  13:                                                new TeamDTO("Flyers", "East"),
  14:                                                new TeamDTO("Blackhawks", "West"),
  15:                                                new TeamDTO("Blue Jackets", "West"),
  16:                                                new TeamDTO("Capitals", "East")
  17:                                            };
  18:   
  19:  IList<TeamDTO> easternTeams = SelectTeamsByFilter(allTeams, IsEasternConferenceTeam); // will return a list wtih Flyers and Capitals
  20:   
  21:  IList<TeamDTO> teamsThatStartWithLetterB = SelectTeamsByFilter(allTeams, TeamNameStartsWithB); // will return a list with Blackhawks and Blue Jackets

Yes.  I just passed functions into another function to be run.  Pretty sweet.  And to go back to my other example where someone who is using my compiled library wants to do a search that I haven't written code for - as long as they call this function with a method that conforms to the contract of the delegate (once more - takes a TeamDTO and returns a boolean value), it'll run.  And these don't have to be as simple as the examples above.  They can do as much work inside the functions as you'd like - they just have to stick to the input and output contract of the delegate.

So hopefully you are beginning to see how delegates are useful features and maybe some nice ways to use them in your code to cut down on the amount of repeated code or make your code easier to extend or whatever else.  In the next part of the series, I'll get into some ways to improve upon this code to make it a little more understandable and a little less cumbersome and move closer to how lambdas were born in the .NET framework.

In the meantime, feel free to leave any questions/comments/thoughts.

Fixing Broken Windows

I started re-reading The Pragmatic Programmer over the weekend and one of the early chapters mentioned the broken window theory.

Google search the term, but the quick version is basically that studies were done by experts in crime and urban decay that something as small as one broken window in a building, left unfixed, will make people occupying a neighborhood feel as though no one cares about the neighborhood and things will go downhill from there.  One study was done where a car was left in the same spot for weeks and nothing happpened to it.  Then one day, the person conducting the study smashed the window and by the next day, the entire car had been stripped.

Ok, so how does this apply to software?  Well - when a codebase contains a lot of un-clean code and generally looks as though it's been abandoned, the developers working on it are often more likely to use it as an excuse to do things the quick and dirty way.  Why should I worry about making my code maintainable, when this codebase has duplication all over the place and functions/pages that haven't worked correctly in months.

On the flipside, if a codebase is nice, clean and easy to work with... developers will be LESS likely to go for the quick and dirty change because they won't want to be responsible for being the one to start the downfall.

The reason this hit me so hard this weekend while reading was on account of something that occurred during work on Friday.  I came across an old file in my application that had a few validation functions in it.  The only problem was, the entire body of the functions were commented out and all that was left was a "return true".

Now, this is hardly the biggest problem I've come across in this codebase since I started my job, but it was just another case where I could've seen it, felt hopeless and moved on.  But what I decided to go was... fix them.  Remove the functions that have been commented out for years and then clean up the code was calling on them only to set their values to true.

And that's basically what the chapter in The Pragmatic Programmer suggests.  Fix Broken Windows.  Because just like seeing decay will sway a fellow developer to continue the decay, seeing repair will push fellow developers to continue that effort towards a cleaner codebase.

Book Review: Working Effectively With Legacy Code

This is a very important book on a topic that hasn't been covered thoroughly prior to its release.  For all the text out there about Agile software development, XP programming practices, unit testing, etc., there seems to be an unwritten understanding that you're dealing with a fresh, new project space.  And for me, specifically, that was the case for the past few years.  As a independent contractor, I was often brought in to projects at their beginning to see them through to completion.  But having recently re-joined the full-time employee ranks to maintain and improve an existing product, I now understand how overwhelming it can be to look at a giant codebase and think to yourself "ok, where do I even start?"

That's where this book comes in.

First, it's definition of legacy code is simple.  Any piece of code that is not under test.  I think that's a good starting point.  Too many people think of legacy code as having to have been written years ago and allowed to degrade.  Not true.  By the author's definition, legacy code is still being written by developers every single day.

So obviously, the point of the book is refactoring existing code to make it testable.  And what's provided are chapters describing different situations, such as "I'm Changing The Same Code All Over The Place" and "I Can't Run This Method In A Test Harness".  In that way, the book can act like a reference material for programmers working in legacy code.  If you see yourself running up against one of these problems, simply flip to the chapter list, find your problem and read the chapter about it.  Most chapters are pretty short and get right to the point.

After the situational chapters, the book ends with a list of refactoring techniques, written step-by-step, that you can apply to get pieces of your code under test.  It's very much like Fowler's Refactoring book, except with some new techniques explicitly for getting your code into a test harness.

I had heard that this book was useful for years now, but never bothered to pick it up.  But now facing a codebase that seems unwieldy, I think this may be one of the most important books I've ever read.  We don't all code in green pastures, but this book certainly helps you not lose focus of the techniques you hold dear (unit testing, separation of concerns, D-R-Y, single responsibility, etc.) when you encounter a situation that seems overwhelming.

http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052

Code Contracts In .Net 4.0 - My second thoughts

Well - I just watched this screencast which served as my intro to Code Contracts and now I'm not quite as siked on them:

http://www.dimecasts.net/Casts/CastFeedDetails/118

They're still pretty useful and I think the syntax beats having all the IF statements checking for null and other expectations as far as readability goes, but I really thought they would throw a full fledged compiler error in the case that a contract was violated, rather than just a warning.  I mean, it's better than nothing, but a lot of programmers ignore warnings (unless you've subscribed to the pragmatic programmers philosophy of treating warnings as errors).

I also don't particularly like the code you have to write to handle the contract check (it's in the SetUp of the test harness in the video).  It just seems like an added step, where you could just assert that the exception was thrown in the old piece of code, without having to write in that extra stuff in SetUp.

I'm still looking forward to hearing more about this as VS2010 and .NET 4.0 come closer to being released.  For me, the jury is still out on this one.

But the video did show me one cool thing, completely unrelated to code contracts.  In his test, he used NUnit syntax helpers which I thought made the test code more readable.  I'm going to have to look into those and once again renew my ongoing battle between MbUnit and NUnit.