DEV Community

Ski
Ski

Posted on

Short bits: writing fashionable functional code

Old and boring code:

interface Authenticated {
  username: string
  firstName?: string
  isAuthenticated: true
}

interface Anonymous {
  isAuthenticated: false
}

type User = Authenticated | Anonymous 

function greet(user: User) {
   if(user.isAuthenticated) {
      return 'Hello ' + (user.firstName || user.username)
   } else {
      return "I don't talk to strangers, bye"
   }
}

Enter fullscreen mode Exit fullscreen mode

It's functional, it's not bad, but it lacks in style. We need more swag! Monads are all the rage nowadays. Functional code without monads ain't no functional code. Let's throw in some to make code look more hip

interface User {
   username: string
   firstName: Option<string>
}

interface Anonymous {
}

function greet(someone: Either<User, Anonymous>) {
   return someone
       .mapLeft((user) => 
         'Hello ' + user.firstName
               .getOrElse(user.username))
       .orElse(() => "I don't talk to stranges, bye")
}
Enter fullscreen mode Exit fullscreen mode

How much better is this? Infinitely better!

And did you also noticed, we didn't just add swag, we removed the unnecessary boolean isAuthorized! We can identify users from anonymous by their political leaning left or right*. Less business specific jargon, more generalizations, better code!

*Monad inspired APIs, for example fp-ts, frequently refer to one of two possible types of values either as 'left' or 'right'

Discussion (0)