Register Login

 

Welcome to the Coach Factor blog. Here you will find all of our ideas on software development. Subscribe at  http://blog.nventive.net.

# Monday, May 12, 2008

Hopefully, after reading Part 1, Part 2, Part 3, Part 4 and Part 5, you should've become an Extension Method Master.

But there's more. There are other elements that can be simplified by using extension methods and that is, limiting usage of reflection.

Given something like:

public interface IServiceLocator

{

  T Resolve();

}

 

It is important to notice that the generic method Resolve has a type parameter for the sole purpose of providing the type to resolve. There are NO constraints.

One might use the service locator as follows:

public ILogger GetLogger()

{

  ILogger logger = serviceLocator.Resolve<ILogger>();

 

  return logger;

}

But what if the type to resolve is only known at runtime? You'll have to fallback on reflection:

public static class ServiceLocatorExtensions

{

  public static object Resolve(this IServiceLocator locator, Type type)

  {

    MethodInfo resolveMethodInfo = typeof(IServiceLocator).GetMethod("Resolve");

    resolveMethodInfo = resolveMethodInfo.MakeGenericMethod(type);

 

    return resolveMethodInfo.Invoke(serviceLocator, null);

  }

}

This approach can have terrible performance, especially since there is no reflection cache.

A far better approach is to define your IServiceLocator interface as a non-generic interface and provide strongly-typed extension methods:

public interface IServiceLocator

{

  object Resolve(Type type);

}

and

public static class ServiceLocatorExtensions

{

  public static T Resolve(this IServiceLocator locator)

  {

    return (T)locator.Resolve(typeof(T));

  }

}

 

Thoughts?

powered by metaPost

Monday, May 12, 2008 2:04:40 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | .net - Extension Methods
# Wednesday, April 30, 2008

Finding tools that can help you through your daily SCRUM meeting can be a hard task. Other than the usual rubber football that allows a person to speak, nothing else seemed interesting, that is until last week.

I was aimlessly surfing on CodePlex when I found TFS Sticky Buddy. It's a great way for your team to "see" the iteration. It's a small WPF program that visualizes the work items contained in a TFS Team Project.

TFS Sticky Buddy

As soon as I have time, I will try to implement this tool within my teams, because I believe that it is a nice way to focus the team, during the SCRUM meeting, on the iteration.

Wednesday, April 30, 2008 2:06:04 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Process

Yesterday I was helping somebody with a small WCF application and one of the tools I proposed was a plugin visualizer for Visual Studio called WCF Visualizers. It's available freely on CodePlex and will allow you to see different parts of WCF (messages, endpoints, channels...) while you are debugging. Go and check it out, as there are some great images on the project page. The next time I give a WCF presentation with Francois at different user groups, I will also take the time demo this tool.

Wednesday, April 30, 2008 2:05:22 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net
# Monday, April 21, 2008

nVentive was present in Quebec city at HEROES happen {here}, Microsoft's launch for Visual Studio.Net 2008, SQL Server 2008 and Windows Server 2008.

François and I were experts there on the developer side of things, and the one thing we got asked the most, were questions on LINQ.

Everybody knows that LINQ is the hot new way to query objects in C# using a syntax similar to SQL. It depends on 2 tricks, Extension Methods and Lanbda Expressions.

This is a small sample.

public class Blog

{

   public string Title { get; set; }

}

class Program

{

   static void Main(string[] args)

   {

      IList<Blog> blogs = new List<Blog>();

      blogs.Add(new Blog { Title = "3 cheese lasagna" });

      blogs.Add(new Blog { Title = "Blue cheese alfredo sauce" });

      blogs.Add(new Blog { Title = "Macaroni and cheese" });

      blogs.Add(new Blog { Title = "Angel cake" });

 

      var blogsWithCheese = from blog in blogs

            where blog.Title.ToLower().Contains("cheese")

            select blog;

      //blogsWithCheese contains 3 elements.

   }

}

You can query something that is IEnumerable with LINQ to Objects, or a database itself using LINQ to SQL. If XML is your thing, there is a LINQ to XML variant and let's not forget that there is adapter to query Ado.Net DataSets. If you've heard of Entity Framework, LINQ will also work there to abstract it's object SQL language.

Now there's still more, if you have a source that you'd like to query with LINQ, it's just a matter of implementing IQueryProvider and IQueryable.

There are 2 tools I recommend you use in your adventures with LINQ:

  1. LINQPad is a interactive LINQ learning tool. Check it out, you'll never go back into Query Analyzer after that.
  2. Visual LINQ Query Builder is a plugin for Visual Studio 2008 that will help you develop your queries with a designer, now that's practical.

Monday, April 21, 2008 8:33:18 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | Announcement
# Saturday, March 29, 2008

We've covered a lot so far with Part 1, Part 2, Part 3 and Part 4 of this adventure with extension methods.

Looking back at it, there are some nifty features and side effects that might have been overlooked.

With the magic of generic methods and compiler type inference, we are able to get a pretty discoverable and predictable api.

Let's look at the test first:

  [Fact]

  public void GetProperty()

  {

    DateTime now = DateTime.Now;

 

    Assert.Equal(now.Day, now.Reflection().GetProperty("Day"));

  }

What's in there? Well first we see that there is a Reflection() extension point, and this typed extension point has a GetProperty method. This makes it really EASY to figure out what can be done by reflection.

What should the code look like?

Let's start by the extension point class that will scope all available reflection methods:

  public class ReflectionExtensionPoint

  {

    public T Instance { get; set; }

  }

The ReflectionExtensionPoint class is generic so it can hold the type for which we want to use reflection. So we don't have to instantiate it manually all the time, we can create an extension method that will create such an instance

  public static class ReflectionExtension

  {

    public static ReflectionExtensionPoint Reflection(this T instance)

    {

      return new ReflectionExtensionPoint { Instance = instance };

    }

  }

Here lies all the magic. Since the method is generic and there are no constraints define, we can use the Reflection extension method on anything. Furthermore, there is no need to specify the generic type argument as it is automatically inferred by the compiler

This allows for a pretty compact syntax as shown here:

  [Fact]

  public void ReflectionExtensionPoint()

  {

    DateTime now = DateTime.Now;

 

    ReflectionExtensionPoint<DateTime> extensionPoint = now.Reflection();

 

    Assert.NotNull(extensionPoint);

    Assert.Equal(now, extensionPoint.Instance);

  }

Now that we have an extension point almost for free that represents a clear and very predictable subset of functionality, we can extend-the-extension-point to add additional behaviors.

  public static class ReflectionExtension

  {

    public static ReflectionExtensionPoint Reflection(this T instance)

    {

      return new ReflectionExtensionPoint { Instance = instance };

    }

 

    public static void SetProperty(

      this ReflectionExtensionPoint extensionPoint,

      string name,

      object value)

    {

      PropertyInfo propertyInfo = typeof(T).GetProperty(name);

      propertyInfo.SetValue(extensionPoint.Instance, value, null);

    }

 

    public static object GetProperty(

      this ReflectionExtensionPoint extensionPoint,

      string name)

    {

      PropertyInfo propertyInfo = typeof(T).GetProperty(name);

      return propertyInfo.GetValue(extensionPoint.Instance, null);

    }

  }

Of course, extending the generic ReflectionExtensionPoint class, we need to make our extension methods generic as well so that we can propagate the extended type.

By now, unit tests should turn green, and we should be looking for next bits of business value to provide.

powered by metaPost

Saturday, March 29, 2008 1:59:11 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | .net - Extension Methods
# Friday, March 28, 2008

If you haven't read Part 1, Part 2 and Part 3 of this serie, go ahead, we'll wait right here.

In the previous post, we suggested that you can move instance methods that represent overloads to static extension methods.

It's been known for a while that static methods don't do well. They infer with most OO principles and are barely testable. Some will even define those as evil.

Selfishness

When you look at the definition of evil, it is used to indicate acts that are selfish.

Static Methods are selfish in the sense that they keep implementation details for themselves. They take control and keep it. They won't allow you to replace them with a mock version for test purposes. They won't allow their behaviour to be modified without digging into the inner guts and recompiling. They can't be decorated, they can't be proxied, they're selfish.

But can't we have both? The ease and greatness of extension methods without the selfishness and lack of testability of static methods?

Well yes you can... Sort of...

Let's start by looking at an extension method we previously developed:

public static class TypeExtensions

{

  public static bool Is<T>(this Type type)

  {

    return typeof(T).IsAssignableFrom(type);

  }

}

 

It contains almost no code but still, it can't be mocked nor replaced.

Make everything an instance again

In order to replace the implementation of this method with another one, we simply need to

1-Extract this method into an interface

public interface ITypeExtensions

{

  bool Is<T>(Type type);

}

2- Provide a default implementation.

public class DefaultTypeExtensions : ITypeExtensions

{

  public bool Is<T>(Type type)

  {

    return typeof(T).IsAssignableFrom(type);

  }

}

3- Make sure the extension method delegates to the instance method

public static class TypeExtensions

{

  public static ITypeExtensions Extensions = new DefaultTypeExtensions();

 

  public static bool Is<T>(this Type type)

  {

      return Extensions.Is<T>(type);

  }

}

Compromise

On the sunny side, we are now able to completely test our extension method implementation. It can also be mocked as we've extracted an interface. It can be replaced or decorated with a Thread-safe version.

On the dark side, you need to set your mock instance to the public static Extensions field in order for existing code to call the mock. It is sort of an indirect dependency.

Friday, March 28, 2008 1:57:28 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.net | .net - Extension Methods
Search
Archive
<May 2008>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
Statistics
Total Posts: 47
This Year: 0
This Month: 0
This Week: 0
Comments: 2
Sign In