Reflection… is like violence

“If it doesn’t solve your problems, you are probably not using enough of it”

Introduction

What is Reflection?

You can think of your class like it is your body. The code contained in it doesn’t “know” anything about its contents (unless it’s statically referenced, but I wouldn’t consider it “knowing about”), just like you don’t know what is inside your body.

The Reflection is then like an encyclopedia of a human body that contains all the information about it. You can use it to discover all the information about all your body parts.

So, what is that Reflection in computer programming?

The Reflection is a mechanism that allows you to discover the information about what your class is made of.

You can enumerate in the runtime through Properties, Methods, Events and Fields, no matter if they are static (Shared in Visual Basic) or instance, public or non-public.

But it does not limit you to discover information about only your classes. You can actually get the information about all the classes currently loaded into your application domain.

This means, Reflection gives you access to the places you can’t get to in a “normal” way.

The purpose of using reflection

Some say that there’s no point in getting access to class members through Reflection because:

  • Public members are accessible in the “normal” way, so using Reflection just breaks the strong typing – the compiler will no longer tell you if you are doing something wrong;
  • Accessing non-public members is just hacking.

They may be right, in both cases, but

  • Sometimes it’s way more convenient to let the program discover members in runtime so we don’t need to explicitly access them one by one, it’s more refactoring-proof, sometimes it’s the only way to implement a well-known design pattern;
  • And sometimes, hacking is the only reasonable way of achieving a goal.

Still in doubt? Let’s take a look at some examples below that describe when to use Reflection and get a profit and when it’s more like a bad practice…

Use-case 1: Enumerate your own members

One of the most popular use cases of Reflection is when you have to serialize your class and send such prepared data over the net e.g. using JSON format. A serializer (a class containing one essential method responsible for creating a data ready to send out of your class object and probably second method to restore the data back to your class object) does nothing else than enumerate through all the properties contained by the class and reads all the data from the class object and then formats it to prepare desired format (such as JSON).

Static typing approach – specify properties explicitly when assembling the output string

Now imagine you have to serialize a class without using the reflection. Let’s take a look at the example below:

Suppose we have a model class

public class SampleClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}

And we want to serialize an instance of this class to a comma separated string.

Sounds simple, so let’s do it. We create a serializer class:

public static class SampleClassSerializer
{
    static string Serialize(SampleClass instance)
    {
        return $"{obj.Id},{obj.Name}";
    }
} 

Looks simple and straightforward.

But what if we need to add a property to our class? What if we have to serialize another class? All these operations require to change the serializer class which involves additional frustrating work that needs to be done each time something changes in the model class.

Reflection approach – enumerate properties automatically when assembling the output string

How to do it properly, then?

We create a seemingly bit more complicated serializer method:

 

//Make the method generic so object of any class can be passed.
//Optionally constrain it so only object of a class specified in a constraint,
//a class derived from a class specified in a constraint
//or a class or an interface implementing an interface specified in a constraint can be passed.
public static string Serialize<T>(T obj) where T : SampleClass
{
    //Get System.Type that the passed object is of.
    //An object of System.Type contains all the information provided by the Reflection mechanism we need to serialize an object.
    System.Type type = obj.GetType();

    //Get an IEnumerable of System.Reflection.PropertyInfo containing a collection of information about every discovered property.
    IEnumerable<System.Reflection.PropertyInfo> properties = type.GetProperties()
    //Filter properties to ones that are not decorated with Browsable(false) attribute
    //in case we want to prevent them from being discovered be the serializer.
        .Where(property => property.GetCustomAttributes(false).OfType<BrowsableAttribute>().FirstOrDefault()?.Browsable ?? true);

    return string.Join(",", //Format a comma separated string.
        properties.Select(property => //Enumerate through discovered properties.
        {
            //Get the value of the passed object's property.
            //At this point we don't know the type of the property but we don't care about it,
            //because all we want to do is to get its value and format it to string.
            object value = property.GetValue(obj);

            //Return value formatted to string. If a custom formatting is required,
            //in this simple example the type of the property should override the Object.ToString() method.
            return value.ToString();
        }));
} 

The example above shows that adding a few simple instructions to the serializer makes us we can virtually forget about it. Now we can add, delete or change any of the properties, we can create new classes and still Reflection used in the serializer will still discover all the properties we need for us.

With this approach all the changes we make to the class are automatically reflected by the serializer and the way of changing its behavior for certain properties is to decorate them with appropriate attributes.

For example, we add a property to our model class we don’t want to be serialized. We can use the BrowsableAttribute to achieve that. Now our class will look like this:

public class SampleClass
{
    public int Id { get; set; }

    public string Name { get; set; }

    [Browsable(false)]
    public object Tag { get; set; }
} 

Note that after GetProperties method in serializer we are using Where method to filter out properties that have Browsable attribute specified and set to false. This will prevent newly added property Tag (with [Browsable(false)]) from being serialized.

Use-case 2: Enumerate class’ methods

This is an academic example. Suppose we are taking a test at a university where our objective is to create a simple calculator that processes two decimal numbers. We’ve been told that to pass the test, the calculator must perform addition and subtraction operations.

So we create the following Form:

There are two rows, each one uses different approach to the problem. The upper row uses common “academic” approach which involves the switch statement. The lower row uses the Reflection.

The upper row consist of following controls (from left to right): numericUpDown1, comboBox1, numericUpDown2, button1, label1

The lower row consist of following controls (from left to right): numericUpDown3, comboBox2, numericUpDown4, button2, label2

In a real case we would create only one row.

Static typing approach – use the switch statement to decide which method to use based on user input

Next, to make it properly, we create a class containing some static arithmetic methods that will do some math for us:

public class Calc
{
    public static decimal Add(decimal x, decimal y)
    {
        return x + y;
    }

    public static decimal Subtract(decimal x, decimal y)
    {
        return x - y;
    }
} 

And then we are leveraging our newly created class. Since it’s an academic test, we don’t want to waste precious time on thinking how to do it properly, so we are choosing the “switch” approach:

private void button1_Click(object sender, EventArgs e)
{
    switch (comboBox1.SelectedItem)
    {
        case "+":
            label1.Text = Calc.Add(numericUpDown1.Value, numericUpDown2.Value).ToString();
            break;

        case "-":
            label1.Text = Calc.Subtract(numericUpDown1.Value, numericUpDown2.Value).ToString();
            break;

        default:
            break;
    }
} 

Plus WinForms Designer generated piece of code that populates the operation combobox:

this.comboBox1.Items.AddRange(new object[] 
{
    "+",
    "-"
}); 

The code is pretty simple and self-explanatory.

But then, the lecturer says that if we want an A grade, the calculator must perform multiplication and division operations as well, otherwise, we will get B grade at most.

Additional hazard (by hazard I mean a potential threat that may in some circumstances lead to occurrence of unhandled exception or other unexpected behavior) in this approach is that we are using “magic constants”, the “+”,“-” strings. Note that for each arithmetic operation one instance of the string is generated by the designer and another instance is used in each case statement.

If by any reason we decide to change one instance, the other one will remain unchanged and there’s even no chance that IntelliSense will catch such misspell and for compiler everything is fine.

But, apart from that, let’s hope that the lecturer will like the “+”,“-“ strings, we need to implement two additional arithmetic operations in order to get our scholarship.

So, we implement two additional methods in our little arithmetic class:

public static decimal Multiply(decimal x, decimal y)
{
    return x * y;
}

public static decimal Divide(decimal x, decimal y)
{
    return x / y; //Since we are using decimals instead of doubles, this can produce divide by zero exception, but error handling is out of scope of this test.
} 

But obviously that’s not enough. We have to add two another cases in our switch statement:

case "×":
    label1.Text = Calc.Multiply(numericUpDown1.Value, numericUpDown2.Value).ToString();
    break;

case "÷":
    label1.Text = Calc.Divide(numericUpDown1.Value, numericUpDown2.Value).ToString();
    break; 

and two another symbols in the combobox Items collection, so the WinForms Designer generated piece of code looks like this:

this.comboBox1.Items.AddRange(new object[] 
{
    "+",
    "-",
    "×",
    "÷"
}); 

We must also bear in mind changing used method names if we copy/paste the existing piece of code, it can be a real hell if we have to add multiple methods or if there are multiple usages.

Reflection approach – enumerate class methods and let user choose one of them

So, how can we do it better?

Instead of using evil switch statement we use Reflection.

First, we discover our arithmetic methods and populate the combobox with them – literally, the combobox items are the System.Reflection.MethodInfo objects which can be directly invoked. This can be done in form constructor or in form Load event handler:

private void Form1_Load(object sender, EventArgs e)
{
    //Populate the combobox.
    comboBox2.DataSource = typeof(Calc).GetMethods(BindingFlags.Static | BindingFlags.Public).ToList();

    //Set some friendly display name for combobox items.
    comboBox2.DisplayMember = nameof(MethodInfo.Name);
} 

Then in the “=” button Click event handler we just have to retrieve the System.Reflection.MethodInfo from selected combobox item and simply call its Invoke method which will directly invoke desired method:

private void button2_Click(object sender, EventArgs e)
{
    label2.Text =                              //Set the result directly in the label's Text property.
        ((MethodInfo)comboBox2.SelectedValue)? //Direct cast the selected value to System.Reflection.MethodInfo,
                                               //we have the control over what is in the combobox, so we are not expecting any surprises.
        .Invoke(                               //Invoke the method.
            null,                              //Null for static method invoke.
            new object[] { numericUpDown3.Value, numericUpDown4.Value }) //Pass parameters in almost the same way as in normal call,
                                                                         //except that we must pack them into the object[] array.
        .ToString();
} 

That’s all. We reduced whole switch, designer populated list with symbols and magic strings to 3 simple lines.

Not only the code is smaller, its refactoring tolerance is greatly improved. Now, when lecturer says that we need to implement two another arithmetic operations, we simply add the static methods to our arithmetic class (as stated before) and we’re done.

However, this approach has a hazard. The usage in button2
Click event handler assumes that all arithmetic methods in Calc class accept only two parameters of type that is implicitly convertible from decimal.

In other words, if someone add a method that processes 3 numbers, the operation represented by this method will show up in the combobox, but attempt to execute it will result in target invocation exception.

But if we tried to use it in the previous approach, we would get the error as well. The difference is that it would be a compile time error saying that we are trying to use method that accepts 3 parameters but we have provided only 2 arguments.

That’s one advantage of static typing, the compiler upholds the code integrity and the IntelliSense will inform us about any misusages long before we even hit the compile button. When we are using dynamic invoke, we must predict any exceptions and handle them ourselves.

Conclusion

The examples above describe how the Reflection mechanism can improve code maintainability and robustness. They also show that Using Reflection, though it’s handy, lays more responsibility on the developer as checking for compatibility is moved from design time to run time and the compiler will no longer lend its hand when invoking dynamically typed members.

In this article we learned how can we use the Reflection to retrieve data from properties and how to invoke methods that are now explicitly specified in design time – they can change over time but the code that are using them will remain unchanged.

In the next article I’ll show you more advanced usages of the Reflection such as storing data, accessing private members and instantiating classes on some interesting examples like Building An Object From Database or Implementing Plugin System. You will also eventually find out why Reflection is like violence

One thought on “Reflection… is like violence

  1. Pingback: Reflection, part 2

Leave a Reply

Your email address will not be published. Required fields are marked *