But there are some things unclear to me. Let's say I have a database with all kinds of cars. What is the best way to create the object "car"? A SQL-query instead the class?
SQL queries and classes are two completely independent concepts and they are not interchangeable.
You can't create objects out of SQL queries, but you can use an SQL query to retrieve the values for the properties of an object. There are two ways to go about this:
- The class knows about the database and retrieves the values itself when you create a new object.
- The class does not know about the database and relies on external code to provide the relevant values. These can come from a database or from elsewhere.
If you code it all yourself, the second way is easier, because you can split it up in more functions, which makes it easier to understand what each function does.
There are also lots of frameworks available that provide an ORM (Object Relational Model) component which does most of the hard work for you. There it depends on the framework architecture if the ORM component is based on the first or the second way.
And the other question is: how can I output a list of all cars? Do I need to create a object called "Garage" with has only one method within that selects all the cars from the database? Or does this kind of method belong in the "Car" object?
Although some ORM implementations do provide such methods as part of the "Car" class, they do not really belong there.
On the other hand, creating a "Garage" class just to provide a list of cars would also be overkill.
The pragmatic way is to have a method in the class that handles the database interaction for "Car" to retrieve a list of cars and if that happens to be "Car" itself, the so be it. IMO, it is more important to have all the code that deals with retrieving cars from the database close together than the purity of the solution. This method returns the cars as a list, array, hash or whatever collection type your language provides you.