Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to put the GetItems static method? + inheritance question

I have Item class:

public class Item {
    public long Id {get; protected set;}
    public string Name {get; protected set;}
}

and now I want to add a function that retrieve items from the db according to filters. This should be static method that returns Item[]:

public static Item[] GetItems(long? itemId, string itemName) {
    //Do Search in the db for items with Id=itemId (in case itemId is not null) and
    //with Name=itemName (in case itemName is not null)

    return itemsList.ToArray();
}

The question is where to put this method? 1. should I create a new class for this? How will I call this class? 2. should I put this method in Item class?

Another question: In case I want to inherit from Item class. How can I force the child classes implement such GetItems method?

like image 227
Naor Avatar asked Nov 29 '25 15:11

Naor


1 Answers

I would recommend a simple repository pattern implementation. You could create a class called ItemRepository that knows about your Item object and your DAL implementation. The repository would simply call into the DAL to get any data it needs and then return business objects back to the consumer.

This is very simple to implement, and if you create an interface to go along with it (ex: IItemRepository), unit testing becomes very easy because you'll be able to mock the repository and pass it along to any object that consumes it. If you make everything static, then testing is much harder, so I wouldn't recommend it.

As for inheritance: if you want to define general method signatures and properties that should be available on every Repository object, then use an interface to specify exactly what each repository should have in common. If you want to provide a base repository skeleton, then an abstract may be more fitting.

like image 155
Scott Anderson Avatar answered Dec 01 '25 05:12

Scott Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!