Getting Started With Glimpse In ASP.NET MVC

If you are using ASP.NET, especially if you are using ASP.NET MVC, you need to be using Glimpse.

I’m currently working on a more exhaustive Pluralsight course on Glimpse, but I thought I’d write up a quick getting started tutorial here.

What is Glimpse?

Perhaps you haven’t heard of Glimpse yet, or you are just a little unsure of exactly what it is.

Glimpse is basically an open source and free diagnostics platform for the web.  Right now it works best with ASP.NET and especially ASP.NET MVC, but it can be extended to other platforms as well.  There is already work started for a PHP version and even a Python port.

What Glimpse essentially does is let you see diagnostics information about what is happening on your server directly in your page through a small diagnostics window completely rendered in JavaScript.

Out of the box, Glimpse can show you all kinds of information about your MVC application, like what routes are registered, what the flow was through the MVC pipeline and how the models were bound.

(BTW, if you are looking to brush up on your ASP.NET MVC 4 skills or learn about ASP.NET MVC 4, I recommend Professional ASP.NET MVC 4.  Great book, top notch authors.)

Here is what the Glimpse window looks like on a page.

Home_Page_-_My_ASP.NET_MVC_Application_-_Google_Chrome_2013-05-19_09-30-58

Glimpse is also fully extendable.

There are already plugins for Entity Framework, NHibernate, Ninject and many, many more

The best part about Glimpse is how easy it is to get setup.

I’ll walk you through the steps below.

Step 1: Get Glimpse from NuGet

All you have to do to get Glimpse installed is simply either:

  • Open up the Package Manager Console and type “Install-Package Glimpse.Mvc4” (or “Glimpse.AspNet if you aren’t using MVC)
  • Or, right click on your references, select Manage NuGet Packages, then search for Glimpse and find the appropriate Glimpse package.

GlimpseTutorial_-_Manage_NuGet_Packages_2013-05-19_09-44-14

One you’ve done that, Glimpse will automatically add a few entries to your web.config for you.

2013-05-19_09-46-18

2013-05-19_09-47-06

2013-05-19_09-49-21

Step 2: Turn on Glimpse

Turning on Glimpse is super easy.

Just launch your app and navigate to glimpse.axd.  Then, click “Turn Glimpse On” to set a cookie that will tell the Glimpse component running on the server to send you Glimpse data.

2013-05-19_09-52-16

Go to glimpse.axd

Glimpse_-_Configuration_Page_-_Google_Chrome_2013-05-19_09-52-38

Turn it on!

It’s that simple!

Step 3: Fire it up

Now all you have to do is navigate to any page in your application and you’ll see this little icon at the bottom right hand corner of the screen:

2013-05-19_09-55-28

If you click the icon, you’ll see the Glimpse panel, which currently looks similar to the Chrome Dev Tools panel.

Home_Page_-_My_ASP.NET_MVC_Application_-_Google_Chrome_2013-05-19_09-57-54

Using Glimpse

Each tab contains different diagnostics information about your application.

This data can be extremely helpful in troubleshooting problems and learning about exactly what is going on inside of MVC.

You can also find plugins that can be easily installed from NuGet.

For example, if you add the Entity Framework plugin, you’ll start seeing a tab that shows data about EF queries, like this:

2013-05-19_10-04-46

I’m pretty excited about Glimpse and its future.  Anthony van der Hoorn and Nik Molnar, the two creators and main maintainers for Glimpse, have done an excellent job transforming how we get diagnostics information for web applications.

One of the things I find most exciting about this platform is how easy it is to extend.  In my upcoming Pluralsight course, I walk you through creating a Glimpse plugin, which is surprisingly easy.

So if you haven’t checked out Glimpse, what are you waiting for?  Go do it now, it will take you about 5 minutes to get setup.

What do you think?  Are you using Glimpse already?  Post a comment and let me know.

My YouTube video for the week:

Dealing With Burnout

And here is the weekly Get Up and Code episode:

Get Up and CODE, Episode 2: Fitnesse And Nutrition Tips For a Busy Schedule

Implicit and Explicit Conversion Operators in C#

Recently I stumbled upon a pretty interesting feature of C# that I either neglected to really pay attention to before or just had entirely missed.

It is definitely debatable whether or not one should even use this feature, because it is likely to result in some confusing situations by someone reading your code even if they are aware of the feature’s existence.

Take a look at this code

Let’s look at an example that might look a bit strange.

What would you think if you stumbled upon this code?

Book book = new Book("Code Complete");
XDocument document = book;

 

new book

What if I told you that Book does not inherit from XDocument?

In this case a custom implicit casting is happening because of an implicit conversion operator I created on Book.

Here is how it is defined:

public class Book
{
        private readonly string title;

        public Book(string title)
        {
            this.title = title;
        }

        public static implicit operator XDocument(Book b)
        {
            // Code to convert the book into an XML structure
            return new XDocument();
        }

        protected List<Page> Pages { private get; set; }
}

 

What is happening in this case is that the compiler is noticing that I am trying to assign a Book object to a variable of type XDocument and that I have defined an implicit operator to allow that conversion.

By defining this implicit conversion operator I can assign any Book to an XDocument and it will execute the code defined in my implicit operator method to return an XDocument.

Backwards as well

I can also make the conversion the other way.

XDocument document = new XDocument();
Book book = (Book)document;

 

You can see here that I am doing something a bit different though.  In this case I am explicitly casting the XDocument into a Book.

I could have used implicit conversion, like the previous example, but not all XDocuments can automatically be converted to Books, so I wanted to make it allowed only if someone explicitly used the casting operator to perform the cast.

Here is what that code looks like:

 public static explicit operator Book(XDocument d)
{
	 // Code to convert the XML document into a book
    return new Book("");
}

 

Limitations

You can only use the implicit and explicit operators on classes that you have defined.  You can’t use them to extend existing classes to add automatic conversions.

Also the conversions can’t chain automatically.  If you have a conversion to type a Dog to a Cat and a Cat to a Mouse, you can’t assign a Dog directly to a Mouse.

Should I use it?

Now that is a tough question.  I have some mixed thoughts on actually using this feature.

My biggest problem with it is the discoverability.  When I look at code that is assigning a Book to an XDocument, I don’t immediately know where to look for the code that is allowing that assignment.  The code could actually exist in either the Book class or the XDocument class.  (We happen to know in this case that XDocument is a .NET class, so it’s not going to be there, but where you have to user defined classes, you can’t be sure.)

If I didn’t know about implicit and explicit operator overloads, I would be even more puzzled.

My other reservation is that in most cases it is not immediately obvious what exactly is happening.

  • Are we getting a copy of Book that is representing an XML structure?
  • Are we getting a raw XML document that could be populated with Book data?
  • Are we losing data here?

I can look at the method to figure out what is going on, but that makes the code that is using the implicit or explicit conversion less readable by itself.

It seems to me in that case having a method off of Book called ToXDocument() would make things at least a bit more clear.

On the other hand, I can definitely see some benefits to using these operators to make code more succinct and to make types that have obvious conversion easier to work with.

Consider having classes that represent temperatures in Celsius and Fahrenheit.  In those cases implicit conversion operators between the two formats makes intuitive sense.  We can also be pretty confident that the conversion would not result in a data loss.

termo

General guidelines

In general, my recommendation would be to avoid defining implicit and explicit operators because it is likely that most developers reading your code will be confused by them and in most cases you are not adding much value.

I would say that you should only use implicit and explicit operators when the conversion between two types is very clear because they are just different ways of representing the same value.

Although I can see the cases for other uses of the operators, it seems like there the usage is more likely to cause confusion than bring clarity.

To me an equal sign means assignment, I do not often think of it to mean conversion.

I could of course be wrong about my thoughts on implicit and explicit operators, but as of yet I haven’t seen it in the wild, so if you have some good examples of where it makes sense to use this feature, please let me now.

If you like this post don’t forget to Follow @jsonmez or subscribe to my RSS feed.

Introduction to MonoGame

I’ve been playing around quite a bit with MonoGame lately and thought I would take some time to write a bit about it and talk about how to get started.

I’m also currently working on a Pluralsight course on cross platform development with MonoGame.

MonogameLogo100x100

What is MonoGame?

Well, if you are familiar with XNA, then you already know what MonoGame is.

If you are not familiar with XNA though, it is basically a game development framework that allows for creating games quickly without having to write all that repetitious code that all games need.

Basically it makes creating games more about the game and less about the technical details.

The only problem with XNA is that it only really works for Windows, XBox360 and Windows Phone 7.  If you want to create a game on Android and iOS, you can’t use XNA.

This is where MonoGame comes in.  MonoGame is an open source port of the XNA framework that can run on many more platforms that Microsoft’s XNA.

Great, so what does this actually mean?

Well, if you are interested in game development, especially if you are interested in game development for the most popular platforms today, MonoGame might be able to help you to write pretty close to the same exact code and have it work on Android, iOS, Windows 7, Windows 8, Windows Phone 7, MacOS, XBox 360, Linux and the new Playstation console.

That is pretty awesome!  Especially if you are trying to monetize your effort.

In my mind MonoGame helps overcome two huge barriers to getting into game development.

  1. Difficulty of monetizing the effort.  By allowing the same code to be shared on most platforms, a game developer can get paid for their effort in multiple marketplaces.
  2. Not knowing where to get started.  The XNA API is so simple to use that you can get a simple game, like a Pong clone for example, up and running in about a couple of hours.

Also, because MonoGame is basically just XNA, you can find a whole host of resources on how to develop a game using the platform.

In my upcoming Pluralsight course, I show how to create a Pong clone on Windows and then we get that game up and running on Android, iOS and Windows Phone 7, with minimal changes.

dgun-853-50-games-pr-h

Getting started

It can be a bit challenging to find good information to get started in each platform using MonoGame, but the basics are located on the Github page.

For the Windows tutorial there, you can use Visual Studio instead and use the MonoGame installer.

For each platform things area slightly different, but really not all that hard.  If you want to have your game run in Android and iOS, you’ll need Mono for Android and MonoTouch respectively.

For Android development, you can use Visual Studio as long as you have Mono for Android installed and all you really need to do is link your files from your Windows project and create a small bit of startup code in an Android Activity to start the game.

For iOS development, you will need to use MonoDevelop, which is packaged with the install of MonoTouch.  MonoTouch itself uses XCode and the iPhone SDK, so you have a bit more installing to do there, but the idea is pretty much the same.  One you have MonoTouch running on your Mac, you can link over the files from your Windows project, add a small bit of startup code, and you are up and running.  (You’ll also need to download the actual MonoGame source code to add to your project, since there isn’t an installer for Mac currently.)

Xamarin also has a seminar they did on MonoGame to help you get started.

True cross platform development, finally

At least for game developers.  For other applications in the mobile space, there are some solutions that help you share your code, but nothing that really allows you to have near 100% portability without a big sacrifice.

I was pretty amazed the first time my game just ran on my Android and iOS devices with virtually no changes.

I’d definitely encourage you to check out MonoGame and stay tuned for my Pluralsight video on the topic, where I will go through all the details of creating a game and getting it running on most of the major platforms.

Book Review: C# in Depth Second Edition

Been staying pretty busy lately, so I haven’t been reading all that much, but I did just finish reading C# in Depth Second Edition by Jon Skeet.

skeet2_cover150

This book is basically a coverage of all the major features of the C# language that have changed since the first edition of C#.

It is a pretty long book, but it covers a pretty large topic and it does indeed cover it “in depth.”

I debated whether it was worth my time to read this book, since I already had a good grasp of most of the C# language, but I am definitely glad I did.  There are many very detailed concepts that Jon does an excellent job of explaining which make other language concepts seem much simpler.

The book is basically a forward progression through the advances of C# through each major revision.  Jon does an excellent job of presenting not just the what, but the how and whys for each language revision.

The developer that has at least a decent knowledge of the C# language will get the most out of this book, as it can get a bit tricky and complex at times.  Definitely is a book for advanced developers as well, who will most assuredly learn something about the language they didn’t know.

If you’ve watched any of my Pluralsight courses, you know that I like to teach in a very informal and conversational way, and it seems Jon Skeet also takes this approach and makes this highly technical book quite readable.

Good:

  • Very excellent and detailed coverage of language features of C#.
  • Excellent verbal illustrations to help simplify some complex topics and make them memorable.
  • Down to earth conversational approach to the material makes it a joy to read.
  • The coverage on LINQ is phenomenal.
  • Book builds in progression on previous examples and chapters very naturally.
  • It is very obvious great detail went into making and planning out this book.  Rare to see today.

Bad

  • Coverage of dynamics and DLR is a bit dry.  The topic is very complex and I felt like the book launched in a bit too fast.
  • Sometimes I felt like Jon was a bit too objective in presenting his opinion.  I generally trust the values and opinions of a skilled developer like Jon Skeet, so I would rather have his opinions be presented a bit more firmly in the book.

What I learned:

First off, a whole lot more than I would have expected.

There are many aspects to the C# language that I thought I understood fairly well, but had never turned down one dark little corridor.  This book made me turn down those corridors and face the demons there.

Specifically, I thought I understood how LINQ providers worked.  I never really looked into one, because I had an assumption about how a LINQ provider would work based on what I knew of the language.  I found out that I was wrong in my assumptions and I now have a much more thorough understanding of LINQ and how all the pieces of the language fit together to make it work.

I also learned quite a bit about dynamics and the DLR.  Although it was a bit painful, I felt like the book got me to reconsider my stance on dynamics just a bit and consider some places in the statically typed C# language where they might make sense.  (Understanding how dynamics work reduced them to the same level as any reflection based code in my mind.)

Overall, I would highly recommend this book.  My only two negatives about the book should not dissuade you from reading it.  A beginner or intermediate C# developer could easily raise both their skill level and knowledge of C# considerably just by reading this book, and any advanced C# developer should have plenty to learn from it as well.

Types of Duplication in Code

One of the biggest reasons to refactor code is to eliminate duplication.  It is pretty easy to introduce duplication in our code either unintentionally or because we don’t know how to prevent or get rid of it.

The three types of duplication

I’ve found that there are three basic types of duplication that we can eliminate from our code that successfully build on each other.

  • Data
  • Type
  • Algorithm

Most developers tend to get stuck at the data level, but in this post, I will show you how to recognize type and algorithm duplication and refactor it out of your code.

duplicate-content

Data duplication

The most basic type of duplication is that of data.  It is also very easily recognizable.

Take a look at these methods:

public Position WalkNorth()
{
   var player = GetPlayer();
   player.Move("N");
   return player.NewPosition;
}

public Position WalkSouth()
{
   var player = GetPlayer();
   player.Move("S");
   return player.NewPosition;
}

public Position WalkEast()
{
   var player = GetPlayer();
   player.Move("E");
   return player.NewPosition;
}

public Position WalkWest()
{
   var player = GetPlayer();
   player.Move("W");
   return player.NewPosition;
}

 

Pretty easy to see here what needs to be refactored.

Most developers don’t need any help to realize that you should probably refactor this code to a method like the following:

public Position Walk(string direction)
{
   var player = GetPlayer();
   player.Move(direction);
   return player.NewPosition;
} 

 

In this example data is duplicated.  To be specific the string data of the direction passed into move is duplicated.  We can eliminate that duplication by creating a method that parameterizes the differences represented by that data.

Type duplication

Now, data duplication is where a majority of developers stop, but we can go much farther than that.  In many cases the difference between two methods is only the type in which they operate on.

With the use of generics in C#, we can refactor out type and parameterize this concept as well.

Look at this example:

public int FindIntMatch(int i)
{
   var match = (int)container.Get(i);
   return match;
}

public string FindStringMatch(string s)
{
   var match = (string)container.Get(s);
   return match;
}

 

Here we have two method that do pretty much the same thing, but they just differ on the type they operate on.  Generics gives us the ability to actually refactor out that type information just like we would with data.

public T FindMatch(T t)
{
   var match = (T)container.Get(t);
   return match;
}

 

By refactoring to the above method we have eliminated duplication. We have achieved this by refactoring out type.

Algorithm duplication

Without a good understanding of delegates and functional programming, few developers ever even consider refactoring out algorithm duplication, but it can be done fairly easily.

Take a look at this example:

public void GoForRun()
{
   GetDressed();
   Run();
   Shower();
}

public void LiftWeights()
{
   GetDressed();
   Lift();
   Shower();
}

 

It is a pretty basic example, but it highlights the kind of duplication that I often see left in many code bases.  Delegates in C# allow us to treat functions like data.  With this ability we can easily refactor out the commonality in these two method to get something like this:

public void DoFitnessActivity(Action activity)
{
   GetDressed();
   activity();
   Shower();
}

 

We could have also refactored out this duplication by using an abstract base class and having the inherited classes definite their own fitness activity, but using delegates creates a much simpler approach and casts the problem in the same light as refactoring any other type of data.

Combining them together

Often I find that several different types of duplication are present across several methods in a class.

When this is the case, it is often possible to apply data, type and algorithm duplication refactoring techniques to find the most simple and elegant solutions.

I’ve also found this is a skill that must be practiced.  When I first really started using generics and delegates in C#, I had a hard time finding uses for them, because I could not easily recognize the patterns of duplication that called for them.  But, I found over time that it became easier and easier to recognize where these techniques could be applied to reduce duplication in my methods.

I’ve also found the key to eliminating duplication is sometimes to first exaggerate it.  Often I will purposely take two methods that I know have some duplication and make them look even more duplicated in order to be able to clearly see where the duplication lies.  I may do several small refactoring steps to get to the point where it is easy to identify what data, type or algorithm is being repeated.

Wrapping Callbacks

I’ve recently had the problem of trying to display a progress dialog when executing an asynchronous operation and to dismiss that progress dialog when the operation completes.

I wanted to build a way to do this that is generic to my application, so that it would work with any asynchronous operation in order to reduce duplication of writing progress dialog logic everywhere in the code.

11-290x300

Looking at the problem

So here is some basic pseudo-code of the problem.

public void DoCall()
{
   ShowProgressDialog();
   RemoteService.DoAsync(CallBackMethod);
}

public void CallBackMethod(Result result)
{
    HideProgressDialog();
    // Process result;
}

Now the problem with this code is that it would have to be repeated everywhere I want to make an asynchronous call and display a progress dialog.

If I want to do this in my application every time that I make an asynchronous call, I have to put this kind of code in many places in the application.

You can also see a mixing of responsibilities here.  We are handling UI related showing of a progress dialog split between an initial call and the callback.  It just seems a bit dirty to do things this way.

Breaking it down

So how can we solve this problem?

Go ahead and think of some way that you might be able to solve this.

One of the best ways that I have found to solve any problem like this is to work backwards.

Let us assume that any syntax we can think of is possible, and then only change the ideal syntax if it proves to not be possible.

What do I mean by this?

Simple, let’s come up with the way we want this code to look and we will worry about implementing it later.

It would be nice to be able to execute an asynchronous method and display a progress dialog with a one-liner, like so:

UIServiceCaller.ExecuteAsync(RemoteService.DoAsync, CallBackMethod);

If we could just do this wherever we want to make an asynchronous call and automatically have the progress dialog shown and dismissed, life would be wonderful.

Solving the problem

In order to solve this problem, we can do something very similar to a decorator pattern.

We can basically just wrap our callback method with a new callback that adds the functionality of dismissing our progress dialog.

So the idea will be that we will do the following steps in our ExecuteAsync method:

  1. Show the progress dialog
  2. Wrap our callback with one that dismisses our dialog and then executes the callback.
  3. Execute our asynchronous operation passing the new wrapped callback as the parameter.

gift-wrap-nature-lovers-easy-style-fabric-wrapping-1211-l

Here is what this looks like in code:

public static void ExecuteAsync(Action<Action<Result>> asyncMethod, Action callback)
{
   ShowProgressDialog();

   Action wrappedCallback = (r =>
   {
      DismissProgressDialog();
      callback(r);
   }

   asyncMethod(wrappedCallback);
}

This code actually looks more complicated than it really is.

You will need to understand how Action works though.  If you don’t, check out this post I did explaining Action and Func.

Understanding the solution

It can be a bit hard to wrap your head around Action of type Action of type Result.

Let me translate this to make it a bit easier.

The first parameter to ExecuteAsync is a method that takes another method as a parameter (the callback,) which takes a Result object as a parameter.

Go ahead and read that over until you get it.

So, the idea here is that we are passing in the method that is going to do the callback as the first parameter to your ExecuteAsync method.

Then we are passing in our actual callback as the 2nd parameter to ExecuteAsync.

The idea is that we are splitting apart the method and the callback it takes, so that we can insert our code to handle the dialog where we need to.

Now we can just call ExecuteAsync and pass it our method and its callback and progress dialog code will automatically be handled for us.

Building on the idea

We can expand upon this concept in several ways.

One thing we could do is also apply error handling logic to the callback wrapper method.  We could preprocess the result in some way before passing it to the callback.  This could allow us to display an error message or even retry a number of times before executing the callback.

Another thing we could do is to change the signature of the ExecuteAsync method so that it takes a type T instead of Result; this would allow us to handle any kind of return type and method, and the ExecuteAsync method would work with just about any asynchronous method call.

MonoTouch

I’ve been so busy lately that I have neglected to write about a great platform for developing iOS applications called “MonoTouch.”

I recently released a new course on MonoTouch at Pluralsight.

I wanted to take a bit of time here to talk about MonoTouch and to tell you why you should be using it instead of developing iOS applications in Objective-C

text-monotouch

Flipping directions

GoPhoto_0197_Scanned-Image-00363

When I first started developing with iOS, I firmly believed that the job should be done using the tools that Apple provided.

I still think it is a very good idea to learn Objective-C and how to develop an iOS application using Objective-C and XCode.

But I am convinced now that overall MonoTouch is the way to go.

Objective-C is a decent language, but it has a fairly steep learning curve for a C# or Java developer.  XCode, the IDE for developing iOS applications, is a decent IDE, but it is not nearly as powerful as MonoDevelop or Visual Studio.

The reality of the situation is that Apple’s development platform is still back in 1990.  Even though there have been some changes and growth, I firmly believe now that Objective-C and the underlying technology cannot ever catch up to .NET or Java.

I don’t say this lightly.  As I said, before I developed a fairly large application in Objective-C.  I authored a Pluralsight course on iOS development with Objective-C.  I was pretty convinced this was the way to go until I gave MonoTouch a try.

An unfair test

I really gave MonoTouch an unfair test, but it passed anyway.  I set out to learn, configure, build a MonoTouch application, and deploy it to the Apple App Store in 1 weekend.

I figured if MonoTouch could pass this test then I would immediately save more than the $400 cost for the software since the next application I was going to build was going to probably take at least a week worth of time to build in Objective-C.

MonoTouch easily passed my test and really exceeded my expectations.

The main advantage

By and far the main advantage in using MonoTouch is the language.

C#’s ability to wire up events through event handlers and delegates makes working with iOS so much easier.

There are many situations in iOS where you have to create a special class to act as a delegate for providing behavior for various iOS controls and classes.  In C#, many of these delegate classes can be replaced by a C# delegate or lambda expression.

Another really painful situation in Objective-C is memory management.  If you aren’t used to tracking memory usage it takes a bit to get adjusted to it in Objective-C.  Sure, it really isn’t that hard, but once I started working with C# to build my iOS application, I realized how much faster I could fly through the code without having to even think about it.  (The newer version of Objective-C has somewhat built in memory management, but it is not a true garbage collection implementation.)

Along with C#, you get the full power of the .NET framework.  Almost all of the base class libraries from .NET are available in MonoTouch.  (You basically have the silverlight .NET profile.)

This really comes in handy in 3 main areas:

  • Working with XML
  • Working with databases
  • Calling web services

If you try to do these things in Objective-C, it is possible, but it will hurt like hell.

Give it a shot

If you are interested in developing iOS applications and you haven’t tried MonoTouch, go give it a try.  Trust me, it is worth the effort.  One of the big factors that had me developing Android applications and shying away from iOS was the hurdle of trying to learn and work with Objective-C.

MonoTouch lets you reuse your C# skills without any extra overhead, since the application is compiled down to native ARM assembly code.

If you don’t know where to get started or want to learn a little bit more about MonoTouch, feel free to check out my course on Pluralsight.

Kudos to the Xamarin team for building such a great product!

(BTW, that photo is me flipping.  Actually it is a thing I used to call “throwing myself at the ground for dramatic effect.”)

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out ElegantCode.com where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.

Making Switch Refactorings Better – Defaultable Dictionary

I’ve written before on the idea of refactoring a switch to a Map or Dictionary.

There is one major problem that I have been running into though.  Switch statements and dictionaries are not functionally equivalent for one major reason…

Switches allow for default

I kept struggling with this when I would implement a dictionary to replace a switch.  How can I deal with the default case?

There are of course many ways to deal with the default case in a dictionary or map, but I didn’t really like any of the solutions because they either required me to remember to check to see if my entry was in the dictionary before looking it up, or to rely on catching an exception.

Let me give you an example:

switch(vegetables)
{
	case Vegetables.Carrot:
		DoCarrotStuff();
		break;

	case Vegetables.Spinach:
		EatIt();
		break;

	case Vegetables.Peas:
		FeedToDog();
		break;

	default:
		Butter();
		Salt();
		SprinkleCheese();
		Eat();
}

Converting this to a dictionary we get something like:

var vegetableActionMap = new Dictionary<Vegetable, Action>
{
	{ Vegetable.Carrot, () => DoCarrotStuff() },
	{ Vegetable.Spinach, () => EatIt() },
	{ Vegetable.Peas, () => FeedToDog() }
}

Action result;
if(!vegetableActionMap.TryGetValue(vegetable, out result)
{
     Butter();
	  Salt();
     SprinkleCheese();
     Eat();
}
else
   result();

So clunky, just to handle the default case.

Would be much better do something like this:

var vegetableActionMap = new Dictionary<Vegetable, Action>
{
	{ Vegetable.Carrot, () => DoCarrotStuff() },
	{ Vegetable.Spinach, () => EatIt() },
	{ Vegetable.Peas, () => FeedToDog() }
}.WithDefaultValue( () => { Butter(); Salt(); SprinkleCheese(); Eat(); });

vegetableActionMap[vegetable]();

Well now you can!

Enter DefaultableDictionary!

Also the first thing I ever put on GitHub!

The idea is pretty simple, I am just creating a decorator for IDictionary.

The DefaultableDictionary has a constructor that takes an IDictionary and a default value.

It then delegates all of the methods to the passed in IDictionary reference.  For the methods that look up a value, it handles returning the default if the key doesn’t exist in the dictionary.

I created an extension method that lets you just put a .WithDefaultValue() on the end of your dictionary declaration in order to auto-magically give you a DefaultableDictionary back with that default value.

Sleep well my friend

Knowing that you can not create a dictionary that has a default value which is returned instead of throwing an exception if the key passed in is not found.

I have no doubt that in 3rd world countries children are still starving, but in 1st world countries children with VS Express hacking away at iPhone applications using MonoTouch will not have to catch exceptions from dictionaries that do not know how to just return a default value.

So now there is no excuse!  Refactor those switches!

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out ElegantCode.com where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.

Using Var + As, a Neat Little Trick

Perhaps this is something everyone already knew about, but I recently came across this little C# combo that solves one of my major outstanding issues with the var keyword.

I consider var to actually be quite a useful language feature to reduce repetition and make your code slightly more flexible for refactoring, but I’ve always had one little problem with it.

What if I want a base class type or interface?

I most often run into this problem when I am working with lists.

Have you ever written some code like this?

var myList = new List<int>();

 

The problem with this code is that we are stuck with the concrete List implementation for our variable myList, because we don’t have a way of specifying that we actually want an IEnumerable to be our reference type.

The solution is so simple that I am a bit surprised I didn’t think of it earlier.

I had always assumed that I just couldn’t use var there and would have to declare the type like so:

IEnumerable<int> myList = new List<int>();

 

But we can actually just use as to keep our var in place if we want to.

var myList = new List<int> as IEnumerable<int>

 

So it’s actually a little more verbose, but I think it is a bit more clear, and it is more consistent if you are using var everywhere else.

There has to be a better use

I’ve been racking my brain trying to come up with more useful ways to use this little combo, but I can’t really seem to come up with anything.

It seems like there has to be something else you could use this combo for.

What do you think?  Any ideas?

Refactoring Switches Advanced

KevDog posted a question in response to my post Pulling out the Switch: It’s Time for a Whooping and I thought it would be good to go ahead and answer it as a post since it is a pretty interesting real world example of a somewhat difficult switch statement to get rid of.

Here is the original code.

public static DataFileParser GetParser(DataFile dataFile)
{
    switch ((FileType)dataFile.ValidationFormat.FileType)
    {
        case FileType.PDF:
            return new PdfParser(dataFile);
        case FileType.Image:
            return new ImageParser(dataFile);
        case FileType.CsvWithHeaderRow:
            return new CsvParser(dataFile, true);
        case FileType.Csv:
            return new CsvParser(dataFile, false);
        default:
            throw new NotImplementedException("There is no parser for " + 
dataFile.ValidationFormat.FileType.ToString());
    }
}

 

Surprisingly simple solution

Try and say that 3 times fast.

I thought about this a bit and at first was having a hard time coming up with a solution.  Then I typed the code into an editor and realized how easy it is.

The trick here is that it looks like something other than the simple case of data mapping to logic, but it isn’t.

  • The logic in this case is the creation of the Parser. 
  • The data is the file type.

Once you think of it in those terms you can easily solve it using the pattern I mention in my previous post on the subject

Switch be gone!

private static Dictionary<FileType, Func<DataFile, DataFileParser>> DataFileTypeToParserCreatorMap = 
    new Dictionary<FileType, Func<DataFile, DataFileParser>>()                                                                                            
{ 
    {FileType.PDF, file => new PdfParser(file)},
    {FileType.Image, file => new ImageParser(file)},
    {FileType.CsvWithHeaderRow, file => new CsvParser(file, true)},
    {FileType.Csv, file => new CsvParser(file, false)}
};

public static DataFileParser GetParserRefactored(DataFile dataFile)
{
    Func<DataFile, DataFileParser> parserCreator;
    if(!DataFileTypeToParserCreatorMap.TryGetValue(
                             dataFile.ValidationFormat.FileType, 
                             out parserCreator))
        throw new NotImplementedException("There is no parser for " +
            dataFile.ValidationFormat.FileType.ToString());

    return parserCreator(dataFile);
}

 

That is the quickest solution that preserves the existing code as much as possible.

Another solution

With the first solution we pushed the object creation into the map.

If we can make the constructor for all the parsers the same, we can use reflection to dynamically create our instances by looking up the type in the dictionary.

In this example, I assume that we have refactored CsvParser to have a constructor that only takes one parameter and internally sets a value of usesHeader to false, and we have created a CsvWithHeaderParser that inherits from the CsvParser and sets usesHeader to true.

private static Dictionary<FileType, Type> DataFileTypeToParserTypeMap = new Dictionary<FileType, Type>()
{
    { FileType.PDF, typeof(PdfParser)},
    { FileType.Image, typeof(ImageParser)},
    { FileType.CsvWithHeaderRow, typeof(CsvWithHeaderParser)},
    { FileType.Csv, typeof(CsvParser)}                 
};

public static DataFileParser GetParser(DataFile dataFile)
{
    Type parserType;
    if(!DataFileTypeToParserTypeMap.TryGetValue(
            dataFile.ValidationFormat.FileType, 
            out parserType))
        throw new NotImplementedException("There is no parser for " +
                    dataFile.ValidationFormat.FileType.ToString());

    return (DataFileParser) Activator.CreateInstance(parserType, dataFile);
}

 

Pretty similar solution.  I prefer the first though for several reasons:

  • The refactor is localized, where the second solution has to touch other classes.
  • Reflection makes you lose compile time safety.
  • You may create a new parser that you want to have more parameters for the constructor.  With the second solution, you will have a hard time doing that.
  • The first solution gives you ultimate flexibility in setting up the constructor of the parser.  If you wanted to do 5 steps for a particular parser, you could.

Anyway, next time you run into a switch statement that is hard to figure out how to refactor, try to break it into a mapping between data and logic.  There is always a solution.

As always, you can subscribe to this RSS feed to follow my posts on Making the Complex Simple.  Feel free to check out ElegantCode.com where I post about the topic of writing elegant code about once a week.  Also, you can follow me on twitter here.