Archive

Posts Tagged ‘Reflection’

Magic Strings: How to make this necessary evil (LESS) evil

October 15th, 2009

Magic strings are nasty for several reasons.

  1. Compiler will not pick up type-o’s
  2. When done improperly (e.g. copy / paste ) they can be inconsistent
  3. If they refer to a property or method, they will break on refactoring or renaming (prop / method)

What to do:

1) Try not to use them.

2) When you must, make constants (do not copy paste)

  • Bad: [Dependency("RxDomainUOW")]
  • Good:

Create a new Constants class in a top level directory (make it obvious)

public static class AmPharmConstants

    {

            const String c_RxDomainUOW = "RxDomainUOW";

    }

ii. Then use that constant instead

[Dependency(AmPharmConstants.c_RxDomainUOW)]

3) Rather than magic strings to name a property you can use a class in AmMedUtils: ReflUtil

  • Instead of this: this.PropertyChange(this, “PublishedOrders”);
  • Use this: this.PropertyChange(this, ReflUtil.PropName(() => PublishedOrders));

< CLASS ReflUtil >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace AMFW.Utilities
{
    /// <summary>
    /// From:
    /// http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
    /// </summary>
    public static class ReflUtil
    {
        /// <summary>
        /// string name = ReflectionUtility.PropName(() => default(Sample2).Foo);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string PropName<T>(Expression<Func<T>> expression)
        {
            MemberExpression body = (MemberExpression)expression.Body;
            return body.Member.Name;
        }

    }
}

alan.huffman C# , , ,