Skip to content

Option or union with empty tuple

Jonathan edited this page Aug 30, 2018 · 4 revisions

In Firefly we have two ways to represent the absence of a value, first is with Option type and Optional/Nullable notation (?), the second is with Union types, using empty tuple as possibility (()). But, which one is better?

First, you should understand that Optional/Nullable notation after a type represents an Option implicitly.

Now let dive into examples that use both of them:

type UserName(_: String)
fun query(userName: UserName): Option<User> =
  this.database.query(#{"{username: {0}}" where 0 -> userName}).any()

fun change(current: UserName, new: UserName): Result<Operation, Error> =
  query(current)
    .and()
    .set(_.username).to(new)
    .ok(Operation(Change(UserName, from=current, to=new)))
    .fail(NotFound(User, By(UserName(current))))
  
fun query(userName: UserName): User|() =
  this.database.query(#{"{username: {0}}" where 0 -> userName}).any() ? ()

fun change(current: UserName, new: UserName): Result<Operation, Error> =
  query(current)
    .match(
      User -> 
        some(user).and()
          .set(_.username).to(new)
          .ok(Operation(Change(UserName, from=current, to=new)))
          .fail(Error())
      () -> fail(NotFound(User, By(UserName(current))))
    )

Which one is more readable and fun to work with?

Clone this wiki locally