Path to Functional Style: a TypeScript Refactoring Example
How to refactor a function from imperative style to functional style
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:
- Too many Temporary Fields affect the readability and make it difficult to refactor.
- Loops can be replaced by map operators that can perform the same operations in a functional style.
- Long Method, it smells as if we have a reason to expect a shorter version, given it is a simple function.