Today we will dive in the Active Record data source patterns for enterprise applications
A. Active Record
A.1 Definition
An object carries both data and behavior. Much of this data is persistent and needs to be stored in a database. Active Record uses the most obvious approach, putting data access logic in the domain object. This way all people know how to read and write their data to and from the database.
A.2 How it works ?
Each Active Record is responsible for saving and loading to the database and also for anyndomain logic that acts on the data. This may be all the domain logic in the application, or you may find that some domain logic is held in Transaction Scripts with common and data-oriented code in the Active Record.The data structure of the Active Record should exactly match that of the database: one field in the class for each column in the table. Type the fields the way the SQL interface gives you the data—don’t do any conversion at this stage.
A.3 Composition of an Active Record Class
The Active Record class typically has methods that do the following:
• Construct an instance of the Active Record from a SQL result set row
• Construct a new instance for later insertion into the table
• Static finder methods to wrap commonly used SQL queries and return
Active Record objects
• Update the database and insert into it the data in the Active Record
• Get and set the fields
• Implement some pieces of business logic
A.4 When to use it ?
The author of the book says :
Active Record is a good choice for domain logic that isn’t too complex, such as creates, reads, updates, and deletes. Derivations and validations based on a single record work well in this structure.
Active Record is a good pattern to consider if you’re using Transaction Script and are beginning to feel the pain of code duplication and the difficulty in updating scripts and tables that Transaction Script (110) often brings. In this case you can gradually start creating Active Records and then slowly refactor behavior into them.
A.5 What's in the Real World
In the real world we have ActiveRecord (Ruby on Rails), Eloquent (Laravel / PHP), some implementations of JPA (Java Persistence API), Django ORM (Python)
When you use those ORM you'll face Active Record pattern because in each the class contains the domain information and can do the operations directly againts the database
Conclusion : The problem is the coupling between the domain and the database, and that's why the next time , we will talk about Data mapper 😉
Top comments (0)