I'm fiddling around with OOP in building simple CRUD systems.
I've decided to focus on using the Repository Pattern for separating Object business logic and Object data persistence (actually saving the object in a persistent data store, i.e a database).
Saving a simple object is straightforward
class Customer {
setData(data) {
this.data = data;
}
}
// PUT Customer
customer = new Customer();
customer.setData(data);
customerRepo.save(customer);
But saving a composite object becomes a bit complicated
But what happens if my Customer class is now includes other objects that also need to be persisted in the DB?
In the following example, setting a customer's data also needs to create an
AuditTrail
which is a set of differences between the previous data and the new data passed in customer.setData()
.
AuditTrail
is a class and in this example it's a classic has-a relationship between Customer
and AuditTrail
class Customer {
setData(data) {
// instantiate an auditTrailCalculator with some constants from the DB
auditTrail = auditTrailRepo.create();
// `calculate()` produces a diff between the previous data and the new data
this.auditTrail = auditTrail.calculate(this.data, data);
}
getAuditTrail() {
return this.auditTrail;
}
}
// PUT customer
customer = Customer();
customer.setId(customerId);
customer.setData(data);
customerRepo.update(customer);
auditTrailRepo.insert(customer.getAuditTrail());
The above example looks clumsy.
- I'm instantiating the
AuditTrail
object using it's repo from within theCustomer
Object. - For performing the whole update of a Customer I clumsily:
- Instantiate a new Customer
- Set it's data
- Get it's auditTrail that was generated inside the object
- Save the AuditTrail to the DB using the
AuditTrailRepo
- Save the Customer to the DB using the
CustomerRepo
My questions:
- Is it correct to instantiate objects from their repo's from within other objects?
- Should I create a factory function instead, which instantiates both Objects,
Customer
&AuditTrail
and return a composition of the 2? - How should I handle saving this composite object?
AuditTrail
specific for Customer entity, or is it used by multiple entities?Customer
entity