Saturday, 20 June 2015

Reflection at rescue

Few days back , i found some codebase which handled so many if conditions based on some input parameter. This thing made particular method to be 100 lines long. The code works fine , but was too ugly.



The situation was like this.

using System;
namespace Solution
{
public class Program
{
public SomeModel AddValue(string value, string type)
{
var obj = new SomeModel();
if (type == "IsBelowTenYears")
{
obj.IsBelowTenYears = true;
}
if (type == "IsFeelingBetter")
{
obj.IsFeelingBetter = true;
}
if (type == "IsYoung")
{
obj.IsYoung = true;
}
if (type == "IsGoodBoy")
{
obj.IsGoodBoy = true;
}
return obj;
}
}
public class SomeModel
{
public int id { get; set; }
public string name { get; set; }
public Boolean IsBelowTenYears { get; set; }
public Boolean IsFeelingBetter { get; set; }
public Boolean IsYoung { get; set; }
public Boolean IsGoodBoy { get; set; }
}
}
view raw conditions.cs hosted with ❤ by GitHub
Using reflection it can done in some few lines.

using System;
using System.Collections.Generic;
namespace Solution
{
public class Program
{
public SomeModel AddValue(string value, string type)
{
var obj = new SomeModel();
var properties = typeof(SomeModel).GetProperties();
foreach (var n in properties)
{
if (n.Name == type)
{
n.SetValue(obj, true, null);
break;
}
}
return obj;
}
}
public class SomeModel
{
public int id { get; set; }
public string name { get; set; }
public Boolean IsBelowTenYears { get; set; }
public Boolean IsFeelingBetter { get; set; }
public Boolean IsYoung { get; set; }
public Boolean IsGoodBoy { get; set; }
}
}
view raw reflection hosted with ❤ by GitHub
So you can see here , that this particular piece of code is more maintainable , no matter how many more properties or types you add , it just works.

Basics of Tree data structure

Tree data structure simulates a  hierarchical tree structure, with root and subtrees represented by linked nodes. Some Terminology Root...