Assume an application with a rich domain model with many classes (e.g School
, Classroom
, Teacher
, Student
, Course
, Exam
, Submission
, …) linking to each other. Model and links are mapped to the database which uses appropriate FKs and constraints (without cascade delete). In the admin panel the user has delete buttons next to each object.
Attempting to delete an object has one of the following two outcomes:
- the object isn’t being referenced from any other object, so it is deleted
- the object is being referenced by at least one other object so it cannot be deleted. An alert is shown to the user.
I’ve got two ways to implement this:
- prior to executing the sql delete, do whatever queries are necessary to discover whether this object can be deleted. If it cannot, then alert user.
- go ahead and execute the sql delete and if that fails (due to the rdbms constraints) catch the sql exception and alert the user that it cannot be deleted.
Both ways work well. The first way allows me to give the user a detailed reason why the object cannot be deleted (e.g it is being referenced by 2 Course
s and 1 Classroom
). The second way allows me to solve the whole problem by not writing any constraints checking code and rely on the solid (and existing) implementation of the db.
Is there a reason why I should definitely choose one over the other?