Java – Return values for CRUD methods

apiapi-designjavareturn-typeweb-api

I'm writing a basic web API in Java that does what almost all others do: take input, validate it, then do CRUD operations on the DB. I've written several APIs before, and I've pretty much already figured out what constitutes a good response back to the client.

However, like most APIs, there are several layers of objects invoked between the front-door client API object and the code that actually executes queries against the database. I've always struggled to know what those database interaction objects should return back to the functions calling them.

I imagine that on errors I'll be throwing exceptions and catching them farther up the call stack. However, what do I return on successes? Here's what I've used before:

  1. Create – Return a boolean telling whether the create was successful or not
  2. Read – Return the object requested
  3. Update – Return a boolean telling whether the update was successful or not
  4. Delete – Return a boolean telling whether the delete was successful or not

I feel comfortable with the Read and Delete returns, because I can't think of what else you'd return in those situations. However, I have no idea what the best practice would be for return values from create and update functions. Should I return a new object with the updated values? Should I modify the object that was passed in? Should I just return a boolean value denoting success or failure?

Best Answer

On create, I usually return the ID of the entity I just created. On an update, I return the object I just updated. Delete I usually don't return anything.

In the case of create, the most interesting part is the id of what was created. You throw an error if you couldn't create, so the boolean value you use isn't that interesting. You could also return the entire object with the ID.

On an update, returning the object with any modified fields (either by the updater or someone else) makes the most sense.

Delete either works or you throw an exception, no need for a return value.

Related Topic