DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • The Role of Functional Programming in Modern Software Development
  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Exploring the Power of the Functional Programming Paradigm

Trending

  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • Go 1.24+ Native FIPS Support for Easier Compliance
  • Advancing Your Software Engineering Career in 2025
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  1. DZone
  2. Coding
  3. Languages
  4. Code Organization in Functional Programming vs. Object Oriented Programming

Code Organization in Functional Programming vs. Object Oriented Programming

We walk through some code to check out the differences in FP and OOP in JavaScript programming.

By 
James Warden user avatar
James Warden
·
Jun. 20, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
15.6K Views

Join the DZone community and get the full member experience.

Join For Free

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 three will utilize many internal 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 two 2 basic patterns. 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

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 two 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, two 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 two patterns.

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 three 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:


javascript folder structure

then you unit test peopleparser with a mock for the file system ( fs ).

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:

javascript folder structure

then you unit test getpeople using a stub for fs .

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.

Functional programming Object-oriented programming unit test Public interface Object (computer science) Interface (computing)

Published at DZone with permission of James Warden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Role of Functional Programming in Modern Software Development
  • Redefining Java Object Equality
  • Singleton: 6 Ways To Write and Use in Java Programming
  • Exploring the Power of the Functional Programming Paradigm

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!