Another reason to love Resharper: it can make you look like a LINQ-ninja

For those of who spend our time immersed in code, we're usually trying to find ways to write better code that more clearly expresses our intent.  And in a place like EMC Consulting there is a very healthy competition between devs to write code that is better, cleaner, faster, etc.  One of the new features of Resharper 5.0 (R#) manages to address both of these points!  [:D]

Jetbrains have given R# a pretty deep understanding of LINQ.  To be honest, I'm feeling like R# knows LINQ considerably better than I do!  You see, R# 5.0 will offer to convert your code into LINQ statements wherever it can.  Here's an example:

My code:

   1: foreach(var summaryType in TypeMapper.GetMapper(entityType.Assembly)
   2:           .GetSummaryTypes(entityType))
   3: {
   4:   if(typeof(VersionableSummaryBase).IsAssignableFrom(summaryType))
   5:   {
   6:     var summary = (VersionableSummaryBase)EntityCache.Instance.RetrieveIfCached(id, summaryType);
   7:     if (((IVersionable)entity).Version < summary.Version)
   8:     {
   9:        mustReload = true;
  10:        break;
  11:     }
  12:   }
  13: }

Applying the R# suggestion:

   1: mustReload = TypeMapper.GetMapper(entityType.Assembly)
   2:                  .GetSummaryTypes(entityType)
   3:                  .Where(summaryType => typeof(VersionableSummaryBase).IsAssignableFrom(summaryType))
   4:                  .Select(summaryType => (VersionableSummaryBase) EntityCache.Instance.RetrieveIfCached(id, summaryType))
   5:                  .Where(summary => summary != null)
   6:                  .Select(summary => summary.Version)
   7:                  .Any(summaryVersion => ((IVersionable) entity).Version < summaryVersion);

 

Even without understanding what my TypeMapper class is doing, or any of the other details you can clearly see, I think that the second version is easier to read and more clearly expresses the underlying algorithm.  If you have an opinion on this, then please leave it in the comments ... I'd love to get other views.

Here's another gem from R#.  My code:

   1: var sourceElements = new Dictionary<int, EntityBase>();
   2: foreach (EntityBase element in collectionFromSource)
   3: {
   4:     sourceElements.Add(element.InternalID, element);
   5: }

And the R# version:

   1: var sourceElements = collectionFromSource
   2:                         .Cast<EntityBase>()
   3:                         .ToDictionary(element => element.InternalID);

I didn't even know that that particular extension methods existed until R# suggested I use it!  And perhaps with R# 5.0 in my toolkit, I'll be able to get the edge over some of the other devs at work.  At least, until someone blogs about it ... oh bother!

December 2 2009
blog comments powered by Disqus