函数式编程与面向对象编程:JavaScript中的对比分析

发表时间: 2019-07-12 09:45

本文通过代码来看一看JavaScript中函数式编程面向对象编程的差异。

作者 | Jesse Warden

译者 | 弯月,责编 | 郭芮

出品 | CSDN(ID:CSDNnews)

以下为译文:

一位同事问我有关函数式编程的代码组织形式。他正在使用Node与一群Java开发人员合作一个AWS Lambda项目,他们使用相同类型的类、各种设计模式以及其他面向对象编程的组织代码方式。他想知道,如果他们在函数式编程中仅使用纯函数,那么他们应该如何组织呢?

面向对象编程的方式

我感触最深的一点就是,每个人的代码组织形式都不一样。在不同的语言之间,唯一公认的实践就是要有一个公共的接口用来测试。公共接口指的是针对内部细节进行大量抽象的接口。它可以是类的公有方法、也可以是Facade或Factory设计模式,也可以是模块中的函数。这三者都会使用许多内部函数,但只会公开一个调用的函数。有时这种做法可以确保在添加功能和修复bug后,消费者在更新到最新代码时无需更改代码。当然,副作用仍然会对此产生负面影响。

单一类模块

可以说,至少在Node中,面向对象的方式通常包含两个基本设计模式。第一种方法是创建一个类,然后作为默认导出公开:

// CommonJS
class SomeThing { ... }
module.exports = SomeThing
// ES6
class SomeThing { ... }
export default SomeThing

导出多个东西

第二种方法是从同一模块中公开许多东西,包括类、函数、事件变量等:

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

而在这两种导出代码的基本方法之外,情况就会因各个项目以及各个团队而异了。有些项目或团队会使用不同的框架,例如使用Express与使用Nest的团队的代码截然不同。即使使用同一个Express框架,两个团队的使用方式也有所不同。有时,同一个团队在新项目中组织Express的方式也不一定与以往的项目相同。

函数式编程的方式

函数式编程组织代码的方式,至少在Node中,也有两种模式。

导出一个函数

第二种方式是从一个模块中导出一个函数:

// CommonJS
const utilFunction = => ...
module.exports = utilFunction
// ES6
const utilFunction = => ...
export default utilFunction

导出多个函数

第二种方式是从一个模块中导出多个函数:

// CommonJS
const utilFunction = => ...
const anotherHelper = => ...
module.exports = {
utilFunction,
anotherHelper
}
// ES6
export const utilFunction = => ...
export const anotherHelper = => ...

变量?

有些人们会把变量与函数用同样的方式导出,而有些更喜欢纯函数的人或者倡导延迟计算的人会导出函数:

// pragmatic
export CONFIGURATION_THING = 'some value'
// purist
export configurationThing = => 'some value'

示例

我们针对上述代码创建几个示例,向你演示如何使用单个和多个导出。我们将为面向对象和函数式编程构建一个公共的接口,并暂且忽略两者的副作用(即HTTP调用),假设单元测试将使用这个公共接口来调用内部的私有方法。两者都将加载并解析同一个文本。

这两个示例都将解析以下JSON字符串:

[
{
"firstName": "jesse",
"lastName": "warden",
"type": "Human"
},
{
"firstName": "albus",
"lastName": "dumbledog",
"type": "Dog"
},
{
"firstName": "brandy",
"lastName": "fortune",
"type": "Human"
}
]

示例:面向对象编程

我们需要三个类:一个类通过默认编码读取文件,一个类负责解析文件的类,一个单例类将它们组合到一个公共接口。

readfile.js

首先,这段读文件的代码实现了将文件读取到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

接下来,我们需要一个解析器类,从读取文件中获取原始的String数据,并解析到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

最后,我们需要一个单例将它们组合成一个静态的方法:

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

调用PeopleParser的静态方法

调用方式如下:

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

最后的文件夹结构如下:

最后,你可以使用文件系统对PeopleParser进行单元测试。

示例:函数式编程

对于函数式编程的示例,你可以参考这篇文章(http://jessewarden.com
/2019/01/four-ways-to-compose-synchronous-functions-in-javascript.html)。我们只需要一系列函数:

默认编码的函数

export const getDefaultEncoding =  =>
'utf8'

读取文件的函数

const readFile = fsModule => encoding => filename =>
new Promise((success, failure) =>
fsModule.readFile(filename, encoding, (error, data) =>
error
? failure(error)
: success(data)
)

解析文件的函数

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

从People对象中过滤Human的函数

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

从列表的Human中格式化字符串名称的函数

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

从列表中修正名称大小写以及映射的函数

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

提供公共接口的函数

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

调用getPeople

调用该函数的方式如下所示:

import fs from 'fs'
import { getPeople, getDefaultEncoding } from './peopleparser'
getPeople(fs)(getDefaultEncoding)('people.txt')
.then(console.log)
.catch(console.error)

最后文件夹结构如下:

最后,你可以使用fs的桩测试getPeople。

总结

如上所示,无论是面向对象编程还是函数式编程,你都可以使用CommonJS和ES6的方式实现默认导出,也可以实现多重导出。只要你导出的是隐藏实现细节的公共接口,那么就可以确保在更新时不会破坏使用代码的人,而且还可以确保在更改私有类方法/函数中的实现细节时,无需重构一堆单元测试。

尽管本文中的函数式编程的示例比面向对象的代码少,但是请不要误解,函数式编程中也可以包含很多函数,而且你可以使用相同的方式——从一个模块/文件或一系列函数中导出一个函数。通常,你可以将文件夹中的index.js作为实际导出的公共接口。

原文:https://dzone.com
/articles/code-organization-in-functional-programming-vs-obj

本文为 CSDN 翻译,转载请注明来源出处。

【END】