BAM Weblog

How to stop functional programming

Brian McKenna — 2016-02-23

The following has never happened to me but I often hear stories.

You go into work and discover that a coworker isn't happy with some code you wrote because they don't understand it. They go to your manager and tell them that you're being a problem by writing code they don't understand. Your manager, being very skilled in conflict resolution, makes a technical decision to avoid whatever tool you used which caused the problem. In your case it was functional programming.

That's it. You've been told. No more functional programming.

The manager has figured out what's good for the business and you figure that listening is what's good for your job.

You get back to your desk and take a ticket from JIRA. You've got to add a page listing a person's coworkers to your internal employee directory. First you write a function you need.

def userCoworkers(u: User): List[Employee] =
  u.departments.flatMap(_.employees)

But it's pure. You're doing functional programming! Stop

def userCoworkers(u: User): List[Employee] = {
  val coworkers = ListBuffer[Employee]()
  for { d <- departments }
    coworkers ++ d.employees
  coworkers.toList
}

Well, there's a side-effect involved, but the whole method is pure. You're still doing functional programming!

def userCoworkers(u: User): List[Employee] = {
  logger.info("Collecting coworkers")
  val coworkers = ListBuffer[Employee]()
  for { d <- departments }
    coworkers ++ d.employees
  coworkers.toList
}

Now the method has 1 external side-effect. Is that enough? With "no functional programming" you've been given a lower-bound of 1 side-effect per method but we don't really know what the ideal number is. Hopefully you can slip it through code review.

After this exercise you've learned how easy it is to not do functional programming.

You show it to your product manager. They didn't realise how many coworkers the average person had. The page is huge. They ask you to just change it to a number.

You're going to have to add numbers together. Without being pure. You're going to have to think about this one.

Maybe you should ask your manager how to do it. Good luck.

Please enable JavaScript to view the comments powered by Disqus.