Is this a good return type template for designing a Scala API?

I see this type of template ( 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) } } 

Therefore, depending on the call received: Option [User], List [User], Right [User]. This approach is great! I'm just asking out of interest if this is optimal? For example (and this may be bad): will this make the API better or worse to try to generalize, always returning List [User]? Therefore, when the user is not found or if the failure failed, the list will simply be empty. I'm just wondering ... any other suggestions on how to improve the above "template"?

I'm just trying to determine the perfect template for this API style, where you sometimes get one object, and sometimes none, and sometimes a list of them. Is there a “better” way to do this, or does everyone play a role?

+6
source share
2 answers

Inverse types should help clarify your behavior, the intended API.

If GetUser returned the List , developers might get confused and consider whether it is possible to return multiple users. When they see Option returning, they will immediately understand the intended behavior.

I had to work with a rather complex API that provided CRUD operations that were generalized in the form in which you are describing. I realized that it’s hard to understand, vaguely determine and hardly work.

+15
source

In my opinion, this is a very good sample for the design of the API. I very often use Option as the return type of my functions if I want to return a single element, obviously, because I don't have to deal with null . Seq return, of course, for several elements and Either is optimal, if you want to return a description of the error, I often use it during parsing I / O. Sometimes I even combine Seq with one of the others. You probably don’t know the preferences and goals of the user of your API, so it provides all of these return types to make the user as comfortable as possible.

+1
source

Source: https://habr.com/ru/post/922253/


All Articles