I’m trying to wrap my head around OOP when building simple CRUD systems, using the Repository Pattern to handle object retrieval/saving to persistent storage.
I’ve already designed and implemented a system that doesn’t use OOP, just straight up get, insert, update and delete functions that contain SQL queries.
Non-OOP way
For example, for updating a customer I would call this function:
// PUT customer
function updateCustomer(idCustomer, data) {
db("customer").update(data).where("idCustomer", idCustomer);
}
OOP way
Now, to implement this in OOP using the Repository Pattern I would do something like:
// PUT customer
customer = customerRepo.getById(idCustomer);
customer.setData(data);
customerRepo.update(customer);
OOP way seems to require an extra DB roundtrip
This OOP pattern seems to require DB roundtrips since I need to:
- Instantiate a new customer object from the DB using the repo
- Update the data in the object
- Save the object back to the DB using the repo
Question
Isn’t my current, non-OOP way of doing things more efficient? If yes, are there any common solutions to these roundtrips when following the 2nd OOP method?
3
This isn’t right. You’re comparing two different things. A more fair and perfectly equal method for the second example would be:
// PUT customer
customer = Customer();
customer.setId(customerId);
customer.setData(data);
customerRepo.update(customer);
And in that scenario, you’re also only doing one query (the update) but it’s still more object-oriented. Your problem is that you’re creating a “strawman” argument, suggesting that getting the customer from the database first is somehow intrinsic to object-orientation and the pattern, but that’s not true. OOP, Repositories, and whether or not to get the data from the database first have nothing to do with each other.
13
I believe that for the simplest of CRUD models, even Repository is an overkill.
The main purpose of repository pattern is to allow to query rich object model, that can then be manipulated in OOP way. This sacrifices some DB queries to gain ability to manipulate data in “better” way than plain SQL.
But in your case, it seems that there is no need for rich domain model, as you seem to be fine working with plain SQL.