Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good return-type pattern for designing Scala API's?

Tags:

scala

I see this type of pattern (found this example here) quite often in Scala:

class UserActor extends Actor {
  def receive = {
    case GetUser(id) =>
      // load the user, reply with None or Some(user)
      val user: Option[User] = ... 
      sender ! user
    case FindAll() =>
      // find all users
      val users: List[User] = ...
      sender ! users
    case Save(user) =>
      // persist the user
      sender ! Right(user)
  }
}

So depending on the call you get: Option[User], List[User], Right[User]. This approach is fine! I'm just asking out of interest if this is optimal? For example (and this may be a bad one): Will it make API's better or worse to try and generalise by always returning List[User]? So when a user is not found or if a save fails, then the list will simply be empty. I'm just curious.... any other suggestions on how the above 'pattern' may be improved?

I'm just trying to identify a perfect pattern for this style of API where you sometimes get one entity and sometimes none and sometimes a list of them. Is there a 'best' way to do this, or does everyone role their own?

like image 757
Jack Avatar asked Aug 07 '12 01:08

Jack


2 Answers

The return types should help clarify your API's intended behavior.

If GetUser returned a List, developers might get confused and wonder if multiple users could possibly be returned. When they see that an Option is returned, they will immediately understand the intended behavior.

I once had to work with a fairly complex API which provided CRUD operations that had been generalized in the manner you describe. I found it to be difficult to understand, vaguely defined, and hard to work with.

like image 57
dbyrne Avatar answered Oct 01 '22 19:10

dbyrne


In my opinion it is a very good pattern for API design.
I use very often Option as return type of my functions, if I want to return a single element, obviously because I don't need to deal with null. Returning a Seq is naturally for multiple elements and Either is optimal if you want to return a failure-description, I use it often while parsing I/O. Sometimes I even combine the Seq with one of the others. You likely don't know the preferences and goals of an user of your API, so it makes sence to provide all of these return-types to make the user feel as comfortable as possible.

like image 23
tgr Avatar answered Oct 01 '22 19:10

tgr