I might start by saying that I am aware that usually there's a Repository layer
bookRepository.persist(book)
that abstracts the interaction with the database, but something about using the model directly feels really tempting, as in
book.persist()
This second option would also allow for the model to persist itself when changes are made, which seems pretty useful:
void updateAuthor(string newAuthor){
this.author=newAuthor
this.persist()
}
Assuming that it is a non relational database and its persistence logic is as simple as
bookDatabase.update(bookId,book)
Should the model know how to persist itself?
In what situations (if any) would this approach would make sense?
EDIT: Just want to point out that I selected the answer which better described the conditions that had to be met in order for this to make sense. If you're looking for more details on why usually it doesn't, the other replies do a great job on explaining it.
bookDatabase.update(bookId,book)
" - sorry, but that statement makes no sense to me. This shows only the persistence API, the logic is what happens inside theupdate
method. A model which "knows" how to persist itself means the logic is implemented in thebook
class, and not in thebookDatabase
class. Or do you have a genericupdate
method in mind, and anbook
class which has enough meta data to make that work? Even then, thebook
object would require to hold a reference to thebookDatabase
object to make this work.MongoClient(address)["databaseName"]["collectionName"].update({"id":id},book})
, given that the whole theMongoClient(address)["databaseName"]["collectionName"]
part could be stored staticly as "bookDatabase"