Path to Functional Style: a TypeScript Refactoring Example

How to refactor a function from imperative style to functional style

Sunny Sun

--

This article discusses how to refactor a function with imperative into a functional style. The function is refactored in a few passes. I will discuss the rationale for the changes also.

Imperative vs. Functional

Imperative code mutates the application state in a step-by-step control flow, unlike Functional programming, which emphasizes pure functions and avoids data mutation.

Functional programming is a form of declarative programming. The declarative approach can make the code more readable and maintainable.

Original code

The following Typescript function is in Imperative style. It takes a query param string and outputs an array of param key-value pairs. The function has a few issues:

  1. Too many Temporary Fields affect the readability and make it difficult to refactor.
  2. Loops can be replaced by map operators that can perform the same operations in a functional style.
  3. Long Method, it smells as if we have a reason to expect a shorter version, given it is a simple function.

--

--

Sunny Sun

I am full stack developer. Love coding, always leaning, writing and sharing. Visit my personal blog https://sunnyy02.github.io