Reputation: 7030
private bool SearchFilter(object sender)
{
CommDGDataSource item = sender as CommDGDataSource;
if (FilterPropertyList.IsErrorFilter)
{
if (!item.Error)
return false;
}
if (FilterPropertyList.IsDestinationFilter)
{
if (!(item.Destination == FilterPropertyList.Destination))
return false;
}
if (FilterPropertyList.IsSourceFilter)
{
if (!(item.Source == FilterPropertyList.Source))
return false;
}
return true;
}
Above code works well but I was wondering if there is more of an elegant way to write the above code.
Upvotes: 1
Views: 131
Reputation: 185300
I do not think there is much merit in messing with boolean expressions, except maybe for simple modifications as mentioned in my comment. If you end up with ugly code you have a design which just is not that great.
In this case you could probably refactor the responsibities by:
Something like this Pseudocode:
foreach (var filter in filters)
if !filter.Filter(item) return false;
return true;
public interface IFilter
{
bool Filter(CommDGDataSource item);
}
public class ErrorFilter : IFilter
{
public bool Filter(CommDGDataSource item)
{
return item.Error;
}
}
public class DestinationFilter : IFilter
{
public string Destination { get; set; }
public bool Filter(CommDGDataSource item)
{
return item.Destination == Destination;
}
}
//etc..
Upvotes: 3
Reputation: 2821
You can make a bit more readable by making small alterations as below
private bool SearchFilter(object sender)
{
CommDGDataSource item = sender as CommDGDataSource;
if (FilterPropertyList.IsErrorFilter && !item.Error)
return false;
if (FilterPropertyList.IsDestinationFilter && item.Destination != FilterPropertyList.Destination)
return false;
if (FilterPropertyList.IsSourceFilter && item.Source != FilterPropertyList.Source)
return false;
return true;
}
Upvotes: 4