March 2008 Blog Posts
UPDATE: This was an April Fool’s joke. I actually stated this in the bottom of the original post, but in a very small font, which some people noticed. :)
I’m totally done with blogging. Hanging my blogging hat and never looking back. I started blogging on http://haack.org/ way back when around 1998. I tried to include a Wayback Machine archive link, but some domain squatters put a robots.txt file onto haack.org. Bummer. Shoulda held onto that domain.
If you follow my twitter stream, you've probably noticed I've been lamenting about blogging lately. A lot of bloggers, myself included, put an unhealthy amount of pressure on themselves to continue producing content. It becomes a bit of a self imposed boilerroom.
When I read about Dare stopping his blog, unlike many people who felt sad, I felt envious. Think of all the free time he must’ve freed up. I can totally understand the reasons. He’s getting ready to have a kid. I recently had one (almost 10 months ago). All the time I spend on blogging, is time not spent with my wife and my kid. I do have hobbies other than software.
Not only that, but a lot of the fun in blogging is gone. I feel like discourse in the blogosphere has become so polarized lately, much like the political climate in this country. People seem content with “Drive By Commenting”, messing with someone’s day with a vitriolic comment without regard for conseqences. I'm happy that people vehemently disagree with each other and me, I wish we could keep the discourse civil and focused on finding common ground. Just because I disagree with you doesn’t mean I have to think your point is completely unreasonable or that you’re stupid.
I’ll still read blogs and be on Twitter. The discourse isn’t much higher on Twitter, but the time commitment is small enough to make it worth it. I predict blogging itself will be dead in a year anyway with everyone moving to Twitter or Twitter-like services.
Now that spring and summer is on its way to the Northwest, I think the timing for this move is good. I know this will disappoint many of my friends, but I have to do what’s right for me and my family. I hope you understand.
Yes, this is an April Fool's Joke
LazyCoder (aka Scott Koon) is organizing a little drinky drink this Wednesday around 6:00 PM-ish at The Three Lions Pub. This is just an informal gathering, not the huge production like the Hanselman Geek Dinner which requires eating at a mall food court because some three hundred plus geeks show up. (Did you know his last geek dinner was covered by the Seattle Times online?).
No, this will be a smaller intimate affair. Here’s your chance to get me sloshed by buying me beers in order to slip your pet feature into ASP.NET MVC. If it’s a really crazy feature idea, you may have to move up to Scotch. ;)
Seriously though, if you’re looking to blow off some steam on a Wed night (aren’t we all?) swing by and throw back one or a few with us.
UPDATE: I should have entitled this “Comparing Rhino Mocks and MoQ for State Based Testing”. I tend to prefer state-based testing over interaction based testing except in the few cases where it is absolutely necessary or makes the test much cleaner. When it is necessary, it is nice to have interaction based testing available. So my comparison is incomplete as I didn’t compare interaction based testing between the two frameworks.
For the longest time I’ve been a big fan of Rhino Mocks and have often written about it glowingly. When Moq came on the scene, I remained blissfully ignorant of it because I thought the lambda syntax to be a bit gimmicky. I figured if using lambdas was all it had to offer, I wasn’t interested.
Fortunately for me, several people in my twitter-circle recently heaped praise on Moq. Always willing to be proven wrong, I decided to check out what all the fuss was about. It turns out, the use of lambdas is not the best part of Moq. No, it’s the clean discoverable API design and lack of the record/playback model that really sets it apart.
To show you what I mean, here are two unit tests for a really simple example, one using Rhino Mocks and one using Moq. The tests use the mock frameworks to fake out an interface with a single method.
[Test]
public void RhinoMocksDemoTest()
{
MockRepository mocks = new MockRepository();
var mock = mocks.DynamicMock<ISomethingUseful>();
SetupResult.For(mock.CalculateSomething(0)).IgnoreArguments().Return(1);
mocks.ReplayAll();
var myClass = new MyClass(mock);
Assert.AreEqual(2, myClass.MethodUnderTest(123));
}
[Test]
public void MoqDemoTest()
{
var mock = new Mock<ISomethingUseful>();
mock.Expect(u => u.CalculateSomething(123)).Returns(1);
var myClass = new MyClass(mock.Object);
Assert.AreEqual(2, myClass.MethodUnderTest(123));
}
Notice that the test using Moq only requires four lines of code whereas the test using Rhino Mocks requires six. Lines of code is not the measure of an API of course, but it is telling in this case. The extra code in Rhino Mocks is due to creating a MockRepository class and for calling ReplayAll.
The other aspect of Moq I like is that the expectations are set on the mock itself. Even after all this time, I still get confused when setting up results/expecations using Rhino Mocks. First of all, you have to remember to use the correct static method, either SetupResult or Expect. Secondly, I always get confused between SetupResult.On and SetupResult.For. I feel like the MoQ approach is a bit more intuitive and discoverable.
The one minor thing I needed to get used to with Moq is that I kept trying to pass the mock itself rather than mock.Object to the method/ctor that needed it. With Rhino Mocks, when you create the mock, you get a class of the actual type back, not a wrapper. However, I see the benefits with having the wrapper in Moq’s approach and now like it very much.
My only other complaint with Moq is the name. It's hard to talk about Moq without always saying, “Moq with a Q”. I’d prefer MonQ to MoQ. Anyways, if that’s my only complaint, then I'm a happy camper! You can learn more about MoQ and download it from its Google Code Page.
Nice work Kzu!
Addendum
The source code for MyClass and the interface for ISomethingUseful are below in case you want to recreate my tests.
public interface ISomethingUseful
{
int CalculateSomething(int x);
}
public class MyClass
{
public MyClass(ISomethingUseful useful)
{
this.useful = useful;
}
ISomethingUseful useful;
public int MethodUnderTest(int x)
{
//Yah, it's dumb.
return 1 + useful.CalculateSomething(x);
}
}
Give it a whirl.
Whew! I’ve held off writing about MVC until I could write a non-MVC post in response to some constructive criticism (It’s not just Sean, Jeff mentioned something to me as well). Now that I’ve posted that, perhaps I’ve bought myself a few MVC related posts in a row before the goodwill runs dry and I have to write something decidedly not MVC related again. ;)
As ScottGu recently posted, the ASP.NET MVC source code is now available via CodePlex. A move like this isn’t as simple as flipping a switch and *boom* it happens. No, it takes a lot of effort behind the scene. On the one hand is all the planning involved, and Bertrand Le Roy and my boss Simon played a big part in that.
Along with planning is the execution of the plan which requires coordination among different groups such as the Devs, PMs, QA and the legal team. For that, we have our newest PM Scott Galloway to thank for that effort. I helped a little bit with the planning and writing the extremely short readme (I didn’t know what to say) and roadmap. One part of this experience that went surprisingly well was the person from our legal department we worked with. I was expecting a battle but this guy just got it and really understood what we were trying to do and was easy to work with.
With that said, I’ve seen a lot of questions about this so I thought I would answer a few here.
Is this the live source repository?
No, the MVC dev team is not committing directly into the CodePlex source code repository for many reasons. One practical reason is that we are trying to reduce interruptions to our progress as much as possible. Changing source code repositories midstream is a big disruption. For now, we’ll periodically ship code to CodePlex when we feel we have something worth putting out there.
Where is the source for Routing?
As I mentioned before, routing is not actually a feature of MVC which is why it is not included. It will be part of the .NET Framework and thus its source will eventually be available much like the rest of the .NET Framework source. It’d be nice to include it in CodePlex, but as I like to say, baby steps.
Where are the unit tests?
Waitaminute! You mean they’re not there?! I better have a talk with Scott. I kid. I kid. We plan to put the unit tests out there, but the current tests have some dependencies on internal tools which we don’t want to distribute. We’re hoping to rewrite these tests using something we feel comfortable distributing.
When’s the next update to CodePlex?
As I mentioned, we’ll update the source when we have something to show. Hopefully pretty often and soon. We’ll see how it goes.
As a team, we’re pretty excited about this. I wondered if the devs would feel a bit antsy about this level of transparency. Sure, anyone can see the source code for the larger .NET Framework, but that code has already shipped. This is all early work in progress. Can you imagine at your work place if your boss told you to publish all your work in progress for all the world to critique (if you’re a full time OSS developer, don’t answer that). ;) I’m not sure I’d want anyone to see some of my early code using .NET.
Fortunately, the devs on my team buy into the larger benefit of this transparency. It leads to a closer collaboration with our customers and creates a tighter feedback cycle. I am confident it will pay off in the end product. Of course they do have their limits when it comes to transparency. I tried suggesting we take it one step further and publish our credit card numbers in there, but that was a no go.
Technorati Tags:
aspnetmvc,
codeplex
My family and I recently moved into our new home after a two month stay in temporary housing. One of the perks of moving is when your stuff is delivered from storage, it feels like Christmas again. “Oooh! Look at all the boxes I get to unwrap. Hey! I have a Stereo just like this one!”.
I have a tendency to get distracted by the things I’m unwrapping. For example, I found a few of my old college Math textbooks. I started thumbing through the Complex Analysis, Abstract Algebra, and Number theory books and they seemed like total gibberish to me.
Artists and writers often get all the credit for creativity. It’s often why people call them creative types. Meanwhile, mathematicians are often unfairly portrayed and humorless, pencil pushing, uncreative types. This is so not true. Many mathematicians use computers now and love telling jokes like “Can you prove that the integral of e to the x is equal to f sub u of n?” Perhaps if I write out the equation the joke becomes more apparent.
∫ex = fu(n)
Hey, I didn’t say mathematicians had a good sense of humor. The fact is that this idea that mathematicians lack creativity comes from those who never made it to higher math. Once you hit abstract algebra, number theory, non-Euclidean geometry, etc... you start to wonder if perhaps the giants in the field were smoking a little something something to come up with this stuff.
The creativity involved in some of the proofs (or even the questions the proofs prove) just boggles the mind. I imagine that the proof of Fermat’s Last Theorem (which reportedly took 7 straight years of work to crack) is something that pretty much nobody in the world understands. Not unlike an abstract painting in a modern art museum. But I digress...
Number theory was my favorite class at the time so I thought I’d sit down, crack open the text, and see if I could understand one problem and even make progress on it.
No Dice.
I understood this stuff once, when I was in college, but now, when I’m older and wiser, I am slower to pick it up, even though I understood it once already. So I started thinking? What is different between the now me and the college me? Then it hit me...
Pizza Consumption!
Think about it for a sec. They often say programmers are machines that turns coffee into code. I wonder if college math students are machines that turn Pizza into solved problem sets? And what about the mythical lore of those early Dot-Com boom startups which started off as a small group of recent college students, Pepsi, and a bunch of Pizzas and ended up selling for millions? Pizza was the common denominator.
I think I’m on to something here. Perhaps Pizza is brain food. I wonder if it’s the Mozzarella or the Pepperoni. Of course, the problem for me now is that college was a long time ago. While the question of whether Pizza is brain food is mere idle speculation, it is a well established fact that Pizza is definitely gut food. Food for thought.
UPDATE: I’ve added a NuGet package named "routedebugger" to the NuGet feed, which will make it much easier to install.
In Scott Hanselman’s wonderful talk at Mix, he demonstrated a simple little route tester I quickly put together.

This utility displays the route data pulled from the request of the current request in the address bar. So you can type in various URLs in the address bar to see which route matches. At the bottom, it shows a list of all defined routes in your application. This allows you to see which of your routes would match the current URL.
The reason this is useful is sometimes you expect one route to match, but another higher up the stack matches instead. This will show you that is happening. However, it doesn’t provide any information why that is happening. Hopefully we can do more to help that situation in the future.
To use this, simply download the following zip file and place the assembly inside of it into your bin folder. Then in your Global.asax.cs file add one line to the Application_Start method (in bold).
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
}
This will update the route handler (IRouteHandler) of all your routes to use a DebugRouteHandler instead of whichever route handler you had previously specified for the route. It also adds a catch-all route to the end to make sure that the debugger always matches any request for the application.
I’m also making available the full source (using the word full makes it sound like there’s a lot, but there’s not all that much) and a demo app that makes use of this route tester. Let me know if this ends up being useful or not for you.
UPDATE: I updated the sample to work with the final version of ASP.NET Routing included with ASP.NET 3.5 SP1. This sample is now being hosted on CodePlex.
Download the demo here
In my last post I described how Routing no longer has any dependency on MVC. The natural question I’ve been asked upon hearing that is “Can I use it with Web Forms?” to which I answer “You sure can, but very carefully.”
Being on the inside, I’ve had a working example of this for a while now based on early access to the bits. Even so, Chris Cavanagh impressively beats me to the punch in blogging his own implementation of routing for Web Forms. Nice!
One of the obvious uses for the new routing mechanism is as a “clean” alternative to URL rewriting (and possibly custom VirtualPathProviders for simple scenarios) for traditional / postback-based ASP.NET sites. After a little experimentation I found some minimal steps that work pretty well:
- Create a custom IRouteHandler that instantiates your pages
- Register new Routes associated with your IRouteHandler
- That’s it!
He took advantage of the extensibility model by implementing the IRouteHandler interface with his own WebFormRouteHandler class (not surprisingly my implementation uses the same name) ;)
There is one subtle potential security issue to be aware of when using routing with URL Authorization. Let me give an example.
Suppose you have a website and you wish to block unauthenticated access to the admin folder. With a standard site, one way to do so would be to drop the following web.config file in the admin folder...
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<deny users="*" />
</authorization>
</system.web>
</configuration>
Ok, I am a bit draconian. I decided to block access to the admin directory for all users. Attempt to navigate to the admin directory and you get an access denied error. However, suppose you use a naive implementation of WebFormRouteHandler to map the URL fizzbucket to the admin dir like so...
RouteTable.Routes.Add(new Route("fizzbucket"
, new WebFormRouteHandler("~/admin/secretpage.aspx"));
Now, a request for the URL /fizzbucket will display secretpage.aspx in the admin directory. This might be what you want all along. Then again, it might not be.
In general, I believe that users of routing and Web Form will want to secure the physical directory structure in which Web Forms are placed using UrlAuthorization. One way to do this is to call UrlAuthorizationModule.CheckUrlAccessForPrincipal on the actual physical virtual path for the Web Form.
This is one key difference between Routing and URL Rewriting, routing doesn’t actually rewrite the URL. Another key difference is that routing provides a mean to generate URLs as well and is thus bidirectional.
The following code is my implementation of WebFormRouteHandler which addresses this security issue. This class has a boolean property on it that allows you to not apply URL authorization to the physical path if you’d like (in following the principal of secure by default the default value for this property is true which means it will always apply URL authorization).
public class WebFormRouteHandler : IRouteHandler
{
public WebFormRouteHandler(string virtualPath) : this(virtualPath, true)
{
}
public WebFormRouteHandler(string virtualPath, bool checkPhysicalUrlAccess)
{
this.VirtualPath = virtualPath;
this.CheckPhysicalUrlAccess = checkPhysicalUrlAccess;
}
public string VirtualPath { get; private set; }
public bool CheckPhysicalUrlAccess { get; set; }
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (this.CheckPhysicalUrlAccess
&& !UrlAuthorizationModule.CheckUrlAccessForPrincipal(this.VirtualPath
, requestContext.HttpContext.User
, requestContext.HttpContext.Request.HttpMethod))
throw new SecurityException();
var page = BuildManager
.CreateInstanceFromVirtualPath(this.VirtualPath
, typeof(Page)) as IHttpHandler;
if (page != null)
{
var routablePage = page as IRoutablePage;
if (routablePage != null)
routablePage.RequestContext = requestContext;
}
return page;
}
}
You’ll notice the code here checks to see if the page implements an IRoutablePage interface. If your Web Form Page implements this interface, the WebFromRouteHandler class can pass it the RequestContext. In the MVC world, you generally get the RequestContext via the ControllerContext property of Controller, which itself inherits from RequestContext.
The RequestContext is important for calling into API methods for URL generation. Along with the IRoutablePage, I provide a RoutablePage abstract base class that inherits from Page. The code for this interface and the abstract base class that implements it is in the download at the end of this post.
One other thing I did for fun was to play around with fluent interfaces and extension methods for defining simple routes for Web Forms. Since routes with Web Forms tend to be simple, I thought this syntax would work nicely.
public static void RegisterRoutes(RouteCollection routes)
{
//first one is a named route.
routes.Map("General", "haha/{filename}.aspx").To("~/forms/haha.aspx");
routes.Map("backdoor").To("~/admin/secret.aspx");
}
The general idea is that the route url on the left maps to the webform virtual path to the right.
I’ve packaged all this up into a solution you can download and try out. The solution contains three projects:
- WebFormRouting - The class library with the
WebFormRouteHandler and helpers...
- WebFormRoutingDemoWebApp - A website that demonstrates how to use WebFormRouting and also shows off url generation.
- WebFormRoutingTests - a few non comprehensive unit tests of the WebFormRouting library.
WARNING: This is prototype code I put together for educational purposes. Use it at your own risk. It is by no means comprehensive, but is a useful start to understanding how to use routing with Web Forms should you wish. Download the demo here.
At this year’s Mix conference, we announced the availability of the second preview for ASP.NET MVC which you can download from here. Videos highlighting MVC are also available.
Now that I am back from Mix and have time to breathe, I thought I’d share a few (non-exhaustive) highlights of this release as well as my thoughts on the future.
New Assemblies and Routing
Much of the effort and focus of this release was put into routing. If you’ve installed the release, you’ll notice that MVC has been factored into three assemblies:
- System.Web.Mvc
- System.Web.Routing
- System.Web.Abstractions
The key takeaway here is that MVC depends on Routing which depends on Abstractions.
MVC => Routing => Abstractions
Routing is being used by another team here at Microsoft so we worked on making it an independent feature to MVC. MVC relies heavily on routing, but routing doesn’t have any knowledge of MVC. I’ll write a follow up post that talks about the implications of that and how you might use Routing in a non-MVC context.
Because of the other dependencies on Routing, we spent a lot of time trying to make sure we got the API and code correct and making sure the quality level of routing meets an extremely high bar. Unfortunately, this investment in routing did mean that we didn’t implement everything we wanted to implement for MVC core, but hey, it’s a preview right? ;)
CodePlex Builds
At Mix this year Scott Hanselman’s gave a great talk (IMHO) on MVC. One thing he announced during that talk is the vehicle by which we will be making the MVC source code available. Many of you might recall ScottGu’s recent roadmap for MVC in which he mentioned we would be making the source available. At Mix, Scottha announced that we would be deploying our source to CodePlex soon.
Not only that, we hope to push source from our source control to a CodePlex Project’s source control server on a semi-regular basis. These builds would only include source (in a buildable form) and would not include the usual hoopla with associated with a full Preview or Beta release.
How regular a schedule we keep to remains to be seen, but Scott mentioned in his talk around every four to six weeks. Secretly, between you and me, I’d love to push even more regularly. Just keep in mind that this is an experiment in transparency here at Microsoft, so we’ll start slow (baby steps!) and see how it progresses. In spirit, this would be the equivalent to the daily builds that are common in open source projects, just not daily.
Unit Test Framework Integration
In a recent post, I highlighted some of the work we’re doing around integrating third party unit testing frameworks.

I’ve been in contact with various unit testing framework developers about integrating their frameworks with the MVC project template. I’m happy to see that MbUnit released updated installers that will integrate MbUnit into this dropdown. Hopefully the others will follow suit soon.
One interesting approach I should point out is that this is a great way to integrate your own totally tricked out unit testing project template complete with your favorite mock framework and your own private assembly full of your useful unit test helper classes and methods.
If you’re interested in building your own customized test framework project which will show up in this dropdown, Joe Cartano of the Web Tools team posted an updated streamlined walkthrough on how to do so using NUnit and Rhino Mocks as an example.
Upcoming improvements
One area in this preview we need to improve is the testability of the framework. The entire MVC dev team had a pause in which we performed some app building and uncovered some of the same problems being reported in various forums. Problems such as testing controller actions in which a call to RedirectToAction is made. Other problems include the fact that you need to mock ControllerContext even if you’re not using it within the action. There are many others that have been reported by various people in the community and we are listening. We ourselves have encountered many of them and definitely want to address them.
Experiencing the pain ourselves is very important to understanding how we should fix these issues. One valuable lesson I learned is that a framework that is testable does not mean that applications built with that framework are testable. We definitely have to keep that in mind as we move forward.
To that end, we’ll be applying some suggested improvements in upcoming releases that address these problems. One particular refactoring I’m excited about is ways to make the controller class itself more lightweight. Some of us are still recovering from Mix so as we move forward, I hope to provide even more details on specifically what we hope to do rather than this hand-waving approach. Bear with me.
During this next phase, I personally hope to have more time to continuously do app building to make sure these sort of testing problems don’t crop up again. For the ones that are out there, I take responsibility and apologize. I am a big a fan of TDD as anyone and I hate making life difficult for my brethren. ;)
RTM
When do we RTM? This is probably the most asked question I get and right now, I don’t have a good answer. In part, because I’m still trying to sort through massive amounts of feedback regarding this question. Some questions I’ve been asking various people revolve around the very notion of RTM for a project like this :
- How important is RTM to you?
- Right now, the license allows you to go-live and we’ll provide the source, is that good enough for your needs?
- Is it really RTM that you want, or is it the assurance that the framework won’t churn so much?
- What if we told you what areas are stable and which areas will undergo churn, would you still need the RTM label?
- Is there a question I should be asking regarding this that I’m not? ;)
I do hope to have a more concrete answer soon based on this feedback. In general, what I have been hearing from people thus far is they would like to see an RTM release sooner rather than later, even if it is not feature rich. I look forward to hearing from more people on this.
Closing Thoughts
In general, we have received an enormous amount of interest and feedback in this project. Please do keep it coming as the constructive feedback is really shaping the project. Tell us what you like as well as what is causing you problems. We might not respond to every single thing reported as quickly as we would like to, but we are involved in the forums and I am still trying to working through the massive list of emails accrued during Mix.
You don’t so much return from Las Vegas as you recover from Las Vegas.
Right now, I am recovering from my Las Vegas trip. Recovering from Vegas Nose caused by the extremely dry air and massive second hand smoke inhalation. Recovering from the sensory onslaught they call casinos. Recovering from the fake kitschiness and manafactured excitement as people sit like zombies feeding machines their life savings.
Yet despite all that, I still love the place. Maybe because despite the bad things, Vegas is really the Disneyland for adults with a slight bad streak inside that yearns to get out once in a while to indugle in a vice or three.
I especially love the Mix conference there. As Jeff Atwood writes (and I agree)...
MIX is by far my favorite Microsoft conference after attending the ’06 and ’07 iterations...
What I love about Mix is that it ...
- is relatively small and intimate, at around 2,000 attendees.
- seamlessly merges software engineering and design.
- includes a lot of non-Microsoft folks, even those that are traditionally hostile to Microsoft, so there’s plenty of perspective.
Some highlights from Mix include seeing old friends again such as Jon, Steve, and Miguel. Also enjoyed having time to hang with my coworkers in a non work setting after having imbibed much alcohol. And of course meeting a lot of people I know through the intarweb such as Kevin Dente, Steven Smith, and Dave Laribee among others I’m forgetting at the moment.
I also played Poker for the first time at a casino and I had a blast, leaving with some winnings despite losing four close showdowns, a couple of them in which my pocket Kings were beaten by pocket Aces. Who’d a thunk it?!
The past couple of weeks have been a rough time for me and my family. I missed a few days of work due to a bad fever, and my wife then suffered through the same fever the following week. Fortunately Cody hasn’t seemed to have caught the fever.
In a week, we will finally move into our new home. While our temporary housing has been nice, we’ve been here a long while and it’s just hard to feel settled when we are not in our own home. Once we move into our house and make it our own, I think we’ll finally feel settled into this place and find our rhythm here. Who knows, maybe I’ll have more time for my extracurricular activities I used to do.
Speaking of extracurricular, I have joined two soccer leagues now, the GSSL (Greater Seattle Soccer League) and the MSSL (Microsoft Soccer League). Unfortunately, my foot is injured due to a hard tackle so I didn’t have a good showing in my first MSSL game today.
In the past month, I’ve given several talks, some that went well and one that went...how should I put it...very badly. Hopefully I will be asked to speak again. At least my TechReady (an internal talk) went well with 240 attendees, but probably because Scott Hanselman carried the both of us. ;) That boy can talk!
If you’ve read this far expecting technical content, my apologies, it’s a Saturday. We just had an updated preview of MVC released and I will be writing about that in some upcoming posts. In the meanwhile, the sun just came up outside for once and my mood is lifted after a dark few weeks. Things are starting to look up for me in this town. Hope things are well with you as well.
Technorati Tags:
Vegas,
Mix,
Personal
One interesting response to my series on versioning of interfaces and abstract base classes is the one in which someone suggested that we should go ahead and break their code from version to version. They’re fine in requiring a recompile when upgrading.
In terms of recompile, it’s not necessarily recompiling your code that is the worry. It’s the third party libraries you’re using that poses the problem. Buying a proper third-party library that meets a need that your company can be a huge cost-saving measure in the long run, especially for libraries that perform non-trivial calculations/tasks/etc... that are important to your application. Not being able to use them in the event of an upgrade could be problematic.
Let’s walk through a scenario. You’re using a third-party language translation class library which has a class that implements an interface in the framework. In the next update of the framework, a new property is added to the interface. Along with that property, some new classes are added to the Framework that would give your application a competitive edge if it could use those classes.
So you try and recompile your app, fix any breaks in your app, and everything seems fine. But when you test your app, it breaks because the third party library is not implementing the new interface. The third party library is broken by this change.
Now you’re in a bind. You could try to write your own language translation library, but that’s a huge and difficult task and your company is not in the business of writing language translators. You could simply wait for the third party to update their library, but in the meanwhile, your competitors are passing you by.
So in this case, the customer has no choice but to wait. It is my hunch that this is the sort of bind we’d like to limit as much as possible. This is not to say we never break, as we certainly do. But we generally limit breaks to the cases in which there is a security issue.
Again, as I’ve said before, the constraints in building a framework, any framework, are not the same constraints of building an app. Especially when the framework has a large number of users. When Microsoft ships an interface, it has to expect that there will be many many customers out there implementing that interface.
This is why there tends to be an emphasis on Abstract Base Classes as I mentioned before within the .NET Framework. Fortunately, when the ABC keeps most, if not all, methods abstract or virtual, then testability is not affected. It’s quite trivial to mock or fake an abstract base class written in such a manner as you would an interface.
Personally, I tend to like interfaces in my own code. I like the way I can quickly describe another concern via an interface and then mock out the interface so I can focus on the code I am currently concerned about. A common example is persistence. Sometimes I want to write code that does something with some data, but I don’t want to have to think about how the data is retrieved or persisted. So I will simply write up an interface that describes what the interaction with the persistence layer will look like and then mock that interface. This allows me to focus on the real implementation of persistence later so I can focus on the code that does stuff with that data now.
Of course I have the luxury of breaking my interfaces whenever I want, as my customers tend to be few and forgiving. ;)