Reputation: 55
I have a class in Active Record pattern. Lets call it "Car". So I have all my methods like insert, update etc but they work only on single object. What if I want to work on a list of these objects? Should I create a separate class lets say "CarCollection" that will be used to work on list of Car objects? Or should I create a method in my Car class that will return a list of Car object? I am a beginner in OOP but the second option (method that returns a list) seems kinda wrong.
Thanks for answers.
Upvotes: 0
Views: 1744
Reputation: 6185
It is standard practice to use Arrays, List or Dictionary. I like using Dictionaries because it is VERY quicker to link classes together with unique entries.
Create a class (Not a struct) called car.
You can use it in a Dictionary to enable Primary Unique key acceleration.
Public class Car
{
public string id;
public string name;
}
Create:
Dictionary<string, Car> carList = new Dictionary<string, Car>();
You can add this inside your method and pass it as parameters or create it global (according to your application)
To add:
Car car = new Car(){id = "1", Name="car1"};
carList[car.id] = car;
You can use Linq to link your classes together (almost like SQL): Basic LINQ Queries
Upvotes: 0
Reputation: 40431
Not a huge fan of the active record pattern, but if you're going this route, I'd expect the methods that return multiple cars would still live in your Car
class - you wouldn't use a separate class.
That seems to be the way Rails does it.
Upvotes: 0
Reputation: 44438
As you say yourself: you'll have to work with a collection of cars. The question is in what class you're going to store this list.
When you're just using it as a standalone example you can store the collection in the class that holds your main
method. In reality though you'll probably have a class Dealership
or something similar that logically contains a list of cars.
There are other posibilities like classes specific for performing actions on a list of objects like a CarManager
, but they are to be used with caution.
Upvotes: 2