Tags: , , , | Categories: Generics, Code Development Posted by nurih on 11/29/2009 3:12 PM | Comments (0)

Often enough we have frameworks do heavy lifting for us. That's usually a good thing. But I always found it kind of sedating to let "the man" provide me with too much comfort. Especially when the framework or other SOUP library fails to perform exactly what you want. That usually leads to some grumpiness followed by some code-acrobatics to punch that square peg into a round hole – often negating the elegance and usefulness of the library call altogether.

One task a framework often performs is binding. Binding – as defined here – is taking an object and assigning values to it's properties from a property bag of sorts. For example, a property bag could be a hash-table or list of name-value pairs and an object would be a POCO (Plain old class object). It's common in web and ORM contexts, also in web services to receive a dictionary of values and have to attach them to your domain model. The plain straightforward way would be to pluck key value pairs one by one by name and assign to your object. But that's no fun and error prone. What we would like is to be able to auto-attach values to the target object.

How do we achieve that? Steve Bearman and I actually presented this very briefly as part of a larger talk on advanced C# at SoCal Code Camp last weekend. A bit of reflection, a bit of generics and extensions, and viola:

   1: public static T Populate<T>(this T target, IEnumerable<KeyValuePair<string, object>> values)
   2: {
   3:     Type targetType = target.GetType();
   4:     foreach (var kvp in values)
   5:     {
   6:         PropertyInfo pi = targetType.GetProperty(kvp.Key);
   7:         pi.SetValue(target, kvp.Value, null);
   8:     }
   9:     return target;
  10: }

The extension method Populate() above takes an IEnumerable of KeyValuePair as a parameter. It then iterates a these pairs and for each key finds a property  by that name and assigns the value from the dictionary to the target object. Reflection comes in at lines 6 and 7. A property is found based on the name alone, and assigned to. Usage of this extension can look something like this:

   1: Dictionary<string, object> assignments = new Dictionary<string, object>();
   2: assignments.Add("Name", "Paris Hilton");
   3: assignments.Add("ID", 42);
   4: assignments.Add("HomePhone", "(310)-555-1212");
   5: assignments.Add("WorkPhone", "(310)-777-FILM");
   6: Person paris = new Person();
   7:  
   8: Person result = paris.Populate(assignments);

Simple, granted. Simplistic perhaps. But let's consider that the average programmer doesn't write much code like this. There can be many bells and whistles added here: A property getter might only assign if the prperty is writable, attempt to match without case sensitivity, only match if property is public or adorned with an attribute. The main thinks is that you can write this method into your solution in very few lines and shape it as you wish. You do not have to depend on default MVC binders or ORMs being open source or anything like that to have binding performed. Further utilizing this bit (!) of code you might create a simple object factory that returns a new populated type from any object given a property bag of values. In fact, let's do this right here:

   1: public static class MyFactory<T>
   2: {
   3:     public static T Create(IEnumerable<KeyValuePair<string, object>> values)
   4:     {
   5:         T result;
   6:         ConstructorInfo ctor = typeof(T).GetConstructor(System.Type.EmptyTypes);
   7:         result = (T)ctor.Invoke(null);
   8:         result.Populate(values);
   9:         return result;
  10:     }
  11: }

The generic factory MyFactory has a Create() method which takes a property bag as a parameter and returns a populated instance with the values provided. The usage of the factory eliminates the need for creating a new empty instance before populating it. Well, actually , it does it so you don't have to – code was not eliminated, just consolidated. The usage then becomes:

   1: Dictionary<string, object> values = new Dictionary<string, object>();
   2: values.Add("Name", "Paris Hilton");
   3: values.Add("ID", 42);
   4: values.Add("HomePhone", "(310)-555-1212");
   5: values.Add("WorkPhone", "(310)-777-FILM");
   6:  
   7: Person actual = MyFactory<Person>.Create(values);

So there we have it folks. Another DIY tidbit that would hopefully help you take control of the common binding task away from framework writers and back into your hands - where it belongs.

In production, you would probably want to also take a look at whether there's a Populate() or TryPopulate() -exception or return boolean -  and handle the whole error pathing in an explicit way that fits your own style of coding. Similarly you should consider whether an unassigned property (missing value in the bag) is cause for error and whether extra unmatched values are cause for error. In this example, an extra value will cause an exception and an unassigned property will not.

Happy Binding!

Tags: , , , | Categories: Code Development, General, Generics Posted by nurih on 10/16/2009 9:50 AM | Comments (0)

Sometimes I just write code. And sometimes I clean up my code. Most of the times, I focus on the meat of the methods, hacking away at verbose or lengthy flows, re-factoring out common code, trying to untangle overly complex logic etc.

Recently, I noticed that many of the conditional terms I write span very long lines and are a bit cumbersome to read. The reason for that is that many of the variable names are long, or the properties or both and that often the comparison is on a property of an object or member of a collection etc.

So for instance:

if (summerCatalog.Products[0].ProductCategories[0].ParentCategoryID >= 1 && summerCatalog.Products[0].ProductCategories[0].ParentCategoryID <= 4)
{ 
//...
}


Can become quite long.
Long is not easy to read.
Long is not easy to maintain.
Long is not easy to think through.

What I really wanted to say is if [value] is between [a] and [b].

Of course, one could say "lets just make the variable names shorter". But that flies in the face of self explanatory plain naming. So abbreviating for the sake of short-lineliness (New word! You heard it her first!) is out.

Well, this is just screaming "EXTENSION METHODS" doesn't it?

Here we go then:

/// <summary>
/// Returns whether the value is between the 2 specified boundaries.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value to compare</param>
/// <param name="minValueInclusive">The min value (inclusive).</param>
/// <param name="maxValueInclusive">The max value (inclusive).</param>
/// <returns>True if the value is equal to or between the boundaries; False otherwise.</returns>
public static bool Between<T>(this T value, T minValueInclusive, T maxValueInclusive) where T : IComparable<T>
{
    if (minValueInclusive.CompareTo(maxValueInclusive) > 0)
    {
        throw new ArgumentException("minimum value must not be greater than maximum value");
    }
    return (value.CompareTo(minValueInclusive) >= 0 && value.CompareTo(maxValueInclusive) <= 0);
}

The Between function takes any object which supports IComparable<T> and performs syntactic sugar comparison with the inclusive min and max values.
What's more, it adds a basic sanity check for the comparison. How many times do I do that sanity check in my normal code (!)?

Now the conditional is

if (summerCatalog.Products[0].ProductCategories[0].ParentCategoryID.Between(1, 4)) 
{
///...
}

At least I don't have to refactor this in my brain while reading.

Sure, you might say, but you could have just de-referenced the deep value and then have a shorter conditional, like so:

Category category = summerCatalog.Products[0].ProductCategories[0];
if (category.ParentCategoryID >= 1 && category.ParentCategoryID <= 4)
{
    //...
}
Yes - of course - but it adds a line of code, places the burden of reading the very common idiom ( x >= a && x <= b) on me, and I constantly stumble on the lest-than-or-equal vs. less-than and it doesn't check for my boundaries being inadvertently swapped.

So there you have it. A simple extension cuts down your lines of code, makes long text shorter and saves lives. Which begs the question: is this already part of the language - and should it be?
Tags: , , | Categories: Code Development, Generics Posted by nurih on 2/14/2007 3:29 PM | Comments (0)

When you want to create custom events, often you need to pass an event argument, and as often you need only to pass in one parameter - your object.

 

So what you used to do is:

    public event MyCustomEventHandler MyCustomEvent;
public delegate void MyCustomEventHandler(MyCustomEventArg evt);
public class MyObject
{
public string foo;
public int count;
public DateTime when;
public MyObject()
{
foo = "hello world";
count = 42;
when = DateTime.Now;
}
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}",foo,count,when);
}
}
    public class MyCustomEventArg : EventArgs
{
private MyObject _value;
public MyObject Data
{
get { return _value; }
set { _value = value; }
}
public MyCustomEventArg(MyObject value)
{
_value = value;
}
}
 

The not so pretty thing about it is that you had to mind-numbingly create a class which derives from EventArgs just to be able to pass your single event argument MyObject.

Now come generics and Microsoft has provided the generic type:

EventHandler<TEventArgs>
and with it, you can now code
 
   public event EventHandler<MyCustomEventArgs> MyCustomEvent;
// Not "necessary" anymore..
// public delegate void MyCustomEventHandler(MyCustomEventArg evt);
public class MyObject
{...}
public class MyCustomEventArg : EventArgs
{
private MyObject _value;
public MyObject Data
{
get { return _value; }
set { _value = value; }
}
public MyCustomEventArg(MyObject value)
{
_value = value;
}
}
 

Well, that saved me one line of code! I can ditch work early today :-)

Wouldn't it by nice if I could cut out the whole MyCustomEventArg class? that would save some more lines of code,

and prevent my head from hitting the desk and busting my skull on an upside-down thumb tack.

Well, that's pretty easy to do: create a new class using generics. It supports a single object as a parameter which

can be passed in at construction.

 
using System;
/// <summary>
/// Encapsulates a single object as a parameter for simple event argument passing
/// <remarks>Now you can declare a simple event args derived class in one wrap</remarks>
/// <code>public void delegate MyCustomeEventHandler(TypedEventArg&lt;MyObject&gt; theSingleObjectParameter)</code>
/// </summary>
public class TypedEventArg<T> : EventArgs
{
private T _Value;
public TypedEventArg(T value)
{
_Value = value;
}
public T Value
{
get { return _Value; }
set { _Value = value; }
}
}

Now the code can look like

 

    public event MyCustomEventHandler MyCustomEvent;
public delegate void MyCustomEventHandler(TypedEventArg<MyObject> evt);
public class MyObject
{ ... }
    //This whole thing now goes away.. 
//public class MyCustomEventArg : EventArgs
//{
//    private MyObject _value;
//    public MyObject Data
//    {
//        get { return _value; }
//        set { _value = value; }
//    }
//    public MyCustomEventArg(MyObject value)
//    {
//        _value = value;
//    }
//}

And life is good. I do have to declare the delegate though, so you daring enough to type 2 nested angled brackets, you can go for the gold:

    public event EventHandler<TypedEventArg<MyObject>> MyCustomEvent;
//public delegate void MyCustomEventHandler(TypedEventArg<MyObject> evt);
public class MyObject
{ ... }
 

This lets you dispense with 1 extra line of code so for those of us typing with 1 or 2 fingers, life is better. Readability of nested generic references vs. the declaration of a delegate is a matter of taste mostly.

Taste would also guide you as to whether you like the declaration on the event consumer side better:

In case of a full delegate declaration:

            Eventful eventSource = new Eventful();
eventSource.MyCustomEvent += new Eventful.SomethingHappenedEventHandler(OnSomethingHappenedEvent);

But if a generics EventHandler is used:

            eventSource.MyCustomEvent += new EventHandler<TypedEventArg<MyObject>>(classWithEvent2_SomethingHappendedEvent);

In conclusion, by creating a simple generic type around EventArgs, I can save a few keystrokes and learn something while at it. Left as a future excercise : look at adding a constraint to the argument type such that the argument type is serializeable.

Tags: , , | Categories: Code Development, General, Generics Posted by nurih on 11/2/2006 9:53 PM | Comments (0)

I was challenged recently with a question about generics with constraints.

The claim was that it's only a compile flaw that allows your to declare an interface for a generic type with a constraint. Namely that the syntax

public interface ISomething <T> where T: SomeClass

would pass compilation but would not be useful (runtime) because you can't declare a variable

ISomething myVar = new ISomething<SomeClass>();

or something to that extent. I went home feeling a bit uneasy about the discussion, then coded this up the way I see it. While it is completely true that you can't 'new' an interface, using an interface that has a generic type is completely possible and legal.

Here it is in all it's g(l)ory.

using System;
using System.IO;
using System.Text;
/// Demo of generic interface declaration with constraint.
/// Showing compilation and runtime feasibility.
namespace NH.Demo
{
class Demo
{
static void Main(string[] args)
{
ITryInstance o1 = new GenericInstanceA();
ITry<MyDerivedType> o2 = new GenericInstanceB();
Console.WriteLine("Generic instance 1 " + o1.ProperT.SomeField);
Console.WriteLine("Generic instance 2 " + o2.ProperT.SomeField);
}
}
interface ITry<T> where T : MyBaseType
{
T ProperT{ get; }
}
public class MyBaseType
{
public string SomeField;
}
public class MyDerivedType : MyBaseType
{
public MyDerivedType(string arg)
{
base.SomeField = arg;
}
}
interface ITryInstance : ITry<MyDerivedType>
{
}
/// <summary>
/// this will fail. cosntraint violation
/// "The type 'string' must be convertible 
/// to 'NH.Demo.MyBaseType' in order to use it as 
/// parameter 'T' in the generic type or 
/// method 'NH.Demo.ITry<T>'"
/// </summary>
//interface IFail : ITry<string> { }
public class GenericInstanceA : ITryInstance
{
MyDerivedType ITry<MyDerivedType>.ProperT
{
get { return new MyDerivedType("hi there!"); }
}
}
public class GenericInstanceB : ITry<MyDerivedType>
{
MyDerivedType ITry<MyDerivedType>.ProperT
{
get { return new MyDerivedType("hi there! again"); }
}
}
}