How to deal with aggregation and composition in RE

2019-05-11 10:35发布

问题:

I have created the following entities, Book, Chapter and Feedback. The Book have many Chapter entities, and it also have many Feedback entities. Since no Chapter entities could live by them self they are part of the Book composition. The same applies to the Feedback entitiy.

My question is whether objects that are part of an composition should have their own URIs in a RESTful system? Such as:

/books/1/chapters (With POST, DELETE, PUT operations) 
/books/1/feedback (With POST, DELETE, PUT operations)

Or should it be threated like this:

/books/1 (With POST, DELETE, PUT operations only on the book)

The last URI mean that the users of the API would have to add a feedback to an array of the book and then update the whole book entity.

And does it make sense to call the relationship between books and chapters "composition + aggregation" since chapters doesn't belong to any other object and their life cycle is dependent of book?

回答1:

My question is whether objects that are part of an composition should have their own URIs in a RESTful system

Yes, most definitely. It makes it significantly easier to access and manage specific parts of the entity representation when those parts are independently addressable. Rather than requiring clients to retrieve the whole representation each time just too update small portions of it, they can focus on just the one part that needs to be modified. It also greatly simplifies access control, where certain endpoints may be available to particular callers but not too others.

The one constraint to be kept when defining sub-resource URI's is that they always be defined within the scope of their parent resource (as you are already showing in your example).

And does it make sense to call the relationship between books and chapters "composition + aggregation" since chapters doesn't belong to any other object and their life cycle is dependent of book

It makes sense to refer to the relationship as composition. Aggregation would mean that the sub-resource (chapter) could exist outside the scope of its parent (book), which in this case it cannot. An example of an aggregation would be something like an address, which could be associated to a person, or an organization.