Where should functions that deal with multiple objects sit?



I'm new to OOP and am getting a handle on Objects which store all the properties and functions/methods which make up and deal with an instance of the Object (singular) but where should functions that deal with multiples sit?

For example lets say we have a database table "Books" which stores all the details of a book. I then have a class with all the columns from the table as properties and some methods to retrieve, manipulate and save details about a (single) book.

Multiple parts of the site need to list all the books so it makes sense to create a function getAllBooks() but where should this go? Does it go in the Books class, maybe as a static method, or somewhere else, and if so where? Putting it in the Books class makes sense as it keeps all the book related code in one place but on the other hand we now have a function that deals with multiple books sitting in a class designed to deal with a single book, so I'm not sure how this is normally done.

Thanks in advance.


My best advice would be to use two classes: Books and Book - one a collection of Book objects and having methods to perform bulk operations on them; and the other will have properties/methods related to a single Book object.

For example, you might want to organize different topics like drama, art, music, fantasy, etc. books and then be able to get them, delete them, rename them etc. and so such bulk operations would belong to Books class.

But, if you want a single book related properties like its name, publisher, author, etc. it should belong to a Book class.

Answer: getAllBooks should be an instance method of Books class. Why not static? Because you might want to create different collections of books as well, so you might use different Books objects as well some day, and then in case you make it an instance method, you will benefit more.

Hope it helps!