Jevgenij Evll
Jevgenij Evll

Reputation: 1889

OOP design for deletion of an object with many dependent objects

I would like to know a best way to design a deletion of an object, with triggers deletion of many dependent objects.

Here is an example. There is an Employer class. When an employer is deleted, all its jobs, invoices are deleted. When a job is deleted its category selection is deleted as well. And so on. So as you can see deletion of Employer triggers deletion on many more objects. The problem is that I have to pass many arguments required for deletion of dependent objects to the delete method in the Employer class.

Here is a simplified example. Imagine a class Main. When a Main object is deleted, objects Dep1, Dep2 have to be deleted as well. When Dep1 is deleted, Dep11 has to be deleted as well. If delete methods look like this: Dep1.delete(arg1), Dep2.delete(arg2), Dep11.delete(arg3), then the delete method on Main has to look like this: Main.delete(arg1, arg2, arg3). You see? The more objects depend on the Main - more arguments will be needed for deletion.

I must also point out that I am interested in deletion from the database, i.e. deletion in its "business logic" sense. I do not even unset "deleted" objects in the delete method.

What options I have considered:

Upvotes: 1

Views: 332

Answers (3)

Marcin
Marcin

Reputation: 49846

If you are passing parameters to deletion functions, you are making a mistake.

Each object on which you call your deletion function should be able to identify the other objects which it is the parent of.

I emphasise object because it sounds like you are coming at this from a relational perspective.

Upvotes: 1

Alex D. Campbell
Alex D. Campbell

Reputation: 126

In my line of work I don't have to write much code to delete, so take my advice with a grain of salt. It might help to look at how these objects/records are created, and handle the deletion in the same way. For example, if the create logic is like this:

  1. Create Employer
  2. Create Invoice
  3. Associate Invoice with Employer

than maybe the delete logic should look like this:

  1. Remove Associations of Invoice(s) with Employer
  2. Delete Invoice(s)
  3. Delete Employer

As long as the entities are created in a consistant way, deleting them in the reverse order should also prove to be consistant.

Upvotes: 0

Jitendra kumar jha
Jitendra kumar jha

Reputation: 243

Try to use the Composition in such a way that once u make the employee reference less other will become automatically reference less....

Other way is to take the help of nested class , if the top most encapsulating class will get unreferenced other will also be automatically get unreferenced..(but make sure u are not pulling out the reference of nested class(say your inner class) out in some other class.)

Upvotes: 0

Related Questions