DEV Community

Ski
Ski

Posted on • Edited on

2 2

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'

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay