{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "@id": "https://www.vidyasource.com/blog/business-case-for-functional-programming/",
  "url": "https://www.vidyasource.com/blog/business-case-for-functional-programming/",
  "mainEntityOfPage": "https://www.vidyasource.com/blog/business-case-for-functional-programming/",
  "headline": "The Business Case for Functional Programming",
  "description": "Learn how functional programming can make your teams more productive than you ever imagined.",
  "datePublished": "2018-09-18T00:00:00.000Z",
  "author": {
    "@type": "Person",
    "name": "Neil Chaudhuri",
    "jobTitle": "President",
    "url": "https://www.linkedin.com/in/neil-chaudhuri/",
    "sameAs": "https://www.linkedin.com/in/neil-chaudhuri/"
  },
  "publisher": {
    "@id": "https://www.vidyasource.com/#organization"
  },
  "image": "https://www.vidyasource.com/img/blog/functions.jpg",
  "keywords": [
    "Agile",
    "Scrum",
    "Java",
    "Scala",
    "Go",
    "Technical Debt",
    "ScalaCheck",
    "REST",
    "Agile",
    "Project Management",
    "Software Engineering",
    "Programming",
    "Functional Programming",
    "Testing",
    "Continuous Integration"
  ],
  "articleBody": "Functional programming isn't exactly a fun topic anywhere outside of technical conferences and\n[The Big Bang Theory](https://www.youtube.com/watch?v=k0xgjUhEG3U). Even software engineers who love\ncode often tune out when they hear terms like [monad](http://stackoverflow.com/questions/44965/what-is-a-monad)\nand [referential transparency](https://stackoverflow.com/questions/210835/what-is-referential-transparency).\nBut if you are a technical manager or executive, heads up. Functional programming will limit your\n[technical debt](tags/technical-debt) so you build better\nsoftware faster than you imagined and will earn you the Tesla you always wanted.\n\nHere's why.\n\n## Code Reuse For Real\n\nCode reuse is a vision long offered by object-oriented (OO) languages like Java but has proven to be a\nmyth--like the Fountain of Youth and fat-free ranch dressing that's edible. In practice OO languages tightly couple data\nwith behavior, so it's hard to extract the behavior into reusable code others can use.\n\nIn functional programming (FP), *behavior* is the first-class citizen--in the form of functions that deterministically transform single inputs\ninto single outputs. This empowers engineers to compose functions into data flows where providing data to an initial function sets off a\n[Rube Goldberg machine](https://www.youtube.com/watch?v=kr_z37TgQO4) where the output of that function\nbecomes the input to the next function and so on down the line. You can also mix and match functions to create new data flows.\nIn the end, building software is basically like [building Legos](https://cdn-images-1.medium.com/max/1600/1*yGnDGRW4pTgmcDUi4oC8Uw.png).\nThis makes your code easier to understand--or in FP vernacular, \"reason about\"--and makes code reuse\na natural outcome of your day-to-day process.\n\n## Satisfaction Guaranteed. Literally.\n\nIf you manage OO projects, you may have heard of \"design patterns,\" which came out of a\n[book by a group of expert software engineers](https://en.wikipedia.org/wiki/Design_Patterns) known as the \"Gang of Four.\"\nDesign patterns offer suggestions for modeling code that solves common problems in a manner resilient to change.\nIn other words, thoughtfully applied patterns reduce your time to market so your team won't have to work the weekend\nafter your mercurial client changes course. That spares you a lot of resentment and\nthe cost of at least two pizzas--more [if I am on your team](https://www.vidyasource.com/consulting/).\n\nSounds great, right? It is! Sort of.\n\nThe problem is design patterns are opinion--expert opinion borne of decades of experience to be sure--but opinion nonetheless.\nAs programming languages and technical challenges evolve, there is no way to know how well they will stand the test of time. The\n[Singleton](https://www.geeksforgeeks.org/singleton-design-pattern/) design pattern, for example, has\nbeen [particularly controversial](https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons).\n\nOn the other hand, FP offers *mathematical* guarantees that the code you write is sound. The laws that govern\nit--[Type theory](https://en.wikipedia.org/wiki/Type_theory) and\n[Category theory](https://en.wikipedia.org/wiki/Category_theory) in particular--are not vulnerable to the whims of the broader\ntechnology landscape. Math isn't opinion.\n\nThis is why [Elm](https://elm-lang.org/) developers often report\n[\"0 runtime exceptions\" in production](https://www.slideshare.net/InfoQ/fullscale-elm-in-production), which sounds like\nfat-free ranch dressing that's edible to JavaScript developers resigned to a lifetime of `undefined`\n[errors](https://stackoverflow.com/questions/48333993/javascript-function-is-undefined-only-in-ie11) at runtime that would make\n[Sisyphus](https://www.britannica.com/topic/Sisyphus) cry. That's a huge win, but note \"0 runtime exceptions\" isn't the same\nas \"0 bugs.\" No paradigm can guarantee that. FP can't stop a developer surviving on Red Bull after staying up all night playing\nFortnite from calculating the total price of a customer's shopping cart by subtracting rather than adding. Still, FP\n--along with companion principles like [immutability](https://www.quora.com/Why-is-immutability-important-in-functional-programming)--\nprovides safeguards making it harder to write bugs and uncovers the ones your team *does* write more quickly and cheaply by virtue of\nmathematical guarantees that endure.\n\n## More Quality in Less Time\n\nThat shopping cart bug should be caught by tests, but most software engineers look at unit and integration testing like [flossing](https://www.dentalassociates.com/application/files/4214/7760/0003/flossing-is-beneficial-1.jpg).\nThey get why it's necessary but don't look forward to it at all. The consequences are particularly profound\nwhen leadership acts as an enabler. Not that you would ever do this, but many technology leaders find testing takes so long that\nthey are satisfied with a few token tests. The result is illusory productivity. Delivering a mess of alpha- and beta-quality features\nquickly might impress unsuspecting clients at first, but watch their enthusiasm wane when the inevitability\nof bug fixes orders of magnitude more expensive becomes apparent.\n\nTo be fair, developer testing can be a pain. Test setup is slow because you need to\nmock or stub your inputs along with any dependencies necessary for the code to execute a scenario like databases or REST clients. This\noften requires an open-source library like [Mockito](https://site.mockito.org/) or [unittest.mock](https://docs.python.org/3/library/unittest.mock.html).\n\n*And* you have to repeat this process for multiple happy-path scenarios and some\narbitrary number of alternate-path and error scenarios.\n\n*And* you need\nto write your tests efficiently so that the test suite doesn't take hours to run in continuous integration.\n\nAll of that is cumbersome, but FP can make it easier.\n\nThe first thing you should do--FP or not--is to reduce dependencies. Lots of dependencies is a [smell](https://martinfowler.com/bliki/CodeSmell.html).\nThen replace the remaining object dependencies\nwith functional dependencies. Gradually have the engineers evolve their APIs towards *behavior* rather than objects.\n\nFor example, let's say one of your user stories involves fetching a username by an identifier to use it for subsequent business logic.\nTypically, that code has a dependency on some object that knows how to read from the database. Testing the logic in isolation\nrequires the overhead of writing your own stub for that database object or importing a library to mock it. What if instead the\ndependency was on a simple function that takes a number (the identifier) and returns a string (the username)? In Scala,\nthat might look like `Int => String`. This\nelegantly decouples the logic from the database concern or any particular family of objects; all it knows is\n\"If I give this function the right identifier, I get the username back.\" Even better, I can stub that function really easily:\n\n* One happy path: `123 => \"neil\"`\n* One error path: `999 => throw new UserNotFoundException(\"No user with id 999\")`\n\nThat's really easy. No mocking libraries necessary. In production the logic will use a function performing the real database lookup, but it\nwill still have the identical `Int => String` shape.\n\nAs for test inputs, consider [property-based testing](http://www.scalatest.org/user_guide/property_based_testing).\nFor the cost of less initial setup than you do now for a single input, tools like\nScalaCheck will generate literally\nhundreds of inputs that will put the code through the wringer against data you never imagined and would never have time to write yourself.\nI would suggest property-based tests as the first line of defense in development but conventional, scenario-based tests\nwith functional dependencies to address bugs discovered in functional testing or production.\n\nFinally, if your team's tests have sophisticated setup with expensive resources you'd like to share across tests and\nclean up afterwards, have your engineers employ the [Loan Pattern](https://www.outbrain.com/techblog/2017/05/effective-testing-with-loan-pattern-in-scala/),\nwhich is one of the FP-est things you can do. I wrote an example\non [Stack Overflow](https://stackoverflow.com/questions/43729262/how-to-write-unit-tests-in-spark-2-0/43769845#43769845)\nof how powerful this can be for testing Big Data jobs using Apache Spark.\n\n## Easier Than You Think\n\nIt is very likely that today you can begin to enjoy many of the FP advantages I've described. Most modern languages--even Java finally\n--offer some degree of FP either in the core language or through open-source extensions.\n\nIt is also critical to keep in mind that it isn't a zero-sum game among FP and other paradigms. In fact, the fundamental\nacademic premise of Scala is that OO and FP can not only coexist but complement each other to produce an ideal language offering\nthe best of both. Similarly, FP can complement other paradigms like the imperative, procedural philosophy that\ndrives Go.\n\nConsequently, you should not worry that FP demands a radical transformation of your code\nbase that is unrealistic for your timeline and unthinkable for your client. No need to send everyone to Haskell training either.\n\n## Conclusion\n\nAs you face increasing pressure to deliver more features in less time at higher quality, your team needs to leverage the full capabilities\nof your engineering stack to maximize productivity. No matter your situation, let functional programming be a weapon\nin your arsenal. Whether you transition to\nfundamentally functional languages like [Elixir](https://elixir-lang.org/) or Scala or Elm, leverage functional capabilities\n(or extensions) in other languages like Java or JavaScript,\nor even just adopt corollary principles like immutability, your team will write fewer bugs and catch others faster than you\nthought possible. You should see improvement in as little as a single sprint (in a Scrum project), and it's an\ninvestment [most software engineers are happy to make](https://www.vidyasource.com/blog/the-art-of-software-engineering/) that will generate huge\nvalue for all of you."
}