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 reflection it can done in some few lines.
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.
The situation was like this.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} | |
} |