joesan
joesan

Reputation: 15385

Scala Functional API Design

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?

Upvotes: 0

Views: 199

Answers (1)

mavarazy
mavarazy

Reputation: 7735

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

Upvotes: 1

Related Questions