<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>code &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/code/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Sun, 16 Jun 2019 14:30:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>code &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Code Organization in Functional Programming vs Object Oriented Programming</title>
		<link>https://jessewarden.com/2019/06/code-organization-in-functional-programming-vs-object-oriented-programming.html</link>
					<comments>https://jessewarden.com/2019/06/code-organization-in-functional-programming-vs-object-oriented-programming.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sat, 15 Jun 2019 21:58:56 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[fp]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[objectorientedprogramming]]></category>
		<category><![CDATA[oop]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5824</guid>

					<description><![CDATA[Introduction A co-worker asked about code organization in Functional Programming. He&#8217;s working with a bunch of Java developers in Node for a single AWS Lambda, and they&#8217;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 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Introduction</h2>



<p>A co-worker asked about code organization in Functional Programming. He&#8217;s working with a bunch of Java developers in Node for a single AWS Lambda, and they&#8217;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? </p>



<span id="more-5824"></span>



<h2 class="wp-block-heading">The OOP Way</h2>



<p>If there is one thing I&#8217;ve learned about code organization, it&#8217;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&#8217;t have to change their code when they update to your latest code. Side effects can still negatively affect this.</p>



<h3 class="wp-block-heading">Single Class Module</h3>



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


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// CommonJS</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeThing</span> </span>{ ... }

<span class="hljs-built_in">module</span>.exports = SomeThing

<span class="hljs-comment">// ES6</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeThing</span> </span>{ ... }
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> SomeThing</code></span></pre>


<h3 class="wp-block-heading">Export Multiple Things</h3>



<p>The second is to expose many things, including classes, functions, event variables, from the same module: </p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// CommonJS</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeThing</span> </span>{ ... }

<span class="hljs-keyword">const</span> utilFunction = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...

const CONFIGURATION_VAR = ...

module.exports = {
    SomeThing,
    utilFunction,
    CONFIGURATION_VAR
}

<span class="hljs-comment">// ES6</span>
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SomeThing</span> </span>{ ... }

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> utilFunction = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...

export <span class="hljs-keyword">const</span> CONFIGURATION_VAR = ...</code></span></pre>


<p>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 <a href="https://expressjs.com/">Express</a> which is different than how you use <a href="https://nestjs.com/">Nest</a>. 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.</p>



<h2 class="wp-block-heading">The FP Way</h2>



<p>The Functional Programming way of organizing code, at least in Node, follows 2 ways. </p>



<h3 class="wp-block-heading">Export Single Function</h3>



<p>The first exports a single function from a module:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// CommonJS</span>
<span class="hljs-keyword">const</span> utilFunction = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...

module.exports = utilFunction

<span class="hljs-comment">// ES6</span>
<span class="hljs-keyword">const</span> utilFunction = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...
export <span class="hljs-keyword">default</span> utilFunction</code></span></pre>


<h3 class="wp-block-heading">Export Multiple Functions</h3>



<p>The second way exports multiple functions from a module:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// CommonJS</span>
<span class="hljs-keyword">const</span> utilFunction = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...
const anotherHelper = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...

module.exports = {
    utilFunction,
    anotherHelper
}

<span class="hljs-comment">// ES6</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> utilFunction = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...
export <span class="hljs-keyword">const</span> anotherHelper = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> ...</code></span></pre>


<h3 class="wp-block-heading">Variables?</h3>



<p>Sometimes you&#8217;ll see where they&#8217;ll export variables alongside functions where others who are more purist and want to promote lazy evaluation will just export functions instead:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// pragmatic</span>
<span class="hljs-keyword">export</span> CONFIGURATION_THING = <span class="hljs-string">'some value'</span>

<span class="hljs-comment">// purist</span>
<span class="hljs-keyword">export</span> configurationThing = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-string">'some value'</span></code></span></pre>


<h2 class="wp-block-heading">Examples</h2>



<p>We&#8217;ll create some examples of the above to show you how that works using both single and multiple exports. We&#8217;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.</p>



<p>Both examples will be parsing the following JSON string:</p>


<pre class="wp-block-code"><span><code class="hljs language-json">&#91;
	{
		<span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"jesse"</span>,
		<span class="hljs-attr">"lastName"</span>: <span class="hljs-string">"warden"</span>,
		<span class="hljs-attr">"type"</span>: <span class="hljs-string">"Human"</span>
	},
	{
		<span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"albus"</span>,
		<span class="hljs-attr">"lastName"</span>: <span class="hljs-string">"dumbledog"</span>,
		<span class="hljs-attr">"type"</span>: <span class="hljs-string">"Dog"</span>
	},
	{
		<span class="hljs-attr">"firstName"</span>: <span class="hljs-string">"brandy"</span>,
		<span class="hljs-attr">"lastName"</span>: <span class="hljs-string">"fortune"</span>,
		<span class="hljs-attr">"type"</span>: <span class="hljs-string">"Human"</span>
	}
]</code></span></pre>


<h3 class="wp-block-heading">Example: OOP</h3>



<p>We&#8217;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.</p>



<h4 class="wp-block-heading">readfile.js</h4>



<p>First, the reader will just abstract away the reading with optional encoding into a <code>Promise</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// readfile.js</span>
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>
<span class="hljs-keyword">import</span> { EventEmitter } <span class="hljs-keyword">from</span> <span class="hljs-string">'events'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReadFile</span> </span>{

    readFile(filename, encoding=DEFAULT_ENCODING) {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">success, failure</span>) </span>{
            fs.readFile(filename, encoding, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error, data</span>) </span>{
                <span class="hljs-keyword">if</span>(error) {
                    failure(error)
                    <span class="hljs-keyword">return</span>
                }
                success(data)
            })
        })
    }
}

<span class="hljs-keyword">export</span> DEFAULT_ENCODING = <span class="hljs-string">'utf8'</span>
<span class="hljs-keyword">export</span> ReadFile</code></span></pre>


<h4 class="wp-block-heading">parser.js</h4>



<p>Next, we need a parser class to take the raw <code>String</code> data from the read file and parse it into formatted names in an <code>Array</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-php"><span class="hljs-comment">// parser.js</span>
import { startCase } from <span class="hljs-string">'lodash'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ParseFile</span> </span>{
    
    <span class="hljs-comment">#fileData</span>
    <span class="hljs-comment">#names</span>

    get names() { 
        <span class="hljs-keyword">return</span> this.<span class="hljs-comment">#names</span>
    }
    
    constructor(data) {
        this.<span class="hljs-comment">#fileData = data</span>
    }

    parseFileContents() {
        let people = JSON.parse(this.<span class="hljs-comment">#fileData)</span>
        this.<span class="hljs-comment">#names = &#91;]</span>
        let p
        <span class="hljs-keyword">for</span>(p = <span class="hljs-number">0</span>; p &lt; people.length; p++) {
            <span class="hljs-keyword">const</span> person = people&#91;p]
            <span class="hljs-keyword">if</span>(person.type === <span class="hljs-string">'Human'</span>) {
                <span class="hljs-keyword">const</span> name = this._personToName(person)
                names.push(name)
            }
        }
    }

    _personToName(person) {
        <span class="hljs-keyword">const</span> name = `${person.firstName} ${person.lastName}` 
        <span class="hljs-keyword">return</span> startCase(name)
    }
}

export <span class="hljs-keyword">default</span> ParseFile</code></span></pre>


<h4 class="wp-block-heading">index.js</h4>



<p>Finally, we need a Singleton to bring them all together into a single, static method:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-comment">// index.js</span>
<span class="hljs-keyword">import</span> ParseFile <span class="hljs-keyword">from</span> <span class="hljs-string">'./parsefile'</span>
<span class="hljs-keyword">import</span> { ReadFile, DEFAULT_ENCODING } <span class="hljs-keyword">from</span> <span class="hljs-string">'./readfile'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PeopleParser</span> </span>{

    <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> getPeople() {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> reader = <span class="hljs-keyword">new</span> ReadFile()
            <span class="hljs-keyword">const</span> fileData = <span class="hljs-keyword">await</span> reader.readFile(<span class="hljs-string">'people.txt'</span>, DEFAULT_ENCODING)
            <span class="hljs-keyword">const</span> parser = <span class="hljs-keyword">new</span> ParseFile(data)
            parser.parseFileContents()
            <span class="hljs-keyword">return</span> parser.names
        } <span class="hljs-keyword">catch</span>(error) {
            <span class="hljs-built_in">console</span>.error(error)
        }
    }

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PeopleParser</code></span></pre>


<h4 class="wp-block-heading">Using PeopleParser&#8217;s Static Method</h4>



<p>To use it:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">import</span> PeopleParser <span class="hljs-keyword">from</span> <span class="hljs-string">'./peopleparser'</span>
PeopleParser.getPeople()
.then(<span class="hljs-built_in">console</span>.log)
.catch(<span class="hljs-built_in">console</span>.error)</code></span></pre>


<p>Your folder structure will look like so:</p>



<figure class="wp-block-image"><img decoding="async" width="206" height="160" src="http://jessewarden.com/wp-content/uploads/2019/06/oop-folder-structure.png" alt="" class="wp-image-5826"/></figure>



<p>Then you unit test <code>PeopleParser</code> with a  <strong>mock</strong> for the file system (<code>fs</code>).</p>



<h3 class="wp-block-heading">Example: FP</h3>



<p>For our Functional Programming example, we&#8217;ll need <a href="http://jessewarden.com/2019/01/four-ways-to-compose-synchronous-functions-in-javascript.html">everything in this article</a>, heh! Seriously, a list of pure functions:</p>



<h4 class="wp-block-heading">Function for Default Encoding</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getDefaultEncoding = <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span>
    <span class="hljs-string">'utf8'</span></code></span></pre>


<h4 class="wp-block-heading">Function to Read the File</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> readFile = <span class="hljs-function"><span class="hljs-params">fsModule</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">encoding</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">filename</span> =&gt;</span>
    <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">success, failure</span>) =&gt;</span>
        fsModule.readFile(filename, encoding, (error, data) =&gt;
            error
            ? failure(error)
            : success(data)
        )</code></span></pre>


<h4 class="wp-block-heading">Function to Parse the File</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> parseFile = <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span>
    <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">success, failure</span>) =&gt;</span> {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> result = <span class="hljs-built_in">JSON</span>.parse(data)
            <span class="hljs-keyword">return</span> result
        } <span class="hljs-keyword">catch</span>(error) {
            <span class="hljs-keyword">return</span> error
        }
    })</code></span></pre>


<h4 class="wp-block-heading">Function to Filter Humans from Array of People Objects</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> filterHumans = <span class="hljs-function"><span class="hljs-params">peeps</span> =&gt;</span>
	peeps.filter(
        <span class="hljs-function"><span class="hljs-params">person</span> =&gt;</span>
            person.type === <span class="hljs-string">'Human'</span>
    )</code></span></pre>


<h4 class="wp-block-heading">Function to Format String Names from Humans from a List</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> formatNames = <span class="hljs-function"><span class="hljs-params">humans</span> =&gt;</span>
    humans.map(
        <span class="hljs-function"><span class="hljs-params">human</span> =&gt;</span>
            <span class="hljs-string">`<span class="hljs-subst">${human.firstName}</span> <span class="hljs-subst">${human.lastName}</span>`</span>
    )</code></span></pre>


<h4 class="wp-block-heading">Function to Fix Name Casing and Map from a List</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">const</span> startCaseNames = <span class="hljs-function"><span class="hljs-params">names</span> =&gt;</span>
    names.map(startCase)</code></span></pre>


<h4 class="wp-block-heading">Function to Provide a Public Interface</h4>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getPeople = <span class="hljs-function"><span class="hljs-params">fsModule</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">encoding</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">filename</span> =&gt;</span>
    readFile(fsModule)(encoding)(filename)
        .then(parseFile)
        .then(filterHumans)
        .then(formatNames)
        .then(startCaseNames)</code></span></pre>


<h4 class="wp-block-heading">Using getPeople</h4>



<p>To use the function:</p>


<pre class="wp-block-code"><span><code class="hljs language-javascript"><span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>
<span class="hljs-keyword">import</span> { getPeople, getDefaultEncoding } <span class="hljs-keyword">from</span> <span class="hljs-string">'./peopleparser'</span>

getPeople(fs)(getDefaultEncoding())(<span class="hljs-string">'people.txt'</span>)
.then(<span class="hljs-built_in">console</span>.log)
.catch(<span class="hljs-built_in">console</span>.error)</code></span></pre>


<p>Your folder structure should look like this:</p>



<figure class="wp-block-image"><img decoding="async" width="190" height="88" src="http://jessewarden.com/wp-content/uploads/2019/06/fp-folder-structure.png" alt="" class="wp-image-5827"/></figure>



<p>Then you unit test <code>getPeople</code> using a <strong>stub</strong> for <code>fs</code>.</p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>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&#8217;ll not break people using your code when you update it, as well as ensuring you don&#8217;t have to refactor a bunch of unit tests when you change implementation details in your private class methods/functions.</p>



<p>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 <code>index.js</code> in a folder as the person who decides what to actually export as the public interface. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2019/06/code-organization-in-functional-programming-vs-object-oriented-programming.html/feed</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
