Path to Functional Style: a TypeScript Refactoring Example

How to refactor a function from imperative style to functional style

Sunny Sun
3 min readJan 5, 2019

--

This article discusses how to refactor an imperative-style function to a functional-style function in a few iterations. I will also discuss the rationale for the changes.

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: We have a reason to expect a shorter version, given that it is a simple function.
  4. Inconsistent naming of variables.

--

--

Sunny Sun
Sunny Sun

Written by Sunny Sun

I am full stack developer. Love coding, learning, writing. Checkout my NestJS course: https://shorturl.at/cpJM7, visit my blog https://coffeethinkcode.com

Responses (4)