简体   繁体   中英

Who should save object to persistent memory

I am currently learning UML. I looked everywhere but couldn't find an answer. Should the creator of an object be the one to always saves it in persistent memory via a data access object or by an expert, is an object better to save itself via a data access object in persistent memory?

Main alternatives

UML is agnostic in this regard. It depends of your architectural choices:

  • A popular approach is Repository objects that act as a kind of collection that hides the database. You'd insert, retrieve, suppress or update elements in the repository and the repository takes care of the database.
  • Another popular approach is the active record . Each persistent object is in charge of inserting, updating or deleting itself in the database.
  • There are several other approaches.

How to chose?

The scenario you describe corresponds to the second one. It is a tempting approach for CRUD oriented application with little domain logic. But it has several drawbacks that limit their suitability:

  • it does not enforce proper separation of concerns (see also Songle Responsibility Principle).
  • it couples your system tightly to the database and it might be difficult at a later stage to change the inderlying database.

Moreover, you'd need to care also for transactional logic (ieeither complete a set of related changes or cancel them all), or to avoid that several objects in memory correspond to the same object in the database. While not impossible, this is more difficult with active records.

How to deepen your understanding of these alternatives?

The most comprehensive book on this topic is Fowler's “ Patterns of enterprise application architecture ”. Another book worth to invest in for deepening what's behind repositories, is Evans' DDD bible . ( Imho, you will save years of on the job experimentation and discovery by reading both books. You can then use the saved time to deepen your skills on other innovative domains ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM