3
\$\begingroup\$

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
                });
            }
        }
    }
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Why do you use ToArray in one, but not the other? \$\endgroup\$
    – Pimgd
    Commented Jul 24, 2014 at 8:15
  • \$\begingroup\$ Thank you for pointing that out, did not notice it \$\endgroup\$ Commented Jul 24, 2014 at 8:17

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is true. I am going to look into the model design. \$\endgroup\$ Commented Jul 24, 2014 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.