DEV Community

Jesse Warden
Jesse Warden

Posted on

Code Organization in Functional Programming vs Object Oriented Programming

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


Enter fullscreen mode Exit fullscreen mode

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 = ...


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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 = () => ...


Enter fullscreen mode Exit fullscreen mode

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'


Enter fullscreen mode Exit fullscreen mode

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"
    }
]


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

Using PeopleParser’s Static Method

To use it:



import PeopleParser from './peopleparser'
PeopleParser.getPeople()
.then(console.log)
.catch(console.error)


Enter fullscreen mode Exit fullscreen mode

Your folder structure will look like so:

OOP Folder Structure

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'


Enter fullscreen mode Exit fullscreen mode

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)
        )


Enter fullscreen mode Exit fullscreen mode

Function to Parse the File



const parseFile = data =>
    new Promise((success, failure) => {
        try {
            const result = JSON.parse(data)
            return result
        } catch(error) {
            return error
        }
    })


Enter fullscreen mode Exit fullscreen mode

Function to Filter Humans from Array of People Objects



const filterHumans = peeps =>
    peeps.filter(
        person =>
            person.type === 'Human'
    )


Enter fullscreen mode Exit fullscreen mode

Function to Format String Names from Humans from a List



const formatNames = humans =>
    humans.map(
        human =>
            `${human.firstName} ${human.lastName}`
    )


Enter fullscreen mode Exit fullscreen mode

Function to Fix Name Casing and Map from a List



const startCaseNames = names =>
    names.map(startCase)


Enter fullscreen mode Exit fullscreen mode

Function to Provide a Public Interface



export const getPeople = fsModule => encoding => filename =>
    readFile(fsModule)(encoding)(filename)
        .then(parseFile)
        .then(filterHumans)
        .then(formatNames)
        .then(startCaseNames)


Enter fullscreen mode Exit fullscreen mode

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)


Enter fullscreen mode Exit fullscreen mode

Your folder structure should look like this:

FP Folder Structure

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.

Top comments (8)

Collapse
 
taljoffe profile image
Tal Joffe

Wow. I love this post!
I really appreciate the fact that you managed to come up with a really nice FP style without using any external library.
You managed to show Either and Maybe monads, currying, and function composition effortlessly in a way I think most Javascript developers will feel comfortable with.
Really awesome!

Collapse
 
koresar profile image
Vasyl Boroviak

I'll add to the above, if I may.

Please, do you not do Java in JavaScript. Do not use classes. (unless you need to create a million object instances per second)

In fact. The only time I saw class abuse in node.js is when the code was written by Java developer.

This was my begging. 🙏 Please, readers, do not use classes in node.js.

Collapse
 
jesterxl profile image
Jesse Warden

Behind the party, a large creature wreathed in flame with a TypeScript whip that cracks loudly, echoing the Dynamic types doom throughout the chamber. The JavaScripts had dug too deep... and unleashed horror, NestJS! Swaths of stateful classes permeated it's demonic form.
(they look like this docs.nestjs.com/controllers)

:: looks in bewilderment and concern at @Vasyl while hanging from ledge ::
"Run, you fools!" then let's go to fall into the darkness.

Collapse
 
koresar profile image
Vasyl Boroviak

NestJS is awesome! 😀

Collapse
 
taljoffe profile image
Tal Joffe

Re-read the article and I have a question on side-effects:
Looks like you are ignoring it or am I wrong?
Can you share a little how you think the impurity in your examples should be addressed?

Collapse
 
jesterxl profile image
Jesse Warden

There are a few ways to handle them. In the article, I just use Promises.
The other way is to use Dependency Injection where things like fsModule, JSON.parse, and even request style things you make them part of the function parameters.
The other way is using the Effect functor. That's a lot of work in JavaScript without using libraries/languages that help you handle that (a la PureScript).
To learn more about DI and Effect: jrsinclair.com/articles/2018/how-t...

Collapse
 
taljoffe profile image
Tal Joffe

Thanks for the response!
I actually stumbled upon this post after asking you here and found it very helpful.
My conclusion after reading it and a few others was that side effects are not to be eliminated just to be minimized.
Where it is clear that there should be side effect I just leave it

Collapse
 
jasterix profile image
Jasterix

This is exactly what I was looking for. Great article!