DEV Community

Ski
Ski

Posted on • Edited on

Writing fashionable functional code

Old and boring code:

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

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 Authenticated {
   username: string
   firstName: Option<string>
}

interface Anonymous {
}

function greet(someone: Either<Authenticated, 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!

Which style do you prefer more? Leave comment.

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

Top comments (0)