Introduction
A co-worker asked about code organization in Functional Programming. He’s working with a bunch of Java developers in Node for a single AWS Lambda, and they’re using the same style of classes, various design patterns, and other Object Oriented Programming ways of organizing code. He wondered if they used Functional Programming via just pure functions, how would they organize it?
The OOP Way
If there is one thing I’ve learned about code organization, it’s that everyone does it differently. The only accepted practice that seems to have any corroboration across languages is having a public interface for testing reasons. A public interface is anything that abstracts a lot of code that deals with internal details. It could be a public method for classes, a Facade or Factory design pattern, or functions from a module. All 3 will utilize internal many functions, but will only expose one function to use them. This can sometimes ensure as you add things and fix bugs, the consumers don’t have to change their code when they update to your latest code. Side effects can still negatively affect this.
Single Class Module
Suffice to say, the OOP way, at least in Node, typically consists of 2 basic ways. The first way is to create a class, and then expose it as the default export:
// CommonJS
class SomeThing { ... }
module.exports = SomeThing
// ES6
class SomeThing { ... }
export default SomeThing
Export Multiple Things
Multiple Classes/Things in a Module
The second is to expose many things, including classes, functions, event variables, from the same module:
// CommonJS
class SomeThing { ... }
const utilFunction = () => ...
const CONFIGURATION_VAR = ...
module.exports = {
SomeThing,
utilFunction,
CONFIGURATION_VAR
}
// ES6
export class SomeThing { ... }
export const utilFunction = () => ...
export const CONFIGURATION_VAR = ...
Once you get past these 2 basic ways of exporting code, things stop looking the same from project to project, and team to team. Some use different frameworks like Express which is different than how you use Nest. Within those frameworks, 2 teams will do Express differently. One of those teams will sometimes organize an Express project differently in a new project than a past one.
The FP Way
The Functional Programming way of organizing code, at least in Node, follows 2 ways.
Export Single Function
The first exports a single function from a module:
// CommonJS
const utilFunction = () => ...
module.exports = utilFunction
// ES6
const utilFunction = () => ...
export default utilFunction
Export Multiple Functions
The second way exports multiple functions from a module:
// CommonJS
const utilFunction = () => ...
const anotherHelper = () => ...
module.exports = {
utilFunction,
anotherHelper
}
// ES6
export const utilFunction = () => ...
export const anotherHelper = () => ...
Variables?
Sometimes you’ll see where they’ll export variables alongside functions where others who are more purist and want to promote lazy evaluation will just export functions instead:
// pragmatic
export CONFIGURATION_THING = 'some value'
// purist
export configurationThing = () => 'some value'
Examples
We’ll create some examples of the above to show you how that works using both single and multiple exports. We’ll construct a public interface for both the OOP and FP example and ignore side effects in both for now (i.e. HTTP calls) making the assumption the unit tests will use the public interface to call the internal private methods. Both will load the same text file and parse it.
Both examples will be parsing the following JSON string:
[
{
"firstName": "jesse",
"lastName": "warden",
"type": "Human"
},
{
"firstName": "albus",
"lastName": "dumbledog",
"type": "Dog"
},
{
"firstName": "brandy",
"lastName": "fortune",
"type": "Human"
}
]
Example: OOP
We’ll need 3 things: a class to read the file with default encoding, a class to parse it, and a Singleton to bring them all together into a public interface.
readfile.js
First, the reader will just abstract away the reading with optional encoding into a Promise
:
// readfile.js
import fs from 'fs'
import { EventEmitter } from 'events'
class ReadFile {
readFile(filename, encoding=DEFAULT_ENCODING) {
return new Promise(function (success, failure) {
fs.readFile(filename, encoding, function(error, data) {
if(error) {
failure(error)
return
}
success(data)
})
})
}
}
export DEFAULT_ENCODING = 'utf8'
export ReadFile
parser.js
Next, we need a parser class to take the raw String data from the read file and parse it into formatted names in an Array:
// parser.js
import { startCase } from 'lodash'
class ParseFile {
#fileData
#names
get names() {
return this.#names
}
constructor(data) {
this.#fileData = data
}
parseFileContents() {
let people = JSON.parse(this.#fileData)
this.#names = []
let p
for(p = 0; p < people.length; p++) {
const person = people[p]
if(person.type === 'Human') {
const name = this._personToName(person)
names.push(name)
}
}
}
_personToName(person) {
const name = `${person.firstName} ${person.lastName}`
return startCase(name)
}
}
export default ParseFile
index.js
Finally, we need a Singleton to bring them all together into a single, static method:
// index.js
import ParseFile from './parsefile'
import { ReadFile, DEFAULT_ENCODING } from './readfile'
class PeopleParser {
static async getPeople() {
try {
const reader = new ReadFile()
const fileData = await reader.readFile('people.txt', DEFAULT_ENCODING)
const parser = new ParseFile(data)
parser.parseFileContents()
return parser.names
} catch(error) {
console.error(error)
}
}
}
export default PeopleParser
Using PeopleParser’s Static Method
To use it:
import PeopleParser from './peopleparser'
PeopleParser.getPeople()
.then(console.log)
.catch(console.error)
Your folder structure will look like so:
Then you unit test PeopleParser with a mock for the file system.
Example: FP
For our Functional Programming example, we’ll need everything in this article, heh! Seriously, a list of pure functions:
Function for Default Encoding
export const getDefaultEncoding = () =>
'utf8'
Function to Read the File
const readFile = fsModule => encoding => filename =>
new Promise((success, failure) =>
fsModule.readFile(filename, encoding, (error, data) =>
error
? failure(error)
: success(data)
)
Function to Parse the File
const parseFile = data =>
new Promise((success, failure) => {
try {
const result = JSON.parse(data)
return result
} catch(error) {
return error
}
})
Function to Filter Humans from Array of People Objects
const filterHumans = peeps =>
peeps.filter(
person =>
person.type === 'Human'
)
Function to Format String Names from Humans from a List
const formatNames = humans =>
humans.map(
human =>
`${human.firstName} ${human.lastName}`
)
Function to Fix Name Casing and Map from a List
const startCaseNames = names =>
names.map(startCase)
Function to Provide a Public Interface
export const getPeople = fsModule => encoding => filename =>
readFile(fsModule)(encoding)(filename)
.then(parseFile)
.then(filterHumans)
.then(formatNames)
.then(startCaseNames)
Using getPeople
To use the function:
import fs from 'fs'
import { getPeople, getDefaultEncoding } from './peopleparser'
getPeople(fs)(getDefaultEncoding())('people.txt')
.then(console.log)
.catch(console.error)
Your folder structure should look like this:
Then you unit test getPeople using a stub for file system.
Conclusions
As you can see, you can use the basic default module export, or multiple export option in CommonJS and ES6 for both OOP and FP code bases. As long as what you are exporting is a public interface to hide implementation details, then you can ensure you’ll not break people using your code when you update it, as well as ensuring you don’t have to refactor a bunch of unit tests when you change implementation details in your private class methods/functions.
Although the FP example above is smaller than the OOP one, make no mistake, you can get a LOT of functions as well, and you treat it the same way; just export a single function from a another module/file, or a series of functions. Typically you treat index.js in a folder as the person who decides what to actually export as the public interface.