Passing Property Names the "compiler-safe" Way

A common bad practice which I often find when browsing through code is to see people directly hard-code strings in their source code. I've also proposed some refactorings in some of my previous posts. Today I'd like to blog about a similar issue which targets the issue of object property referencing within code.

I guess most of us already had the case where you give a property of your entity like

SomeHelper.Validate(entityObject, "somePropertyName", value);
SomeHelper.Validate(entityObject, "someOtherPropertyName", value);
This "strange" assignment because SetProperty takes objects in a generic way and validates the specified property. Note, this is not real-world code, so don't be scared :) , but it may arise in similar ways throughout your code-base.
Another use case I was currently experiencing and which was the reason for writing this blog post is when announcing a problem about some property to the system user (i.e. in a log). In such a case you'd probably write
MyLogger.LogProblem("SomePropertyName", "Some message from a resource file");

So what's the problem with such code?
  • No compile-time-checking! Changing the property name of your object, won't give you any error during compile time but you may experience nice errors when the system is being used. Well ok, ReSharper does a nice job in also including such strings in refactorings, but still.
    These kind of bugs are heavy, since you may have difficulties in spotting them.
  • It is cumbersome to type and code because you have to remember the exact name of the property without any kind of Intellisense support.
These issues can be solved by using a nice Linq construct.
public static void LogProblem<T>(Expression<Func<T>> propertyExpression, string message)
{
    string propertyName = GetPropertyName(propertyExpression);
    if (propertyName == null)
        throw new NullReferenceException("The name of the property couldn't be retrieved!");

    LogEntry logEntry = new LogEntry()
    {
        Fieldname = propertyName,
        MessageDescription = String.Format(message, propertyName)
    };

    logEntries.Add(logEntry);
}

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}
This can then be used very nicely by rewriting the logging instruction I mentioned before like this
MyLogger.LogProblem(() => myObjInstance.SomePropertyName, "Some message from a resource file");
Voilá, you have a compile-time, fully intellisense supported logging method now. The only thing I don't really like is the somehow strange-looking declaration of the property name by having to use () => ...

“I am ready to write some unit tests. What code coverage should I aim for?”

Here's a nice "story" about code coverage from the Google Testing Blog.

Testivus on Test Coverage
Early one morning, a young programmer asked the great master:

“I am ready to write some unit tests. What code coverage should I aim for?”
The great master replied:
“Don’t worry about coverage, just write some good tests.”
The young programmer smiled, bowed, and left.

Read more on the official blog »
Code coverage is an interesting metric which I found particularly useful as an indicator of "trust in your tests". See my according post here.

HowTo: Install your Android app OTA on your device for testing

A fundamental thing when developing Android apps but also in general when developing with device emulators is to test your app on real devices. Android makes this easy. By activating "USB debugging" on the device and connecting it to your workstation with an USB cable. The app can then either be started from within Eclipse or by deploying it using the adb bridge.

However, most often I do not really want to debug the code on the real device, but rather just to test it by running it. ADB doesn't however allow you to install your app to an arbitrary IP (in the WLAN net for instance), but just by using the USB cable which, however, is really annoying when you just need to deploy your app. But don't give up, there are some alternatives which allow you to have some kind of OTA installation.

Practical example: Applying the Template Method design pattern

As I already mentioned in my previous post I'm currently doing domain objects to XSD generated object mapping. Monotonic, exactly, but I'm approaching the end of the work.
Still, when doing such annoying work, I'm continuously striving to reduce the amount of work by trying to find smarter, faster, more concise ways for doing this tedious work (in order to finish earlier ;) ). Usually after a couple of hours common patterns/repetitions emerge as I learn the structure of the underlying XSD. Refactorings then usually help to proceed faster.

A design pattern which I found to fit nicely when doing such object mapping work is the Template Method design pattern.

A template method defines the program skeleton of an algorithm. One or more of the algorithm steps are able to be overridden by subclasses to provide their own concrete implementation. This allows differing behaviors while ensuring that the overarching algorithm is still followed.
Source: Wikipedia
In fact, the most interesting part when doing this kind of mapping work is to define an appropriate program skeleton for outlining the basic structure and here is where I used the Template Method pattern.
The data flow is from the application's domain model to the XSD generated objects. Basically there is some input (one or potentially more domain objects) which produces the desired output (exactly one XSD generated object). These objects have then to be assembled properly before being serialized to the final XML output. Frankly, just basic serialization work.

Refactoring for the sake of compactness and reusability

Currently I'm doing a rather monotonic work, let's call it like this. We basically need to serialize our data to an XML file that has to match a given XSD which has been given to us by our customer. The problem, the XSD has not nearly the same structure of our own domain model which implies a lot of property 1-1 mapping between the C# objects generated from the XSD file and our domain model. Automatism?? Not really applicable. I tried already to figure out to which degree libs like AutoMapper could be useful but concluded that it wouldn't really bring much in the end.

A nice thing when coding such object mappings is that there emerge patterns which can then be refactored nicely, also because these mapping stores involve an overall structural/architectural design initially but then they are nearly a pure typing exercise (which often isn't that bad too). Take the example below:

List<SoggAggiudicatarioType> soggAggiudicatarioTypes = new List<SoggAggiudicatarioType>();
if (awardCompanies != null)
{
    foreach (ICompanyDetail companyDetail in awardCompanies)
    {
        soggAggiudicatarioTypes.Add(MapAwardCompanySoggAggiudicatarioType(companyDetail));
    }
}
convertedType.Aggiudicatari = soggAggiudicatarioTypes.ToArray<SoggAggiudicatarioType>();

This was one re-occurring pattern. A list of objects from our domain model had to be mapped accordingly to an array of a generated XSD type. Lot's of mostly similar constructs emerged so I refactored the whole stuff above to the following:

convertedType.Aggiudicatari = 
  MapArray<ICompanyDetail, SoggAggiudicatarioType>(awardCompanies,MapAwardCompanySoggAggiudicatarioType);

Transforms in a nice one-liner :) and saves you from cramps in your fingers ;) . But the code hasn't disappeared, it has just been refactored to the given, generic method:

protected TConvertTo[] MapArray<TConvertFrom, TConvertTo>(List<TConvertFrom> sourceData, Func<TConvertFrom, TConvertTo> convertFunction)
{
    List<TConvertTo> convertedResult = new List<TConvertTo>();
    if (sourceData != null)
    {
        foreach (TConvertFrom sourceItem in sourceData)
        {
            TConvertTo converted = convertFunction.Invoke(sourceItem);
            convertedResult.Add(converted);
        }
    }

    return convertedResult.ToArray<TConvertTo>();
}