HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Changing these two functions into one function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theseintofunctiontwoonefunctionschanging

Problem

I have two functions that are similar. The only differences is that they're using two different models. How can I change them into one function?

ITagRepository tagRepo = new TagRepository();
 ICategoryRepository catRepo = new CategoryRepository();

public void AddTagsDontExist(string tags)
    {
        var allTags = tagRepo.GetAllQueryAble();
        string[] tag = tags.Split(',');

        foreach (var item in tag)
        {
            if (allTags.Where(e => e.Name.Contains(item)).Count() == 0)
            {
                tagRepo.Add(new Tag
                 {
                     Name = item.ToString(),
                     DateAdded = DateTime.Now,
                     LastModifiedDate = DateTime.Now,
                     IsDeleted = false
                 });
            }
        }
    }

    public void AddCategoriesDontExist(string Categories)
    {
        var allCategory = catRepo.GetAllQueryAble();
        string[] Category = Categories.Split(',');

        foreach (var item in Category)
        {
            if (allCategory.Where(e => e.Name.Contains(item)).Count() == 0)
            {
                catRepo.Add(new Category
                {
                    Name = item.ToString(),
                    DateAdded = DateTime.Now,
                    LastModifiedDate = DateTime.Now,
                    IsDeleted = false
                });
            }
        }
    }

Solution

You need to think about the underlying model. Have a think about isA/hasA. Depending on what you conclude...

  • Are the types defining similar interfaces? You may find that the date info is like a label that both object types have attached to them. (It looks that way.) Define an interface that contains the common names. Have each of the two types implement it. Now you can use just one loop.



  • Is one of them actually a member of the other? Then define it that way. Your loop will get smaller.



Bottom line is that highly repetitive code should make you think about whether your model is correct.

Context

StackExchange Code Review Q#57899, answer score: 2

Revisions (0)

No revisions yet.