Search code examples
api-design

API Design: pass id or complete object


Assume, there is a person and an address object. The person does not hold a reference to the address, but only its id. E.g:

Person {
  id: PersonId,
  addressId: AddressId,
  name: String,
  ...
}

Address {
  id: AddressId,
  street: String,
  ....
} 

The model is legacy and cannot be changed.

Now you want to set an address on the person, how would you design the API for this call. There are only two possibilities you can choose from:

void setAddress(PersonId id, Address address)

void setAddress(Person person, Address address)

As you can see, the only difference is, that one time only the id of the person is sent, and one time the complete person object.

Which one would you choose and why?

PS: This question arises from an internal discussion at work, I am just interested in how this is seen by other programmers / designers.


Solution

  • I would choose the first one, so the caller of this API only needs to provide minimum information and the API implementation gets all information needed to proceed the call (in your example get the person from a database or something else). The second one does not seem logic to me, because if you pass the whole person object, you would also have to fetch the person from your data source (object could have been modified during the call), so you would pass way more information than needed in this case.