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