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.
Join the DZone community and get the full member experience.
Join For Freeintroduction
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:
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:
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.
Published at DZone with permission of James Warden, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments