3 ms·
I would not label it bad practice. Honestly, I'm not sure if there is a simple rule to decide what is good or bad. Using an ORM is not necessarily mixing in DB
by qznc 9y ago
I would not label it bad practice. Honestly, I'm not sure if there is a simple rule to decide what is good or bad. Using an ORM is not necessarily mixing in DB interactions.
Here is an example from the Django documentation [0]:
selected_choice.votes += 1
selected_choice.save()
The offender in my eyes is the save() method call. The first line is business logic, but the second line has nothing to do with business logic. It might be slightly better to hide the database interaction in the object itself, create a special method, and change the two lines into:
selected_choice.increaseVotes(1)
As a counter argument, I dislike code which hides database accesses, because that easily leads to code which does way to many of them and thus is unnecessarily slow.
[0] https://docs.djangoproject.com/en/2.0/intro/tutorial04/ https://docs.djangoproject.com/en/2.0/intro/tutorial04/
- acdha 9y agoThe second argument should also include correctness: if I increment two variables on that object (e.g. votes and last_vote_time) it needs to be a single atomic operation to not create a hard to debug race condition. It seems better to explicitly say when to save things rather than hope that every custom method does that and you have a method for every combination of updates. The Django ORM also has another case to consider: bulk updates, where separating logic from serialization makes a huge performance win easy and safe.