Feeds:
Posts
Comments

Archive for March, 2009

Reflecting on Code

Static reflection. It’s all the rage.

What is static reflection? It’s obtaining type information at compile time instead of runtime, typically by using LINQ expression trees. Here’s my take on providing a static helper to do this.

public static class Reflect
{
    public static MemberInfo GetMember(Expression<Action> expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(
                GetMember(() => expression).Name);
        }

        return GetMemberInfo(expression as LambdaExpression);
    }

    public static MemberInfo GetMember<T>(Expression<Func<T>> expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(
                GetMember(() => expression).Name);
        }

        return GetMemberInfo(expression as LambdaExpression);
    }

    public static MethodInfo GetMethod(Expression<Action> expression)
    {
        MethodInfo method = GetMember(expression) as MethodInfo;
        if (method == null)
        {
            throw new ArgumentException(
                "Not a method call expression", GetMember(() => expression).Name);
        }

        return method;
    }

    public static PropertyInfo GetProperty<T>(Expression<Func<T>> expression)
    {
        PropertyInfo property = GetMember(expression) as PropertyInfo;
        if (property == null)
        {
            throw new ArgumentException(
                "Not a property expression", GetMember(() => expression).Name);
        }

        return property;
    }

    public static FieldInfo GetField<T>(Expression<Func<T>> expression)
    {
        FieldInfo field = GetMember(expression) as FieldInfo;
        if (field == null)
        {
            throw new ArgumentException(
                "Not a field expression", GetMember(() => expression).Name);
        }

        return field;
    }

    internal static MemberInfo GetMemberInfo(LambdaExpression lambda)
    {
        if (lambda == null)
        {
            throw new ArgumentNullException(
                GetMember(() => lambda).Name);
        }

        MemberExpression memberExpression = null;
        if (lambda.Body.NodeType == ExpressionType.Convert)
        {
            memberExpression = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
        }
        else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
        {
            memberExpression = lambda.Body as MemberExpression;
        }
        else if (lambda.Body.NodeType == ExpressionType.Call)
        {
            return ((MethodCallExpression)lambda.Body).Method;
        }

        if (memberExpression == null)
        {
            throw new ArgumentException(
                "Not a member access", GetMember(() => lambda).Name);
        }

        return memberExpression.Member;
    }
}

If you look closely, the code itself shows you a use for the idea. Yep, it’s definitely dogfood. Pay attention to how we raise ArgumentNullExceptions in this code. No “magic strings” for us. This is compiled code. If I use the wonderful IDE refactoring capabilities to rename the argument, the string passed to the ArgumentNullConstructor is also refactored, because it’s static code and not a string literal.

There’s also situations where you don’t have an instance of data to use for reflecting, and the above code isn’t so useful in this case. That’s where it’s big brother comes in.

public static class ReflectOn<T>
{
    public static MemberInfo GetMember(Expression<Action<T>> expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(Reflect.GetMember(() => expression).Name);
        }

        return Reflect.GetMemberInfo(expression as LambdaExpression);
    }

    public static MemberInfo GetMember<TResult>(Expression<Func<T, TResult>> expression)
    {
        if (expression == null)
        {
            throw new ArgumentNullException(Reflect.GetMember(() => expression).Name);
        }

        return Reflect.GetMemberInfo(expression as LambdaExpression);
    }

    public static MethodInfo GetMethod(Expression<Action<T>> expression)
    {
        MethodInfo method = GetMember(expression) as MethodInfo;
        if (method == null)
        {
            throw new ArgumentException(
                "Not a method call expression",
                Reflect.GetMember(() => expression).Name);
        }

        return method;
    }

    public static PropertyInfo GetProperty<TResult>(Expression<Func<T, TResult>> expression)
    {
        PropertyInfo property = GetMember(expression) as PropertyInfo;
        if (property == null)
        {
            throw new ArgumentException(
                "Not a property expression", Reflect.GetMember(() => expression).Name);
        }

        return property;
    }

    public static FieldInfo GetField<TResult>(Expression<Func<T, TResult>> expression)
    {
        FieldInfo field = GetMember(expression) as FieldInfo;
        if (field == null)
        {
            throw new ArgumentException(
                "Not a field expression", Reflect.GetMember(() => expression).Name);
        }

        return field;
    }
}

Now I can do something like this.

class Program
{
    public void Foo()
    {
    }

    static void Main(string[] args)
    {
        Console.WriteLine(ReflectOn<Program>.GetMethod(p => p.Foo()).Name);
    }
}

Want another, more practical use?

public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    protected void OnPropertyChanged() // All properties changed
    {
        OnPropertyChanged(null);
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    protected void OnPropertyChanged<T>(Expression<Func<T>> expression)
    {
        OnPropertyChanged(Reflect.GetProperty(expression).Name);
    }
}

Which is used like this.

public class Foo : ObservableObject
{
    private string message;

    public string Message
    {
        get
        {
            return this.message;
        }

        set
        {
            this.message = value;
            OnPropertyChanged(() => Message);
        }
    }
}

No more magic strings when raising PropertyChanged from INotifyPropertyChanged implementations.

The performance here is obviously worse than using the magic string, but it’s a lot better than using actual runtime reflection.

Advertisements

Read Full Post »

I’ve been using an assertion framework at least similar to the one I’ve put up on CodePlex called Specificity for quite some time now. The main goal of that library is solely to provide an assertion framework that’s extendable and discoverable, and it does so in a fashion that doesn’t tie it to any specific test framework. The naming conventions used within Specificity follow a more of the BDD form rather than the TDD form, with Should instead of Assert. However, I’ve not actually used any of the BDD frameworks available for .NET, mostly because I have to use MsTest at work and I am accustomed to using it and so continue to use it outside of work. Recently, I’ve been experimenting with following BDD at least to the extent that my unit testing framework of choice will allow (the Test terminology leaks through in the attribute names used, which BDD purists would not care for). This has eventually lead to me experimenting with a base class that I think may be useful for inclusion in Specificity. This base class isn’t tied to any testing framework, and thus could be a drop-in base class for tests you write using any existing testing framework, much like the assertions in Specificity. The base class is really quite simple, though I’m sure it could be expanded. Part of the inspiration came from Jean-Paul S. Boodhoo, though I’ve simplified it quite a bit in ways that most developers would be more comfortable with, I think. Here it is in all its glory (such as it is):

public abstract class Observations<TResult>
{
    private bool acted;
    private TResult result;

    protected TResult Result
    {
        get
        {
            if (!this.acted)
            {
                ArrangeAndAct();
            }

            return this.result;
        }
    }

    protected virtual void Arrange()
    {
    }

    protected abstract TResult Act();

    private void ArrangeAndAct()
    {
        Arrange();
        this.result = Act();
        this.acted = true;
    }
}

That’s it. I told you there wasn’t much to it. I’ve chosen to follow the AAA (Arrange, Act and Assert) terminology rather than the “context” and “because” terminology used by Jean-Paul, but the examples from the blog post of his that I linked are easily translated. Here’s his first example, just to give you the flavor of how this is used.

[TestClass]
public class When_adding_2_numbers : Observations<int>
{
    protected override int Act()
    {
        return 2 + 2;
    }

    [TestMethod]
    public void should_result_in_the_sum_of_the_2_numbers()
    {
        Specify.That(this.Result).ShouldBeEqualTo(4);
    }
}

Of course, this was in MsTest, but you should be able to easily translate it to whatever test framework you use. I’ve not leveraged the Setup concepts available from most testing frameworks because it would tie the code to a specific testing framework, and because some frameworks (looking at you, xUnit.net) don’t have the concept, relying on the constructor instead. I’ve not addressed cleanup here, though it should be possible to work that one out. If your test methods are side effect free (they should be), there’s little purpose in enabling cleanup, so I’ve not bothered to think to deeply on that one.

This seems extremely simplistic, but the point behind the base class is to force a BDD approach to testing, where you have a test per feature, rather than a test per class. It’s a poor man’s addition to a TDD framework to enable a BDD style.

I’d love to hear input on this one. What do people think of the idea? What about the implementation? Should something like this go into Specificity? Nit-pick me to death, please.

Related: Behavior Driven Design and Specificity – Part II

Read Full Post »

Onyx and Specificity

In case you’ve not seen it other places, I’ve started a couple of CodePlex projects myself. The first is an assertion library for unit testing, with a focus on extensibility and intellisence discover ability, called . The second is a WPF framework to aid in the development of applications that use the M-V-VM design, called Onyx. Both are still under development and haven’t yet had a release, but the code is usable and worth checking out.

Read Full Post »

A Thriple Play

Josh Smith, a fellow Disciple who probably needs no introduction, has released a new project on CodePlex called Thriple. This project aids in the use of 3D concepts within WPF by providing simple concepts that do the heavy lifting for you: ContentControl3D which contains a BackContent as well, and can rotate to show both sides; and Panel3D which shows it’s content along a single path in 3D space. This is definitely a project worth checking out if you want to add the final polish to your WPF applications, without having to learn the complicated 3D APIs.

Read Full Post »

Dueling Banjos

In this case, the “banjos” are FXCop and StyleCop.  Can’t we all just get along?

Here’s the deal. I’m a big proponent of using static checkers such as FXCop and StyleCop.  I think they go a long way towards improving the quality of code. However, lately there have been a few things about these tools that have been driving me crazy.

Let’s start with FXCop. There’s a couple of warnings you run into frequently when developing in WPF (at least, I do). CA1810 is a warning about performance when you use a static constructor instead of a static initializer. My first though is, how bloody important is this sort of optimization? The hit can’t be that big, especially when you consider it’s a one time hit and not something that can be amplified by usage in a loop. This sounds like premature optimization to me, and we all know the famous quote about that! Normally, however, this would be a minor thing to comply with, and wouldn’t occur all that often. In fact, my natural instinct is to use an initializer. However, in WPF the static constructor is often required for things like registering class event handlers with the EventManager. You can’t really use an initializer for this, and suppressing this every time it happens is a PITA. At least with FXCop I can turn the rule off, even if I do have to manually do that for each and every project (hint Microsoft: we could use some sort of solution based configuration here).

The next FXCop warning that’s annoying me a lot is CA1004, which complains when you use a generic type parameter only in the return type and not as a parameter type. Seems this is supposed to be “confusing” for developers. Well, I call BS. If you don’t understand how generics work, you probably shouldn’t be coding in .NET languages that support the concept. If you look around it’s really not uncommon at all to have code that uses a generic parameter as the return type, as syntactic sugar to simplify scenarios where you’d otherwise have to employ a cast. Again, though, I can turn this one off.

StyleCop has a lot of rules I don’t agree with as well. The bloody file header stuff serves no real purpose, other than keeping specific legal counsel happy. Legally, you don’t have to provide a copyright statement at all: your code will still be protected by copyright laws. You certainly don’t have to repeat it for every file in a project. Not only does it clutter the source, it’s a PITA when the copyright notice must change (such as a change on the date). I also hate the warning that wants you to place the imports inside the namespace. VisualStudio doesn’t like this, either. The default templates put the imports outside, and intellisense helpers have a hard time with indentation for imports they add when inside the namespace. All for something that, despite the attempts to make it sound like a sound technical thing to do, it’s really just a “tabs vs. spaces” kind of debate.

However, what I’m here to talk about today is how these two tools sometimes don’t like each other. The specific issue I want to talk about is with naming member variables. See, StyleCop doesn’t like you to use “warts” or “hungarian notation” at the beginning of member variable names. This means the typical usages of “m_” and “_” at the beginning of member variable names is verboten, according to StyleCop. OK, let’s not get into any “religious arguments” over this. I prefer the warts, honestly, but I can live without them. So, the warts are gone. I no longer use them, in order to keep StyleCop happy. Unfortunately, this means I often make FXCop unhappy. See, FXCop has this warning, CA1500, which complains when you use a local variable name that’s the same as a member variable name (thankfully, it doesn’t complain when you do this with parameters to constructors. However, it’s still fairly common to need a local representation of data for the same thing as the member. Argh!!! I’ve actually resorted to use names like “theWidget” instead of “widget” for local names, just to shut the tools up. This is a wart, but because it’s a word, StyleCop won’t complain. Sad. Very sad. I’d rather go back to using “m_” or “_” on member variable names (though “this._widget”, which another StyleCop rule requires, is a bit silly).

Well, enough ranting. I’ve got work to do.

Read Full Post »