I'm constructing a set of filter-classes which will all have the same method 'Applyfilter'.
How should I define the interface which contains apply filter? The only issue is that apply filter can take a second argument of various types e.g. int, string, Lists. Some pseudo code.
Current Interface method:
Data ApplyFilter(input-data, object value);
Example:
public *data* ApplyFilter(input-data, ***string color***) {
// Do something with to data with the color string
}
public *data* ApplyFilter(input-data, ***List<int> size***) {
// Do something with to data with the size list
}
If I defined the type of argument two as an 'object'. I can do some validation within the ApplyFilter function. As mentioned here: Check if Object is Dictionary or List but is there a better way to do this?
CodePudding user response:
An approach would be to use Generic
For exemple:
public interface Filter
{
string ApplyFilter<T>(string inputData, T secondArgument);
}
public class MyImplementationClass : Filter
{
public string ApplyFilter<T>(string inputData, T secondArgument)
{
throw new NotImplementedException();
}
}
public class UseCase
{
MyImplementationClass myImplementationClass = new MyImplementationClass();
void applyFilter()
{
string color="";
myImplementationClass.ApplyFilter<string>("input-data", color);
List<int> size=new List<int>();
myImplementationClass.ApplyFilter<List<int>>("input-data", size);
}
}
CodePudding user response:
For centralized code , you can create a filter properties class
public class FilterProperties
{
public string Color { get; set; }
public List<int> Sizes { get; set; }
//add filter properties as you want
}
then create one ApplyFilter method that takes this class as an argument
public object ApplyFilter(List<object> inputData , FilterProperties filterProperties)
{
var querable = inputData as IQueryable<object>;
// if the color property has value , then filter with it ,else don't filter
if (!string.IsNullOrEmpty(filterProperties.Color))
{
querable = querable.Where(//your condition
);
}
if(filterProperties.Sizes.Count > 0)
{
querable = querable.Where(//your condition
);
}
}
now you have one filter method to avoid duplicating code , and have the flexibility to add new optional Filters easily