Refactoring null check before adding to Func collection with different predicates [closed]

Posted on

Problem

I’d want to refactor that if ladder but I’m not sure how to do that or whether it is even possible

public async List<ComplexObject> Generate(DateTime? data1, DateTime? data2, string FirstName, string SecondName)
{
    var ListOfPredicates = new List<Func<ComplexObject, bool>>();

    if (data1.HasValue)
    {
        ListOfPredicates.Add(new Func<ComplexObject, bool>(x => data1.Value <= x.data1));
    }
    if (data2.HasValue)
    {
        ListOfPredicates.Add(new Func<ComplexObject, bool>(x => data2.Value >= x.data2));
    }
    if (!string.IsNullOrEmpty(FirstName))
    {
        ListOfPredicates.Add(new Func<ComplexObject, bool>(x => x.FirstName.ToLower() == FirstName.ToLower()));
    }
    if (!string.IsNullOrEmpty(SecondName))
    {
        ListOfPredicates.Add(new Func<ComplexObject, bool>(x => x.SecondName.ToLower() == SecondName.ToLower()));
    }

    (...)
}

I thought about something like this:

switch(true)
{ 
    case expression (e.g x > 5):
}

Solution

One simple refactoring you could do is to use an extension method to simplify your code.

public static void AddIf(this List<Func<ComplexObject, bool>> list, bool condition, Func<ComplexObject, bool> item)
{
    if (condition)
        list.Add(item);
}

public async List<ComplexObject> Generate(DateTime? data1, DateTime? data2, string FirstName, string SecondName)
{
    var ListOfPredicates = new List<Func<ComplexObject, bool>>();

    ListOfPredicates.AddIf(data1.HasValue, new Func<ComplexObject, bool>(x => data1.Value <= x.data1));
    ListOfPredicates.AddIf(data2.HasValue, new Func<ComplexObject, bool>(x => data2.Value >= x.data2));
    ListOfPredicates.AddIf(!string.IsNullOrEmpty(FirstName), new Func<ComplexObject, bool>(x => x.FirstName.ToLower() == FirstName.ToLower()));
    ListOfPredicates.AddIf(!string.IsNullOrEmpty(SecondName), new Func<ComplexObject, bool>(x => x.SecondName.ToLower() == SecondName.ToLower()));
}

Leave a Reply

Your email address will not be published. Required fields are marked *