0

Let's say I have to develop an API which will talk to the database and will have some methods to do CRUD operations. Let's say I have a method that fetches a List of something based on some criteria:

def fetchUsers(criteria: Criteria): List[User] = ???

If I cannot find any users for the given Criteria, should I return an empty List or it is a good practice to return a Try[List[User]] and if I do not find any users, I return a Failure?

What is considered a good practice?

4
  • Is it an error if you don't find any users? If so you probably want to use a non-empty list type for the success case e.g. Try[NonEmptyList[User]]. Commented Apr 11, 2017 at 12:42
  • Ok, in that case is it a wise idea to clutter my API with Try[_]? Commented Apr 11, 2017 at 12:43
  • In which case? If it's always an error then you should represent that in the type. If it's not then return a List[User] and let the caller decide how to handle the empty case. Commented Apr 11, 2017 at 12:45
  • Use a Try[_] only if there's value in having the calling code handle the error case. i.e., the calling code wants to be given a chance to do something in case of error (log it, present a message to the user, retry, etc). For a lot of cases though (db connection error, out of space, etc) there's not much the calling code can do (true exceptional case), and I think it's better to use an exception that is then caught at the top. Commented Apr 11, 2017 at 16:50

1 Answer 1

1

This question does not have a definite answer, it depends on your preferences and your API requirements.

  1. If an empty list an acceptable response, return an empty list
  2. If there is always must be a user, you can throw an Exception, and the calling method should handle it
  3. Return Either response or error, in your case you have Try, which is basically the same for this case.

All solutions are acceptable and depend on requirement.

I personally would prefer 1st or 2nd solutions, because

  1. If error happens, the caller does not necessarily want's to handle it, so it can be handled anywhere on the calling stack
  2. RuntimeExceptions can happen regardless, for example, If you have DB connection problems and even if you return Try in your method, does not mean that there would not be an Exception before return statement reached
  3. It leaves code cleaner
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.