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:
- Create - Return a boolean telling whether the create was successful or not
- Read - Return the object requested
- Update - Return a boolean telling whether the update was successful or not
- 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?
create
method that completes successfully should create the object. Acreate
method that fails should throw an exception. I'm hard-pressed to imagine a case where you would want the method to complete successfully without successfully creating the object and to rely on the client to check the return method and figure out that something went wrong.