Reputation: 1228
Currently I have a bunch of if else statements to set CategoryId's based on how many items are in each collection.
For example,
public class TeamWork
{
public string EmployeeName { get; set; }
public int CategoryId { get; set; }
}
public class BLL
{
public void SetCategoryId(ICollection<TeamWork> Converted, ICollection<TeamWork> Sourced)
{
if (Converted.Count == 1 && Sourced.Count == 1)
{
if (String.Compare(Sourced.First().EmployeeName, Converted.First().EmployeeName) == 0)
{
// set category id to 1
Converted.First().CategoryId = 1;
Sourced.First().CategoryId = 1;
}
else
{
// set category id to something
}
}
else if (Sourced.Rows.Count == 1 && Converted.Rows.Count > 1)
{
// set category id to something
}
// more if else statements...
}
}
I think there's a better way to do this perhaps by applying some design pattern. Any suggestions? Thanks!
Upvotes: 3
Views: 284
Reputation: 71591
A Strategy pattern comes to mind. Try to break these rules down into a series of "if this condition is true, then the category ID is this". Make each one of these a method, then add those methods as delegates to a List<Func<ICollection<TeamWork>, ICollection<TeamWork>, bool>>
or a comparable indexed collection. Then, your SetCategoryId() code looks like this:
public void SetCategoryId(ICollection<TeamWork> Converted, ICollection<TeamWork> Sourced)
{
foreach(var categoryRule in CategoryRules)
{
var category = test(Converted, Sourced);
if(category != 0)
{
Converted.First().CategoryId = Sourced.First().CategoryId = category;
break;
}
}
}
The above code would never have to change regardless of how many rules you added or removed. However, with the if - else if structure you have, your series of rules will likely be order-dependent, so be careful when setting up the rules in the list.
Upvotes: 1
Reputation: 81700
Chain of responsibility is the way to go.
So this object is passed to a series of command objects until one is able to act upon and set the status.
Upvotes: 4