I have a situation in C# web api function where I will need to retrieve a list of different objects from my database and need to implement some logic by invoking various methods.
How can I better achieve this by writing a Generic function for all 3 objects
example
there are two scenarios of locking list
whole list is locked (do not proceed and throw exception if whole list is locked)
only a single entity is locked (filter and remove this element if locked from the list)
List<Object1> list1;
List<Object2> list2;
List<Object3> list3;
private FilterLockedEntities(List<Object1> list1){
if(list1[0].isListLocked) //whole list is locked
throw ValidationException("Message")
list1.RemoveAll(a => a.IsLocked); //filter locked entities
//some more logic common to all
}
private FilterLockedEntities(List<Object2> list2){
if(list2[0].isListLocked) //whole list is locked
throw ValidationException("Message")
list2.RemoveAll(a => a.IsLocked); //filter locked entities
//some more logic common to all
}
private FilterLockedEntities(List<Object3> list3){
if(list3[0].isListLocked) //whole list is locked
throw ValidationException("Message")
list3.RemoveAll(a => a.IsLocked); //filter locked entities
//some more logic common to all
}
I have the same logic in each of the three function but with List of different entities.
Is there a way where I can use a single method instead of three different functions its hard to maintain due to redundant logic. If there is a change in logic it needs to be updated in all the three places.
Create a new interface:
public interface ILockable
{
bool isListLocked();
}
Then make your object inherit the interface in their class declarations:
class Object1 : ILockable
{
public IsLocked()
{
// Your code here...
}
}
...
class Object2 : ILockable ...
class Object3 : ILockable ...
Then make your function accept a List
of ILockable
objects:
private FilterLockedEntities(List<ILockable> list)
{
// Your code here...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With