Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eliminate duplicate code?

Tags:

c#

I have the following codes and I would like to write it in a way that I have minimum duplication of codes.

if (Categories != null)
{
    bool flag=false;
    foreach (dynamic usableCat in Category.LoadForProject(project.ID))
    {
        foreach (dynamic catRow in Categories)
        {
            if (usableCat.ID == catRow.ID)
                flag = true;                            
        }
        if (!flag)
        {
            int id = usableCat.ID;
            Category resolution = Category.Load(id);
            resolution.Delete(Services.UserServices.User);
        }
    }
}
if (Priorities != null)
{
    bool flag = false;
    foreach (dynamic usableCat in Priority.LoadForProject(project.ID))
    {
        foreach (dynamic catRow in Priorities)
        {
            if (usableCat.ID == catRow.ID)
                flag = true;
        }
        if (!flag)
        {
            int id = usableCat.ID;
            Priority resolution = Priority.Load(id);
            resolution.Delete(Services.UserServices.User);
        }
    }
}

Please note that Category and priority do not have a common base type or interface that includes ID.

like image 852
learning Avatar asked Feb 03 '23 03:02

learning


2 Answers

void DeleteUsable<Ttype>(IEnumerable<Ttype> usables, IEnumerable<Ttype> collection, Func<int, Ttype> load)
{
     bool flag = false;
     foreach (dynamic usableCat in usables)
                {
                    foreach (dynamic catRow in collection)
                    {
                        if (usableCat.ID == catRow.ID)
                            flag = true;
                    }
                    if (!flag)
                    {
                        int id = usableCat.ID;
                        Ttype resolution = load(id);
                        resolution.Delete(Services.UserServices.User);
                    }
                }
}

Edit: call it:

if (Categories != null) 
   DeleteUsable(Category.LoadForProject(project.ID), Categories, Categoriy.Load); 
if (Priorities != null) 
   DeleteUsables(Priority.LoadForProject(project.ID), Priorities, Priority.Load);
like image 63
onof Avatar answered Feb 07 '23 11:02

onof


Let me suggest an alternative approach: Instead of factoring out the flag thing, use LINQ to remove the need for the flag loop:

if (Categories != null)
{
    foreach (var usableCat in Category.LoadForProject(project.ID))
    {
       if (!Categories.Any(row => usableCat.ID == row.ID))
            Category.Load(usableCat.ID).Delete(Services.UserServices.User);
    }
}
if (Priorities != null)
{
    foreach (var usablePri in Priority.LoadForProject(project.ID))
    {
        if (!Priorities.Any(row => usablePri.ID == row.ID))
            Priority.Load(usablePri.ID).Delete(Services.UserServices.User);
    }
}
like image 45
Heinzi Avatar answered Feb 07 '23 12:02

Heinzi