I have a penchant for taking "unsolvable" computer problems and getting to the bottom of them.  Often times this means I'm exploring the contents of a memory dump, that is, all of the data held in RAM of the process you're inspecting.  When I got started in this area about 2+ years ago I found Tess Fernandez's blog blog was a great resource.  In fact I've blogged about Tess and WinDBG before.  Her blog is one of my favorites when it comes to debugging and troubleshooting .NET applications (web or otherwise).

Debugging and troubleshooting is a skill I think too many developers lack.  By debugging and troubleshooting I don't mean stepping your way through code.  I mean, "Holy Crap our production app is failing and we don't know why," kind of debugging.  I think debugging is so valuable that I used to ask specific questions about it during interviews.  Too many times I could ask questions and see the developer try to answer, but often it was easy to see that if this was a real world scenario and not an interview question, they would have long ago thrown up their arms in defeat.  Computers are predictable, they don't "decide" anything, they're told what to do. If you understand that you're a step ahead of the average developer when it comes to debugging and troubleshooting.

Earlier this week DotNetRocks interviewed Tess Fernandez, an escalation engineer with Microsoft.  She's Tier 2 support. In other words, when you have a problem and call Microsoft you get Tier 1 support.  Then "when thinks get too sticky" she comes to the rescue. 

(I'd like to take a moment and have you consider the types of problems she gets.  The typical engineer will encounter many issues over their career.  I'm sure you've had them.  I've had them.  However, I typically will peruse articles, blog posts, and forum posts to find the answers I look for.  When faced with a problem, how many times have you ever resorted to calling Microsoft? Me? Zero. So imagine for a moment that you've not found an answer on any of the typical resources and have called Microsoft.  You're working with their Tier 1 support but they can't seem to help you.  It as it this point that you get a person like Tess.  She's smart.  She know .NET like I know Mt. Dew).

If you're sitting at a desk download the podcast and listen now:


 
Categories: .NET | Debugging

imageI have what I believe to be a fairly simple problem in theory, yet in reality it proves to be a bit more hairy.  Below I present the problem and the requirements as I see them as well as a few possible solutions.  The solution I've settled on may or may not be correct, so I'm tossing out here to see what you guys think.  By all means please post some feedback.

Problem

To have a common, consistent logging access across multiple assemblies (that I own) in an application.

Requirements

  • I want to be able to have logging capabilities in any method of any class in my application.
  • I want to define logging once and only once for my application. 
  • I want to maintain testability by not having any unnecessary dependencies or unmockable objects. 
  • I want as few assemblies to be aware of dependencies as possible.
  • If at all possible I wanted to avoid having all of my classes have an external dependency on some interface (such as ILog)
    • I also want to avoid every class having a public property which exposes an ILog (for setter injection)

The Structure

To the right is a picture of the assembly dependency diagram.

Solution #1

I could use Windsor's logging facility as suggested by Casey Charlton except that the solution provided only seemingly works for my top level assembly, ABCCompany.MVC.Web.  I don't want my other assemblies to be aware that I'm using an IoC Container.  I especially don't want the assemblies to know I'm bound to a particular IoC container (in this case I'm using Castle's Windsor container).  I've emailed Casey about this and we are going to try to talk this through.  I'm interested to hear what his thoughts are given that on Castle's site it says about the logging facility (emphasis mine):

The logging facility provides a seamless way to add logging capabilities to your application. There are two levels of integration.

  • Allow your classes to receive an ILogger instance for logging support
  • Allow you to ask for an ILoggerFactory instance to provide logging support to classes that are not managed by Windsor.

While I wait to talk with Casey I have to discount this solution since I cannot see past the first assembly on how this would work and therefore cannot use this as my solution of choice.

Solution #2

This is what I've come up with so far.  Please comment if you see issues. 

I have set up a static class inside of the ABCCompany.Framework assembly from which all methods could call for Logging purposes.  This satisfies the requirements above which states that I do not want constructor dependencies nor public setters on all classes.  This solution however does mean that every assembly much also ship with the ABCCompany.Framework assembly and all of it's dependent assemblies.  I'm okay with this until I hear a reason that this is bad.  I view this much like when I do work with Castle that in order to get any behavior I have to bring Castle.Core along to the party.

I liked Casey's solution (Solution #1) except that I cannot see past it working in one and only one assembly.  I thought I could modify his solution by simply having a static class, which any assembly can reference and call.  By default the Logger would be set up with a NullLogger.  The Logging class would have a method available to change the underlying logger.  It would then be incumbent upon the application layer to change the logger if they actually wanted logging.  In my app this is the first thing that happens, the NullLogger is replaced by an actual logger by calling Log.SetLogger().

As you can see from the code below I've followed much of Casey's example.

   1: private static ILogger logger;
   2:  
   3: public static ILogger Logger
   4: {
   5:     get
   6:     {
   7:         if (logger == null)
   8:         {
   9:             logger = NullLogger.Instance;
  10:         }
  11:         return logger;
  12:     }
  13: }
  14:  
  15: public static void SetLogger(ILogger value)
  16: {
  17:     logger = value;
  18: }

I do have a dependency on the Castle.Core assembly (due to usage of types in Castle.Core.Logging).  However none of the classes using the Log static class have to reference anything to do with Castle since I've have methods which pass through to every method in ILogger (see example below):

   1: public static void Debug(string message)
   2: {
   3:     Logger.Debug(message);
   4: }
   5:  
   6: public static void Debug(string message, Exception exception)
   7: {
   8:     Logger.Debug(message,exception);
   9: }
  10:  
  11: public static void Debug(string format, params object[] args)
  12: {
  13:     Logger.Debug(format, args);
  14: }
  15:  
  16: public static void DebugFormat(string format, params object[] args)
  17: {
  18:     Logger.DebugFormat(format, args);
  19: }
  20:  
  21: public static void DebugFormat(Exception exception, string format, params object[] args)
  22: {
  23:     Logger.DebugFormat(exception,format, args);
  24: }
  25:  
  26: public static void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
  27: {
  28:     Logger.DebugFormat(formatProvider, format, args);
  29: }
  30:  
  31: public static void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
  32: {
  33:     Logger.DebugFormat(exception, formatProvider, format, args);
  34: }

The usage pattern becomes quite simple in that any class that references ABCCompany.Framework can use the ABCCompany.Framework.Logging.Log class.  No external references needs

The reason I chose to bind myself at the framework level to Castle's ILogger interface and not something like ILog (log4net) was because ILogger is an abstraction over the ILog interface.  Castle also provides some concrete implementations of ILogger, one of which is for log4net

  • log4net (requires Castle.Services.Logging.Log4netIntegration.dll)
  • NLog (requires Castle.Services.Logging.NLogIntegration.dll)
  • ConsoleLogger
  • DiagnosticsLogger
  • StreamLogger
  • WebLogger (TraceContext)
  • NullLogger (used as placeholder)

As far as testing is concerned, the solution imposes no restrictions on testing.  In my testing assemblies my logging calls are swallowed by the null logger.  If I want to ensure the logger is called in my testing (interaction based tests), I can mock an instance of ILogger and call Log.SetLogger() and set up expectations on the mock ILogger.

As I've mulled over this solution now for about a day it feels pretty solid.  As I go through the requirements above they are all satisfied.  However I can only see as far as my current knowledge so I'm hoping that if you see issues with the above that you'll let me know.


 
Categories: .NET | Programming

August 4, 2008
@ 09:55 AM

I posted earlier this year with the basic question, Is Var Better?  I'm not the only one to question the reintroduction of var.  Rhys Campbell went as far as to say some abuse the new keyword. I will say that my initial aversion to using var has softened a bit.  However there are at least two issues I have with them.

  1. Implicit conversions
  2. Intellisense

Implicit Conversions

In my latest project I've encapsulated all domain knowledge in it's own assembly in DDD fashion.  We have the notion of a ProductSku, a unique identifier for a product.  A Product object therefore has a ProductSku property which identifies it.  I could have implemented the ProductSku property as a string type, but in thinking about my domain and remembering March is Not a Number ProductSku is now it's own first-class citizen type.

I have the following code to perform implicit conversion from a ProductSku to a string:

   1: /// <summary>
   2: /// Performs an implicit conversion from <see cref="JPCycles.Domain.ProductSKU"/> to <see cref="System.String"/>.
   3: /// </summary>
   4: /// <param name="sku">The sku.</param>
   5: /// <returns>The result of the conversion.</returns>
   6: public static implicit operator string(ProductSKU sku)
   7: {
   8:     return sku.value;
   9: }

In order to test this method I have the following code:

   1: [Test]
   2: public void Implicit_conversion_of_sku_to_string()
   3: {
   4:     string skuValue = "ZZ123456";
   5:     var sku = new ProductSKU(skuValue);
   6:  
   7:     var converted = sku;
   8:  
   9:     Assert.That(converted, Is.EqualTo(skuValue));
  10: }

As you can see in line 7, I'm using the var keyword.  The problem with this is that using var in the scenario keeps me from testing the code that I want to test.  The goal of the test is to confirm the implicit conversion of a ProductSku to string.  This happens in line 7.  However when using the var keyword, the compiler interprets the "converted" variable as a ProductSku object and not a string object, as I really want. 

See below for confirmation:

image

(You might be saying to yourself that the conversion still happens in line 9, when the ProductSku object is evaluated against a string.  You might be right?  Or...does the string get implicitly converted to a ProductSku object?  If you don't know the answer to that question off the top of you head you cannot rely on line 9 for your conversion.  Also you shouldn't be using your asserts to perform the work for which you are testing)

If I leave the var keyword in place in line seven, my test will pass and possibly deceive me into thinking I've properly tested my code.  Only when running a coverage report do I see that the implicit conversion method is never being called.

The use of var is fine, except that now I have to think about how the compiler will interpret a statement versus what I want in programming it.  The var keyword does the best it can, but sometimes that's not good enough.  As another example, compare the following code:

   1: IUser user1 = new User();
   2: var user2 = new User();
The two users above have different type signatures, which on some level bothers me a bit, since you can see that the code is clearly the same.

Intellisense

The use of var makes intellisense less effective.  It's not the compilers fault though.  Given the point where you use var, the compiler has no idea what you're going to type on the right-hand side of the expression, so it cannot help. 

Say, for example, I want to define a Dictionary<string,string> called "my list".  When I use the var keyword, I have to type out enough information from which intellisense can narrow down what I'm looking for.  I hear a lot from the proponents of var how great it is because complex declarations, especially with generics, can be avoided.  I disagree and only need to show you the example below to prove my point.  In the example below I'm writing the exact same line of code.  The first example uses var, the second does not, which would you prefer?

image 

image

When using var I had to type everything since the compile cannot help me, only I had to type on the right hand side of the expression.  So I really have saved nothing.

Jeff Atwood posted that by not using var, you're being redundant.  I would say that by not being redundant, for which the compiler penalizes you nothing, you're being slower, because you cannot take advantage of build-in assistance, ie intellisense.

These two annoyances won't stop me from using var in various (read: limited) situations.  The point of this post is to caution the reader to not be too quick to jump on the var bandwagon.  In the first example it may cause you headaches in performing proper testing and in the second, it may slow you down with the loss of intellisense.


 
Categories: .NET | Programming

I'm on vacation and am sitting in a coffee shop catching up on some blogs.  Sergio Pereira posted the other day his praises of the new crop of .NET screencasts.  His post explicitly calls out Steve Bohlen and his Summer of NHibernate series.  I wanted to echo Sergio's sentiments about the .NET screencasts and in particular Steve's new series.  I have used the quiet evening in the cabin to watch the excellent videos that Steve Bohlen has put out.  The quality of the videos both in production and content are unsurpassed.  I've used NHibernate before but this is a much better primer than reading a few blog posts/tutorials here and there when a roadblock is hit.

If you've not seen these videos yet and are looking for a good introduction to NHibernate, check out the Summer of NHibernate series.  When you do, make sure you donate (at least a dollar).


 
Categories: .NET | Open Source Software | ORM

This is the third in an ongoing series of articles about my team's transition to the Asp.NET MVC Framework.  In my last post I blogged a bit about how I haven't quite got comfortable enough with the new MVC framework to feel über productive.  What augments the feeling is the difficulty of finding quality information.  The data is few and far between and only sometimes relevant.

I was struggling yesterday to find information on the ComponentController class.  Things I was finding were from the Preview 2 release but finding something on the Preview 3 release was a bit more challenging.  Things are rapidly changing in the framework and the MVC team is not afraid to refactor, rename , or even remove a class.  For example, with the release last night, ComponentController is no longer a worry of mine because it's now gone, removed completely from the framework. 

The MVC framework has been around for under a year (Nov 2007 I believe).  It is now in it's fourth iteration (Preview four, released last night).  While a number of people have downloaded and are using the framework the amount of data/tutorials/blogs/articles pales in comparison to the same information about web forms.  This makes finding the info you need much much tougher.  It's exciting though and must say I enjoy the challenge.  The change in releases doesn't bother me.  It's a bit of a nuisance but I signed up for this trip.  Also the changes are for the better.  The ComponentController class that was replaced yesterday was not easily testable.  The MVC team removed it in favor of the Controller class, which is testable!  Fundamentally it boils down to the fact that I trust the guys on the MVC team and where they're going with the framework.

That trust doesn't help me day to day in moving my project forward though.  In order to find the data I need I've had to be both resourceful and thorough in my reading.  The trick I've found is following a few bloggers closely and reading all of their posts regarding MVC and all comments made to the posts (that's where I find the real gems, in the comments).

Here is a list of bloggers I'm following, obviously some are well-known, others are not.  If you follow some bloggers who post about the MVC framework that aren't on my list please share!! My list:

Updated to add new blogs (7/23/2008) ... thanks Ben

Yesterday I reported that I was learning to walk and while I can't quite say I'm walking yet,  I'm feeling a bit more comfortable.  My velocity increased ever so slightly today and I'm encouraged by that and excited for tomorrow!  And to be quite honest that's a perfectly find place to be.


 
Categories: .NET | MVC

A few days ago I posted that our team was making the transition from webforms to MVC.  Since then a few days have gone by and I wanted to post my some struggles and successes (however few) in recent days.

First, it's been tough wrapping my head around the shift from web forms to MVC.  I would caution anyone making a similar shift or considering it, that despite the recognized short comings of web forms and the postback model that one should approach the change expecting a bit of a rough going in the beginning.  Never underestimate what years of articles, blogs, and webcasts about web forms and working in web forms will do to your perspective.  OnClick...gone.  PreRender...gone.

Does the experience thus far cause me to regret the choice to go MVC route?  Absolutely not.  It was 100% the correct decision.  Despite the difficulties of making the shift, there are points where something clicks and it feels better and more natural.  I'm waiting for that shift and those clicks to be more permanent.  The best analogy I can use to explain it is likening the experience to my one year old son who is learning to walk. To him crawling feels right.  When crawling, he's quicker, self-assured, and can generally get where he wants to go.  When he attempts to walk however, he falls down, he struggles to keep his balance, and generally getting anywhere takes longer.  It's temporary though, we know it and that's why we encourage him to walk and push through the awkwardness. In a few years Lincoln will realize (if not verbally but by the way he chooses to move) how much more natural walking is than crawling, a fact that I'm reminded of every time I get down on all fours with Lincoln.

So what am I doing to push through?  First I'm trying to keep in the project.  With smaller tasks and projects always requiring attention, I'm trying to stay in the project as much as possible.  Secondly, I'm thinking about how I think (Metacognition).  Thinking about MVC, testability, loose coupling and other such principles only aid in the transition.  I'm hoping the next two days this week give way to breakthroughs.  Near the end of the day I had some small wins and started to gain some velocity which leaves me optimistic for tomorrow.


 
Categories: .NET | MVC

We recently decided that with the effort we're putting into our website and some changes that we're making that now would be as good of time as ever to make the switch to the new Asp.net MVC Framework.  We're no Google, but we're currently receiving around 18,000 unique visitors a day and 300,000 page views and hope to grow that number as we make our site easier to use for our customers.  I hope to rely heavily on Phil, Rob, and Scott for assistance if needed. 

The MVC design appeals to us because the large amount of business logic that has crept it's way into the codebehind.  Despite the best intentions, the current site, which is programmed in asp.net 1.1, has had too much logic to creep into presentational areas while running with webforms.  The biggest drawback to this is reduced testability.  Testability should be important in any project but for us it is paramount. We have business rules that if not adhered to amount to real-world fines:

A few years ago a customer bought some lubricant that is sold in an aerosol can.  Since 9/11 aerosol cans cannot be shipped as cargo on airplanes.  Somehow this order made it though the checks we have for this type of thing in the warehouse and made it onto the UPS truck.  At the UPS facility, a UPS employee heard something emanating from a box that sounded like an aerosol can.  At that point he is required by law to check the contents.  When he opened the box he found the aerosol cans.  Despite knowing us and our reputation, he was required to call the FAA and say something to the effect of, "I found some aerosol cans in a package that was scheduled to be flown."  It didn't matter that this was an accident or "just a few cans", we were still fined.  We were warned that if this were to happen again that we would face a fine somewhere in the low six figures. The FAA doesn't mess around.

As we go forward I plan to document on this blog the highs and lows of our transition.  I'll post questions and problems we're having that I hope you can help with as well as tips and tricks our team has found helpful.  Stay tuned as we make the transition.


 
Categories: .NET | MVC | Software

A coworker ran across the following and shared with me.

   1: Dim strpage
   2: strpage = pageNumber.ToString()
   3: If Len(strpage) = 1 Then
   4:     strpage = "000" & strpage
   5: ElseIf Len(strpage) = 2 Then
   6:     strpage = "00" & strpage
   7: ElseIf Len(strpage) = 3 Then
   8:     strpage = "0" & strpage
   9: End If 

The programmer is trying to ensure that the page number, when printed out, is always four characters long.  This is not the best way to write this code.  I thought I'd keep this post to myself but unfortunately this isn't the first time I've seen code like this, it is quite common.

The better way to write the above is:

   1: Dim strpage
   2: strpage = pagenumber.ToString("0000")

It's shorter, more concise, and easier to read.  Further the second example is more extensible.  If the requirements change to say the page number should be five characters, the first example must recompile.  The second example must be recompiled as well in it's current state, however the string "0000" could be moved to a configuration file somewhere and then wouldn't need to be.


 
Categories: .NET | Programming

June 17, 2008
@ 03:05 PM

Compare the following two error messages and think about which you would find more helpful.  Then, the next time you are throwing exceptions with messages remember this post.

Error Message from Castle's Windsor IoC libraries:

Can't create component 'ProductService' as it has dependencies to be satisfied.

ProductService is waiting for the following dependencies:

Services:
- ABCCompany.Framework.Services.IInventoryService which was registered but is also waiting for dependencies.

ControllerInventory is waiting for the following dependencies:

Services:
- ABCCompany.Controller.IInventoryRequestInterpreter which was not registered.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Castle.MicroKernel.Handlers.HandlerException: Can't create component 'ProductService' as it has dependencies to be satisfied.

ProductService is waiting for the following dependencies:

Services:
- ABCCompany.Framework.Services.IInventoryService which was registered but is also waiting for dependencies.

ControllerInventory is waiting for the following dependencies:

Services:
- ABCCompany.Controller.IInventoryRequestInterpreter which was not registered.

Error Message from .NET framework:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

 
Categories: .NET | Programming | Software

"But you have the source!"

I heard that statement a little over a month ago at the Alt.Net Open Spaces event in Seattle.  It's no secret to those who know the community, that open source technologies are at the very least promoted and in many cases you'll find many open source project committers within the Alt.Net community.  Heck, David Laribee, a founding member if there is such a thing, in a post defined Alt.Net as (emphasis mine):

  1. You’re the type of developer who uses what works while keeping an eye out for a better way.
  2. You reach outside the mainstream to adopt the best of any community: Open Source, Agile, Java, Ruby, etc.
  3. You’re not content with the status quo. Things can always be better expressed, more elegant and simple, more mutable, higher quality, etc.
  4. You know tools are great, but they only take you so far. It’s the principles and knowledge that really matter. The best tools are those that embed the knowledge and encourage the principles (e.g. Resharper.)

The quote, and many like it, came in a session titled "Mature Open Source projects versus first generation Microsoft projects".  The discussion centered around why some (many) developers, managers, and executives feel comfortable choosing a brand-new Microsoft product when a far more mature open source alternative exists.  One the fears surrounding the adoption of open source is the lack of surety that open source project will exist in perpetuity.  One needs to look no further than two projects, NVelocity and NDoc, to find historical evidence of an open source project vanishing.  The main counter-point to that argument, and many others, was the quote above, that with open source, you were never truly left high-and-dry, since you had the source.

It's a noble thought, but really, who wants to manage another codebase in addition to their own?  In fact I turn to open source project many times so I don't have to write my own code.  Why re-invent what someone else has already done and guided to maturity?  The idea that I can compile and manage another, possibly large, and probably complex codebase is hardly a comfort to me.  It wasn't until a few weeks ago that I realize that the open source pundits were correct.

I have been working on a project for the last year that has, as of two versions ago, started using Watin to automate the downloading of a file from the internet.  Watin is a testing framework but is used by many to automate business processes, which is what I use it for.  If you haven't checked it out yet, it's beautifully simple.

Watin provides handlers to download a file, however, the code was hanging at the point where it should've cleared the download.  I looked at every documentation page, blog post, and blog comment I could to see if I was missing something.  My usage was correct.  So I dug in a bit further using WinDowse to find the handle of the button that should be clicked.  As it turns out the handle of the Save button in a FileDownload Dialog changed from 4424 to 4427 in IE7, who would've guessed it right?  Well, since I had the source I went in and made the change, and voila, I'm back in business.

It gave me some confidence that if an open source project does cease, I can pick it up and patch it up.  I still don't want to manage multiple codebases from many different source, but in the end the pro open-source guys were right, "You have the source!"


 
Categories: .NET | ALT.NET | Musings | Open Source Software | Software

Yesterday I attended the first ever Iowa Code Camp in Iowa City, Iowa.  This was the first code camp I had ever attended and that fact withstanding, I don't know how the event could have gone any better, it was absolutely flawless.  There were well over 125 attendees and waiting list to boot.

I attended sessions on Java/Hibernate, Inversion of Control, Mocking and .NET Performance Tuning. I enjoyed Derik Whittaker's talk on mocking as it's something I've been into for the last few months.

Talking to other attendees it was very obvious that others enjoyed themselves as well.  The feeling was that the materials presented were things we can take into work tomorrow.  And that is what a code camp is all about.

Thanks to Chris, Javier, Greg S. Greg W and the many others who helped make yesterday a success, you guys set up a wonderful event!


 
Categories: .NET | CRIneta

April 19, 2008
@ 11:04 AM

From the moment we got here it's been so absolutely incredible.  We (Chris Sutton and I) arrived in Seattle about 11:00 and met up in our hotel lobby with a few guys and went off to lunch.  The subject of mocking came up and got into an interesting debate with the guys about mocking, among which was Roy Osherove.

I'm generally a nobody, but that's not how it feels here, everyone comes here to learn from others, so it actually tends to be a great group of developers.  Yesterday afternoon I was chatting with Udi Dahan, Greg Young, Drew Sellers, and Evan Hoff about event driven design.  I'm amazed that when surrounded by many celebreties in our community that they are really just like us (Roy O is the most down to earth guy).

The open spaces format is interesting, people get up and say what they want to talk about and then we figure out what will be talked about.  Some topics from Friday evening were mocking, agile scaling with teams, distributed design, and javascript testing, just to name a few.

A highlight was talking in a small group with Martin Fowler and Scott Hanselman about languages and the importance of finding good code to learn from.

All in all, I'm so far impressed and the conference really hasn't begun.  From the time people showed the conference began, despite it not officially beginning until 6:00 last night.  After the conference everyone went out to eat and this morning people are gathering for breakfast.

Ultimately one cool group of people that I'm proud to be a part of.

 


 
Categories: .NET | ALT.NET

March 10, 2008
@ 10:51 AM

The new Resharper seems to favor the "var" keyword and I don't understand why.  Is it some performance benefit?  To me, if you know the type, then write it as such.  Consider the following:

Person p = new Person("Tim", "Barcz");

Resharper doesn't like this and suggests the following:

var p = new Person("Tim", "Barcz");

Why?  Just because you can do something, I don't think you should.  Maybe my brain hasn't shifted back to a var world yet, but the second snippet is less readable than the first.  To me it's a case of Don't Make Me Think.  With "var", I now have to stop and think, even for a second, what type is being returned.


 
Categories: .NET | Musings | Software

imageI've thought about writing this post several times over the past two years.  Having had regular expressions come up three times last week, I thought it time to address the lack of programmers out there who understand regular expressions.  The sheer amount of fear surrounding regular expressions and the work that goes into avoiding them is astonishing.

Last year I used to troll around the asp.net forums and quite frequently I would answer the regex questions.  One question was posted which illustrates the problem with regexes among developers.

"...and i also i need to add a validator for the password textbox where the user is required to fill atleast [sic] 6 characters"

I suggested a solution to the problem using a regular expression validator. Making sure there are at least 6 characters, is a simple regex (example: \w{6,}), and yet my solution was met with skepticism.  The following was said, in the event a change was requested,

"Putting a new version of a web site can take a surprising amount of time than can go into man-weeks". 

Man-weeks?!?!?  To change a regular expression?!?!?  I see two problems, first the original developer who didn't know that regex would easily solve their problem.  The second problem is the other developer who doesn't know regex advocating his way as "the way", in effect, spreading his ignorance.  The first developer is easily forgiven, the second is not.

It's been said programmers can't program when faced with a simple FizzBuzz test, Imran states:

"Want to know something scary? - the majority of comp sci graduates can’t. I’ve also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution."

I'll pile on.  You want to know something scary?  The majority of professional programmers can't write regular expressions, even simple ones.  I'm not the first to say this.  Last year, at the ALT.NET conference, Scott Guthrie made the following statement when talking about routes in the new MVC framework:

"It's pluggable, so you can use Regexes...<some incoherent stuff>...if you wanna use regexes you can.  What we found is, regexes are super powerful, but only about 10% of people actually understand 'em."

Are regular expressions easy to understand? Well, let me ask you, was HTML easy when you started?  Were you born understanding the following HTML?

<fieldset class="CheckRadio">
    <div id="OngoingEventContainer">
        <input type="checkbox" id="OngoingEvent" name="OngoingEvent" value="1" />
        <label for="OngoingEvent">
            This is an ongoing event (no dates and times)
        </label>
    </div>
</fieldset>

If you understand the above, you didn't always.  My guess is that at some point you buckled down and learned HTML because you're job requires it.  Well, if you're a programmer, web or windows, you need to know regular expressions, your job requires it, it's that simple. 

imageRegular expressions have been around so long that they're deeply ingrained in many of the tools we use.  Christopher Bennage illustrates how regular expressions solved a recent problems in Visual Studio.  In a recent post he posts:

"Then I realized that I was missing the simple solution. Ctrl+F and a regular expression!"

I don't know that many people would be able to come to the conclusion that Christoper did.  It's my belief that regular expressions are fundamental, yet the average developer doesn't treat them as such.  They're ultimately doing themselves a disservice.

Regular Expressions are a tool that should be in every programmers bag.  If you don't understand regular expressions and do a google search every time you need a regular expression, shame on you!  It's time to bite the bullet and learn regular expressions.


 
Categories: .NET | Musings | Software

After a snowy weekend being stuck in Minnesota I was greeted by an email in my inbox saying that I was registered for the 2008 ALT.NET Open Spaces, Seattle conference.  Last year the Alt.NET generated a lot of post-conference buzz and was where the .NET MVC Framework was announced by Scott Guthrie.

After looking at the list of participants I'm gushing with enthusiasm.  I feel like a 14 year old freshman who was just asked to the homecoming dance by the homecoming queen.  For the sports enthusiast, I feel like Jason Kapono at the NBA All-Star game.  Kapono won the three point shootout, but many of you are probably asking yourselves, "who is Jason Kapono?"  Kapono, and his three-point skill, was overshadowed by the All-Star game itself and all of the NBA talent on the floor at one time.  I am Jason Kapono.  I must admit I have borderline unhealthy geek-love-man-crush on some of the attendees (listed in no particular order):

Sure, these guy go to conferences and it's not rare that they're in the same place.  What is rare, is that they're all together and there are only 150 participants.  That means the geek-expert to journeyman ratio is going to be quite high.  In other words, they can't avoid me.

Martin, will you autograph my POEA book?


 
Categories: .NET