<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jonathan Milgrom on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Milgrom on Medium]]></description>
        <link>https://medium.com/@jbmilgrom?source=rss-1f399d61fc99------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pVpkhTjmqkfHfTjE.jpeg</url>
            <title>Stories by Jonathan Milgrom on Medium</title>
            <link>https://medium.com/@jbmilgrom?source=rss-1f399d61fc99------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:00:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jbmilgrom/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Functional and Object-Oriented Programming are Often Juxtaposed]]></title>
            <link>https://medium.com/@jbmilgrom/why-functional-and-object-oriented-programming-are-often-juxtaposed-1017699112d7?source=rss-1f399d61fc99------2</link>
            <guid isPermaLink="false">https://medium.com/p/1017699112d7</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[sicp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Jonathan Milgrom]]></dc:creator>
            <pubDate>Mon, 09 Mar 2020 17:44:37 GMT</pubDate>
            <atom:updated>2020-07-04T16:35:26.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Juxtaposition of Functional and Object-Oriented Programming Exposes an Alternative Model for Time</h3><p>(<em>This post has been</em> <a href="https://softwarefordays.com/post/functional-programming-and-identity-state-and-time/"><em>migrated here</em></a><em> for </em><a href="https://softwarefordays.com/post/hello-world/"><em>better anchor tag and footnote behavior</em></a><em>.</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCxs1E7X1MSUHGrYpxUu2A.png" /><figcaption>Oil &amp; water</figcaption></figure><p>That functional programming opposes object-oriented programming in some fundamental way is a widely-held programming cliche. We list features like immutability, functions and composition in contrast to mutability, classes and inheritance. We tout Clojure and Haskel as functional languages on one end of the spectrum and C++ and Java as object-oriented languages on the other. Articulating the makeup of the spectrum is another story altogether however. None of this trivia explains why certain features are seen together or apart, why languages themselves may skew in one direction or another, or any inherent differences in program semantics. Nevertheless, the “functions vs. objects” cliche is an artifact of a profound truth about program structures and semantics. Like up and down and oil and water, functional and object-oriented programming indeed cannot coexist. We may choose objects or functions, but not both at once, as advertised. Moreover, the choice between paradigms has dramatic implications for program semantics, offering competing “world-views” involving concepts as basic as identity, change, state and time. Where object-oriented programming focuses on “distinct objects whose behaviors may change <em>over time</em>,” functional programming focuses on state transitions between <em>discrete</em> <em>moments in time</em> that can be seen together as “streams of information that flow in the system.” — <a href="https://web.mit.edu/alexmv/6.037/sicp.pdf">Structure and Interpretation of Computer Programs</a> (SICP), Section 3</p><h3>Functional Programming</h3><p>Procedures that produce the same result when provided the same argument can be viewed as computing mathematical functions. For example, a decrement100 procedure in JavaScript<a href="#c746">⁰</a>,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b87471b460c4cf298660c79d3d6a708/href">https://medium.com/media/9b87471b460c4cf298660c79d3d6a708/href</a></iframe><p>or, more succinctly,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/364010e1acaf29399bc700270c53f856/href">https://medium.com/media/364010e1acaf29399bc700270c53f856/href</a></iframe><p>can be viewed as computing the mathematical function f(x) = 100 — x,</p><pre>where f(x) = 100 - x,</pre><pre>f(20) = 80</pre><p>since the return value of decrement100 depends only on the input value just as f(x) depends only on x. Invoke decrement100 a second time with 20 and it will return 80 once again, regardless of time and place within a program’s runtime. By contrast, an alternative implementation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f99b842570219fb9ad6c80d34a3d1086/href">https://medium.com/media/f99b842570219fb9ad6c80d34a3d1086/href</a></iframe><p>involving a mutable binding does not model computing a mathematical function, since its behavior may depend on variable information in addition to its input. Invoke decrementOneHundred a second time with 20 and it will <em>not</em> return 80 once again when such binding is intermediately reassigned.</p><p>Functional procedures are not limited to numbers. Procedures that involve character strings, for example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ec6ecadcd1d7c58b7ce639dd548616/href">https://medium.com/media/67ec6ecadcd1d7c58b7ce639dd548616/href</a></iframe><p>a list of strings,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddc2682eee6d1e900fb03ed0966cf99/href">https://medium.com/media/4ddc2682eee6d1e900fb03ed0966cf99/href</a></iframe><p>or other arbitrary data types and compositions may return the same value provided the same argument. Larger functional procedures can be composed of smaller ones,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e60784287b2156938c66d5053ccbf88d/href">https://medium.com/media/e60784287b2156938c66d5053ccbf88d/href</a></iframe><p>as can programs themselves.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d99ec0e53ba5937a17ad3454833098d2/href">https://medium.com/media/d99ec0e53ba5937a17ad3454833098d2/href</a></iframe><p>When the output of one functional procedure becomes the input of another, the wrapping program or procedure itself can be viewed as computing a mathematical function; a second run with the same input results in the same output.<a href="#dba0">¹</a></p><h3>Object-Oriented Programming</h3><p><em>Object-oriented programming</em> has come to signify a common language for modeling the behavior of objects.<a href="#202d">²</a> Methods leverage privileged access to proscribe the ways in which private attributes may be viewed or changed. A class specifies the blueprint for creating object instances of a certain kind. Together, these constructs may create computational objects that simulate real objects. This bankAccount object in TypeScript, for example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3d498b80aa150e176f2a49276ad4bd7/href">https://medium.com/media/f3d498b80aa150e176f2a49276ad4bd7/href</a></iframe><p>stores balance data in a private attribute and exposes privileged methods checkBalance and withdraw, which proscribe the manner in which access to balance can occur. Together, these constructs create a computational object — e.g. bankAccount — that behaves like a “bank account”, carrying a balance that may be diminished through “withdraw” and viewed through “check balance” actions. Less abstract objects can be modeled with the same set of tools — an apple may have a bite method that reduces an internal bites state in order to model an “apple” and a house may have a paint method that changes an internal color state in order to model a “house.” More abstract objects can be modeled with the same set of tools as well— a userMetaData object may have a setEmail method that updates an internal email state in order to model “user meta data.”</p><h4>An Evolution of Imperative Programming</h4><blockquote>And a key characteristic here is that objects have methods… They are operationally defined. And we use them to provide a layer of abstraction over the places that our program uses. — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p>Private state enforces the object abstraction together with privileged, public methods. Expose balance directly (i.e. make it public), for example, and it can “magically” change from say 100 to 10 despite no withdrawal ever having occurred. Expose color directly and it can “magically” change from say WHITE to BLUE despite no painting ever having occurred. In other words, object-oriented programming provides the means for identifying objects (bankAccount) and associated behaviors (withdraw)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88ac164a0177cdef904291bdf0998acc/href">https://medium.com/media/88ac164a0177cdef904291bdf0998acc/href</a></iframe><p>in place of imperative, direct manipulation of variables (balance) ad hoc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca0d3b57aa709724111611381a95144/href">https://medium.com/media/5ca0d3b57aa709724111611381a95144/href</a></iframe><p>Coincidentally, the private data / public methods dynamic also provides the means for data encapsulation. That data is stored in private attributes, accessible only through privileged methods, proscribes the ways in which such data may be viewed or changed. The balance data of bankAccount can only be changed by withdraw or read by checkBalance, in one sense, because it may not be accessed directly.</p><h4>Place-Oriented Programming</h4><p>Nevertheless, object-oriented and imperative programming share a fundamental orientation towards places in memory.</p><blockquote>But mutable objects are actually abstractions of places. They do not actually have meaning other than that. They are little barricades we have set up in front of memory, so that we do not have to directly manipulate memory addresses any more. So we have this abstraction that is an object, that helps us manipulate that place without too much craziness…So I have a new label for this. It is called PLOP, and PLOP is place-oriented programming. — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p>A method call to withdraw effectively overwrites a balance reference</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16c6a4b7ec35dd1775b6f022bbaeabb8/href">https://medium.com/media/16c6a4b7ec35dd1775b6f022bbaeabb8/href</a></iframe><p>just as any direct assignment that circumvents a method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e0e0642b12f34d72aa38543fdd837a/href">https://medium.com/media/e6e0e0642b12f34d72aa38543fdd837a/href</a></iframe><p>A mutable variable and a place in memory underly the reassignments in both cases.<a href="#1a6f">³</a></p><h3>Semantics, Not Syntax</h3><p>Syntactic constructs like this, new, class, private and public clearly express object-oriented intent — <em>this</em> instance of a <em>class</em> of things <em>private</em>ly maintains data through <em>public</em>ly available APIs — and are common to object-oriented programming languages. However, they are not necessary. Object-oriented semantics may be achieved with nontraditional syntax. For example, this bankAccount object also stores the balance data privately;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fff3a15103e473f978484a1e92f497e/href">https://medium.com/media/3fff3a15103e473f978484a1e92f497e/href</a></iframe><p>balance is accessible only through the functions checkBalance and withdraw, which proscribe the manner in which such access can occur. bankAccount behaves like a “bank account” even though the functions checkBalance and withdraw have gained privileged access to private data through the use of a function closure instead of through explicit syntactic constructs in this case. Object-oriented syntax is also insufficient in and of itself to achieve object-oriented semantics. A bankAccount “object” that avoids maintaining any underlying balance state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05691c9b3cdb8314794394a83ddefbbc/href">https://medium.com/media/05691c9b3cdb8314794394a83ddefbbc/href</a></iframe><p>allows “its” balance to evolve in an unspecified manner, which undermines the “bank account” abstraction. new, class and public constructs obscure the actual semantics in this case. The same can be said of a bankAccount object that publicly exposes the balance attribute, as was alluded to above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4640595c4fc27941c06173c647419483/href">https://medium.com/media/4640595c4fc27941c06173c647419483/href</a></iframe><p>Now, balance can magically change without a withdrawal ever having occurred, undermining the “bank account” abstraction. new, class and public constructs obscure the actual semantics in this case.<a href="#9110">⁴</a></p><p>With functional programming, syntax is also beside the point. The use of functional syntactic constructs is necessary to perform computation against arguments. function and =&gt; (i.e. “arrow function”) syntax may express functional programming intent as well. However, they cannot alone achieve functional semantics. Indeed, a method of an object may use the =&gt; syntax without correctly modeling computing mathematical functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfb5a8c614c28bec0664cb068fddb9cc/href">https://medium.com/media/cfb5a8c614c28bec0664cb068fddb9cc/href</a></iframe><p>Subsequent calls to checkBalance return different results despite identical inputs (i.e. undefined) by design.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b59aabb7f59eb9806576f625b662130/href">https://medium.com/media/2b59aabb7f59eb9806576f625b662130/href</a></iframe><p>Additionally, an alternative implementation of “decrement one hundred” in JavaScript may fall short of correctly modeling a mathematical function even though an =&gt; construct is used, as was alluded to above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f99b842570219fb9ad6c80d34a3d1086/href">https://medium.com/media/f99b842570219fb9ad6c80d34a3d1086/href</a></iframe><p>Invoking this procedure a second time with the same argument produces a different result when the let binding is amended between invocations.</p><h3>Changeability is Fundamental to Object Semantics</h3><p>Objects can change. An apple can be bitten, a house painted, and a bank account withdrawn from. Object implementations follow suit —</p><blockquote>[W]e make computational objects…whose behavior changes with time. We model state with local state variables, and we model the changes of state with assignments to those variables. — SICP Section 3.1.2</blockquote><p>— bite’ing an apple changes bites state, paint’ing a house changes color state and withdraw’ing from a bankAccount changes balance state. The class implementation of a bank account object</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4bcc0298a7efc1733436ee638f2705e/href">https://medium.com/media/a4bcc0298a7efc1733436ee638f2705e/href</a></iframe><p>involves overwriting balance as much as the closure implementation does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52a8b910467a5911b5550f9213dffb80/href">https://medium.com/media/52a8b910467a5911b5550f9213dffb80/href</a></iframe><p>As mentioned above, a state<em>less</em> “object” (e.g. bankAccount) that avoids maintaining any underlying state (e.g. balance)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05691c9b3cdb8314794394a83ddefbbc/href">https://medium.com/media/05691c9b3cdb8314794394a83ddefbbc/href</a></iframe><p>also avoids modeling any underlying object (e.g. “bank account”).</p><h3>Unchangeability is Fundamental to Functional Semantics</h3><p>On the other hand, changeable things undermine functional semantics. The decrement100 procedure can be viewed as computing a mathematical function because its output depends only on its input; there is no other <em>variable</em> information on which it depends. decrementOneHundred introduces a changeable thing. As the value of the mutable let binding changes, so does the behavior of decrementOneHundred as a side-effect. Consequently, decrementOneHundred depends on the ongoing value of some contextual thing in addition to its input x and does not resemble computing a mathematical function as a result.</p><p>Conversely, immutability restores functional semantics. No contextual changes means no side-effects, and no side-effects means functional behavior:</p><blockquote>So long as we do not use assignments, two evaluations of the same procedure with the same arguments will produce the same result, so that procedures can be viewed as computing mathematical functions. Programming without any use of assignment…is accordingly known as <em>functional programming</em>. — SICP Section 3.1.3</blockquote><p>An externally scoped variable cannot change the semantics of decrementOneHundred when immutable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41aa3c4118e5eeedf663a75120c1997f/href">https://medium.com/media/41aa3c4118e5eeedf663a75120c1997f/href</a></iframe><p>It simple cannot change and without change, the output can depend only on the single thing that can — i.e. the input.<a href="#995e">⁵</a></p><h3>“Object” Names Changeability</h3><p>Moreover, changeability <em>implies</em> an object. The rational number “2/3” cannot change, for example. Change the denominator of “2/3” from 3 to 5 and its identity changes as well to “2/5”. Increase the number of units represented by “24” and it may change to “25.”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f05de610f57b27758d36b2e3816c126/href">https://medium.com/media/1f05de610f57b27758d36b2e3816c126/href</a></iframe><p>Similarly, change the molecular construction of “iron” and it may very well change to “gold” or the wave length of “green” and it may change to “red”. The rational number “2/3”, the integer “24”, the metal “iron” and the color “green” are unchangeable things that are not recognizable as objects. Conversely, find changeability and find an object. A cup that is two-thirds full of water can be poured, an iron rod can be dented, a green house can be painted. “That cup” remains that cup notwithstanding less water; “that rod” remains that rod notwithstanding a dent; “that house” remains that house notwithstanding a fresh coat of paint. A “cup”, “rod” and “house” are changeable things that <em>are</em> recognizable as objects. Coincidence of “changeability” and “object” is not happenstance. That parts can change without changing the identity of the whole <em>distinguishes</em> an identity distinct from underlying parts. Changeability distinguishes an object. “Object” in a sense articulates this ability to change.</p><p>Said another way, a new notion of “sameness” emerges with changeability. Unchangeable things can be identified as “the same” simply by examining contents. For example, because <em>immutable</em> rational number implementations, r1 and r2,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ee6e4baa6a8b889e8e7a4893f9ecff7/href">https://medium.com/media/8ee6e4baa6a8b889e8e7a4893f9ecff7/href</a></iframe><p>will <em>always</em> be comprised of 2 in the first slot and 3 in the second and reduce to two-thirds, a reasonable conclusion is that they are the same. To be sure, substitute one for the other and the meaning of a program is unchanged.<a href="#cc5a">⁶</a> By contrast, consider when two <em>mutable (changeable) </em>rational number implementations may be deemed the “same.”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c9bbececb4972829551f8d1573ee643/href">https://medium.com/media/6c9bbececb4972829551f8d1573ee643/href</a></iframe><p>r1 may have the same contents as r2 to start, but this affect is shortly lived. Substitute one for the other and the meaning of the program is changed — references to r2 now incorrectly reduce to two-fifths instead of two-thirds. r1 and r2 are not exactly “the same” in this case. Since two changeable things may evolve independently notwithstanding an analysis of parts performed at any one point in time, a new notion of “sameness” above an examination of parts must be admitted. Remarkably, this “new” notion is less remarkable with intentional object-oriented programming, where the creation of a new identity — i.e. an <em>object</em> — is precisely the goal. georgesAccount and elainesAccount, for example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eb7f05a1cb2f139fc8d0f9e60914d04/href">https://medium.com/media/8eb7f05a1cb2f139fc8d0f9e60914d04/href</a></iframe><p>may share a balance at some point in time. But even if they start with the same funds, georgesAccount and elainesAccount can register different balances at some other point in time because they are<em> </em>in fact<em> </em>different<em> objects</em>. Of course, that two distinct objects can evolve independently goes without saying. That is because “object” clearly articulates the creation of an identity that is not tied to any part, arrangement or quality — “object” names the ability to change.<a href="#6d03">⁷</a></p><h3>Mutually Exclusive</h3><p>In this light, object-oriented can be seen as the opposite of functional programming. Objects are inherently changeable. In fact, changeability and “object” are intertwined as concepts. Yet, changeability undermines functional programming. Just as oil cannot inhabit the same physical space as water, object-oriented cannot occupy the same virtual space as functional programming. Use of one necessarily excludes the other.</p><h3>Program Semantics</h3><p>Mutual exclusion forks the road. When writing programs, we may choose mutability or immutability, objects or functions, but not both at once. Yet, whatever paradigm we choose must include a model for state, and perhaps time. As we saw above, programs that are composed of functions themselves model well-behaved state<em>less</em> mathematical functions,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d99ec0e53ba5937a17ad3454833098d2/href">https://medium.com/media/d99ec0e53ba5937a17ad3454833098d2/href</a></iframe><p>since they produce the same output provided the same input. Some real programs also simply produce output based on input. Compilers, for example, must output the same binaries provided the same input files. More frequently, however, programs require state, and the current state of the program, <em>together</em> with any user input, will determine the next state or output of the program. The current balance, for example, is crucial to calculating any subsequent balance post withdrawal. ATM machines are stateful programs.</p><h3>Stateful Object-Oriented Programs</h3><blockquote>Modeling with objects is powerful and intuitive, largely because this matches the perception of interacting with a world of which we are part. — SICP Section 3.5.5</blockquote><p>Object-oriented programming provides intuitive building-blocks for creating stateful programs. An ATM program, for example, that allows the user to set a “withdrawal amount” and effect a withdraw,</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fjmilgrom%2Fnotc93Lv%2Fembed%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fjmilgrom%2Fnotc93Lv%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1101e2b8dba4410d7c1eebfff271b58d/href">https://medium.com/media/1101e2b8dba4410d7c1eebfff271b58d/href</a></iframe><p>breaks down naturally into withdrawalAmount, representing the chosen amount to be withdrawn, and bankAccount, representing the user account underlying the session. The withdrawal amounts are incorporated by and read from withdrawalAmount. Withdrawals are incorporated by, and balance confirmations are read from, bankAccount. The current balance and the amount to potentially withdraw — the state of the program — are reflected directly by the state of bankAccount and withdrawalAmount — the state of its composite objects.</p><h4>Time</h4><blockquote>If we wish to write programs that model this kind of natural decomposition in our world (as we see it from our viewpoint as a part of that world) with structures in our computer, we make computational objects that… must change with time. — SICP Section 3.5.5</blockquote><p>Objects are intuitive in large part because they are consistent with a familiar model for time. Objects change — as we discussed, the notion of an “object,” having parts that change without changing the identity of the whole, articulates this ability. The flip-side to change is time. Since objects change, <em>when</em> an object is examined is vital to the examination, it goes without saying. The “having parts that can change without changing the identity of the whole” quality of bankAccount, for example, is implemented by withdraw.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c69e80507f8b615e862271fc2cab0ac/href">https://medium.com/media/2c69e80507f8b615e862271fc2cab0ac/href</a></iframe><p>Underlying withdraw lies a mutable balance binding that may be assigned new values. Calls to withdraw change the associated balance of bankAccount as a side-effect, without altering the identity of bankAccount, by design.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c4c8fe170ca8f6f12048271175b257b/href">https://medium.com/media/1c4c8fe170ca8f6f12048271175b257b/href</a></iframe><p>The flip-side to change is time. Any call to withdraw also “delineates moments in time” <em>when</em> balance <em>may</em> change. As a result, the meaning of bankAccount.checkBalance() “depends not only on the expression itself, but also on whether the evaluation occurs before or after these moments.” By modeling objects, “we are forced to admit time into our computational models.” (SICP Section 3.4)</p><h4>Stateful</h4><p>Object-oriented programming reifies objects — objects can be composed in other objects, received and returned by object methods, and generally manipulated like numbers, strings and other <a href="https://en.wikipedia.org/wiki/First-class_citizen">citizens</a> of the program. On the other hand, object-oriented programming presents no direct representation of state. Since object methods proscribe the ways in which state may be viewed or changed, state may not be accessed directly. Rather, state is a <em>quality</em> of objects — i.e. “stateful” or “statefulness” — that may be available at runtime to the extent proscribed by object definitions. bankAccount and withdrawalAmount, for example, may together incorporate the state of the ATM program — the statefulness of the program is reflect by the statefulness of its composite objects. However, access to such state is hidden by methods checkBalance and get. The state of program may only be “expressed” by <em>calling</em> both getters at runtime, like any other attribute, characteristic or object quality.</p><p>That objects indeed lack any express notion of state is highlighted by object signatures with more than one getter, where any such notion may only exist through definition, signature by signature:</p><blockquote>How can you perceive a mutable object that has more than one getter? … How do you it? … Who could say right now how to do this? No one can, right? You cannot do this, because you need this other thing. You need the recipe for doing this, and the recipe is something that everybody has to make up over and over and over again. … We cannot actually perceive the whole. Cannot do it without help. Without these recipes. — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p>An object with a single read method (like bankAccount) in a sense defines <em>the</em> method for accessing the whole of an object’s state. However, each additional read method dilutes this claim, underscoring the need for a method specific to the task (e.g. toJSON, serialize, inspect, etc.). In stark contrast to numbers, string and objects themselves, state may be expressed only through programmer-defined constructs evaluated at runtime.</p><h3>Stateful Functional Programs</h3><blockquote>Is there another approach? Can we avoid identifying time in the computer with time in the modeled world? Must we make the model change with time in order to model phenomena in a changing world? — SICP Section 3.5</blockquote><p>Building stateful functional programs is less intuitive. To start, notice that imperative iteration can be restructured into functional iteration by recursively calling an iterative function with the results of the previous call. An imperative implementation of factorial, for example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cec6dcfce360be458459f6e677816e80/href">https://medium.com/media/cec6dcfce360be458459f6e677816e80/href</a></iframe><p>maintains iteration and running total state through assignments to n and total, respectively, with every iteration. An alternative implementation avoids mutation by returning the iteration and running total state from an iteration function,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36d7e46f7c57f51d069e23ff51d20920/href">https://medium.com/media/36d7e46f7c57f51d069e23ff51d20920/href</a></iframe><p>which may be used by the same function to calculate the next values in the next iteration.</p><p>Stateful functional programs can be constructed in a similar fashion — state that is returned from the previous turn of some larger, iterative “program” function becomes the starter state for the next — with one caveat. With <em>synchronous</em> iteration, results of the previous run can simply be passed to the next. The total result from factorial iteration, for example, is passed directly to the next. In a JavaScript web application, however, events are initiated <em>asynchronously</em> as the user interacts with the page, calling callbacks bound to such events, which run pieces of the program so encoded.</p><pre>event → callback → javascript<br>event → callback → javascript<br>...</pre><p>Communication between <em>asynchronous</em> scripts is performed through shared references. One script updates (mutates!) a place in memory from which another script may later read. Look no further than the object-oriented ATM program above for a concrete example. A user may begin the program by first selecting a withdrawal amount, <em>then</em> clicking withdraw:</p><pre>select → onchange → &quot;withdrawalAmount.set(value)&quot;<br>click → onclick → &quot;bankAccount.withdraw(withdrawalAmount.get())&quot;<br>...</pre><p>The “click withdraw” script occurs asynchronously sometime after the “select withdrawal amount” script has completed. Communication between the two scripts occurs through shared reference to the amount variable underlying the withdrawalAmount object. Calls to withdrawalAmount.get() will return updates by withdrawalAmount.set(value), notwithstanding the asynchrony of such reads and writes.</p><p>Synchronous functions can communicate by simply passing around results. The result from one function becomes the input of another. Asynchronous scripts, by contrast, share a mutable place in memory instead of the values themselves. Consequently, we must also share a mutable place in memory to communicate between asynchronous scripts in the functional program implementation. On the other hand, with a light amount of infrastructure, we can usher such imperative code to the application perimeter and carve out space for a functional core, creating a “<a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">functional core, imperative shell</a>.”</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fjmilgrom%2Fmv2187zo%2F83%2Fembed%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fjmilgrom%2Fmv2187zo%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/140b0e17e9ed1ca79f68b1c13f0bd76a/href">https://medium.com/media/140b0e17e9ed1ca79f68b1c13f0bd76a/href</a></iframe><p>The program now consists of functions parseInt and withdraw, called against specific events WITHDRAWAL_AMOUNT and WITHDRAW. The state of the program has not been reflected directly into distinct objects. Instead, a program <em>function</em> is called with the state resulting from the previous call, together with event data from any user interaction, in order to produce the starter state for the next. program resembles an iterative, recursive function. Yet, calls to program occur asynchronously. Just as with the object-oriented ATM program, a user may begin the functional ATM program by first selecting a withdrawal amount, <em>then</em> clicking withdraw:</p><pre>select → onchange → &quot;store.publish(<br>                      &#39;WITHDRAWAL_AMOUNT&#39;, {amount: value}<br>                     )&quot;<br>click → onclick → &quot;store.publish(&#39;WITHDRAW&#39;)&quot;<br>...</pre><p>The imperative shell (i.e the store) maintains a reference to the state resulting from the previous call to program, in order to pass such state to the next, orchestrating communication between asynchronous calls to program.</p><h4>Time as a Series of States</h4><p>Unlike object-oriented programming, functional programming provides no model for traditional time. Mathematical functions are time<em>less</em>. Computation of a function f(x) a “second time” with the same argument will produce the same result <em>whenever</em> computed; a mathematical statement like f(20) = 80 will not be made any less true by insinuating time. Similarly, time is no matter against procedures that model mathematical function computation. Simple functions,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/364010e1acaf29399bc700270c53f856/href">https://medium.com/media/364010e1acaf29399bc700270c53f856/href</a></iframe><p>compositions of functions,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e60784287b2156938c66d5053ccbf88d/href">https://medium.com/media/e60784287b2156938c66d5053ccbf88d/href</a></iframe><p>as well as “program” functions like the ATM program introduced above,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec34c99898f28f134d3d5882c33be57b/href">https://medium.com/media/ec34c99898f28f134d3d5882c33be57b/href</a></iframe><p>will produce the same output provided the same input <em>whenever</em> evaluated, independent of time.</p><p>Where we once saw object state change as time <em>elapsed</em>, we now see the program jump from one state to the next at individual (i.e. discrete!) <em>moments in time, </em>as if producing entries in a list, log, “stream of information,” or other time-denominated series. Iterative, recursive functions model this same behavior. factorial, for example, produces a value, say F, for each step, say i:</p><pre>F₀: 1<br>F₁: 1<br>F₂: 2<br>...<br>factorial(i): iterate(Fᵢ₋₁ * i, i - 1)</pre><p>Each run of iterate against the result of the previous run produces a new value just <em>after</em> <em>the</em> <em>last</em> — a discrete piece of information that can viewed together with the rest on the same list. Individual program events can be similarly listed,</p><pre>E₀: DEFAULT_EVENT<br>E₁: WITHDRAWAL_AMOUNT, amount:20<br>E₂: WITHDRAWAL<br>...<br>E(i): Eᵢ</pre><p>as can individual program states:</p><pre>S₀: balance:100, amount:10<br>S₁: balance:100, amount:20<br>S₂: balance:80, amount:20<br>...<br>S(i): program(Sᵢ₋₁, Eᵢ)</pre><p>Each run of program against the result of the previous run, together with event data, produces a new value <em>after</em> the last. Yet, program is a timeless function. With the object-oriented approach, we decompose the state of the program into objects <em>within</em> the program. Each object houses mutable state, and each piece of state may underly a mutative expression that “delineates moments in time” when evaluated.</p><blockquote>We modeled real-world objects with local state by computational objects with local variables. We identified time variation in the real world with time variation in the computer. We implemented the time variation of the states of the model objects in the computer with assignments to the local variables of the model objects. — SICP Section 3.5</blockquote><p>A collection of objects, each delineating moments in time when state may change <em>within</em> the program, embeds a simulation of time within the program. By contrast, with the functional approach, state is kept at the application perimeter and <em>functions</em> are composed together in order to transition the program from one state to another. No simulation of time can be found <em>within</em> the program; no moments can be found within the program <em>when</em> state <em>may</em> change. Rather, the program <em>provides</em> change from one state to the next (i.e. it produces state) and program states represent <em>discrete</em> moments in time when state <em>has</em> changed.</p><blockquote>Think about the issue in terms of mathematical functions. We can describe the time-varying behavior of a quantity x as a function of time x(t). If we concentrate on x instant by instant, we think of it as a changing quantity. Yet if we concentrate on the entire time history of values, we do not emphasize change — the function itself does not change — SICP Section 3.5</blockquote><p>Said another way, in object-oriented programs, we hold the identity of objects constant through change. Objects endure change as time elapses, and thus we model time. In functional programs, we forgo object identity. Change creates something new instead of altering something of old, and thus we model change directly. Change is described succinctly by functions as well as by an “entire time history,” list, log, stream, or other series of resulting states.</p><h4>Reified State</h4><p>Unlike object-oriented programs, functional programs reify state. State can be passed to functions, returned by functions, and generally manipulated like numbers, strings, lists, and other <a href="https://en.wikipedia.org/wiki/First-class_citizen">citizens</a> of the program. With a small addition to the ATM program, for example,</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2Fjmilgrom%2Fjfmea63q%2Fembed%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2Fjmilgrom%2Fjfmea63q%2Fembedded%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/72724b472a72c8b823204cd0023122ac/href">https://medium.com/media/72724b472a72c8b823204cd0023122ac/href</a></iframe><p>we can print (to the console) a representation of the each state of the program in sequence. This change is trivial precisely because state is a known quantity of the program and generally manipulable by program code. inspectReturn takes direct advantage of this quality, printing state to the console and returning state from the internal curried function.</p><h3>Resolving the Time Paradox</h3><blockquote>“No man can ever cross the same river twice.” Because what’s a river? I mean, we love this idea of objects; like there’s this thing that changes. Right? There’s no river. Right? There’s water there at one point-in-time. And another point-in-time, there’s other water there. — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/AreWeThereYet.md">Are We There Yet</a>, quoting Heraclitus.</blockquote><p>From the perspective of a user, a functional program may appear stateful. Interact with the functional ATM program above and notice the program remembering previous encounters. On the one hand, this is not surprising. We included an imperative layer to remember previous states. Instead of decomposing the state of the program into distinct objects, like bankAccount and withdrawalAmount, we created a single global object, the store. On the other hand, focusing on the “object” portion of the program betrays an object-oriented predisposition. The imperative piece of the program is merely syntax, a construct used to facilitate a computation based asynchronously on another; it is not semantics. One can even imagine a programming language where such a construct is built into the language itself, hiding any imperative implementation from the programmer’s view. In fact, such a language exists that compiles to JavaScript.<a href="#908d">⁸</a> The semantics of the program better align with the semantics of a recursive, iterative function, having state S at a discrete step i — run the functional ATM program with the output of the previous run to produce the input for the next.</p><p>That a program with a functional, stateless and timeless core can maintain state is surprising, to say the least. Look around the room, bus, park or wherever you find yourself reading this sentence, and you will likely identify “a collection of distinct objects,” such as dogs, people, and trees, “whose behaviors may change over time.” Look around the functional ATM program, on the other hand, and there are no identifiable objects to be found. Yet, the program appears to have state just like any other object in the room.</p><blockquote>One way to resolve this paradox is to realize that it is the user’s temporal existence that imposes state on the system. If the user could step back from the interaction and think in terms of streams of balances rather than individual transactions, the system would appear stateless — SICP Section 3.5.5</blockquote><p>In other words, the ostensible “paradox” dissipates when the augmentation of our conception of time extends beyond the functional program to include the rest of our physical reality. Instead of viewing the world as the sum of its objects, each reflecting its latest state as time elapses, we may also think in terms of discrete state histories. We may interpret the dog at the park as moving in discrete steps S(i) to S(i+1), just as we interpret the state of our functional program as moving in discrete steps S(i) to S(i+1).</p><p>Consider video media. To movie scenes, we may attribute the same object-oriented semantics. Character and inanimate objects shift, interact and evolve as time elapses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FS60BAGcMCRHzy%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FS60BAGcMCRHzy%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FS60BAGcMCRHzy%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/54d4877d5c90cd6d1730a5ef4608e889/href">https://medium.com/media/54d4877d5c90cd6d1730a5ef4608e889/href</a></iframe><p>Glancing above, for example, we may conclude that “a cat is dancing.” Yet, videos are comprised of static frames stitched together in a certain sequence at discrete time intervals. Each frame corresponds to a state of the video at a moment in time and the frames, taken together, a time-denominated series of discrete states. The media chosen above is intentionally meta. The video includes a TV animation of a scene mirrored by a flip-book, showing static frames strung together at discrete time intervals, which itself is mirrored by a flip-book in “real” life, showing static frames strung together at discrete time intervals. Take another step back to notice that the above gif media being played on <em>your</em> computer is comprised of static frames, strung together at discrete time intervals. There is nothing stopping us from taking another step back and interpreting the real world in which your computer currently sits as static frames, strung together at discrete time intervals. We <em>may</em> attribute normal object-oriented semantics to the above gif, concluding that “a cat is dancing.” However, we may also attribute functional semantics, concluding that “a cat has arms above its head on frame fᵢ.” At a park in the real world, we may conclude that “a dog is chasing a squirrel.” However, we may also conclude that “a dog is in the running motion behind a squirrel in the running motion on frame fᵢ.” In both cases, we may identify a time-series of states instead of objects that change over time. The functional programming paradigm can be coherently applied to world and program alike.</p><p>With a model for discrete time in mind, it is less surprising that functional programs can appear stateful. A user of the program may be viewed as a series of states, just like the program itself. A specific series of user states, for example,</p><pre>U₀: &quot;Open up this blog post&quot;<br>U₁: “Select 20 option”<br>U₂: “Click withdraw”<br>...<br>U(i): Uᵢ</pre><p>directly precipitate a series of program states:</p><pre>S₀: balance:100, amount:10<br>S₁: balance:100, amount:20<br>S₂: balance:80, amount:20<br>...<br>S(i): program(Sᵢ₋₁, Eᵢ)</pre><p>In both cases, pieces of static information may be listed, one <em>after</em> another. Moreover, both lists can be plotted along the same discrete timeline<em> </em>i. User interactions come in a certain order U(i), triggering a run of the program function against the result of the previous run S(i-1) and event data E(i), in order to produce S(i). Our reality can be viewed as a time-series of states, just as it can be viewed as a collection of objects. Functional programming models a time-series of states, just as as object-oriented programming models objects. When the program and world <em>alike</em> can be viewed as “streams of information that flow in the system,” (Section 3) the world can flow into the program and the program back into the world.</p><h3>Addendum</h3><h4>Functional Programming as a Scientific Revolution</h4><blockquote>We were all object-oriented programmers at one point in time — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p>Assimilation of functional semantics with any regular conception of the physical world is no easy task. I kicked around chapter 3 of SICP for over a year before wrapping my head around it. Look again around the room, bus or park and you will likely still identify distinct objects that may change over time. That we may still be experiencing disbelief at the thought of a new model for time suggests a larger game at play.</p><p>Dominant scientific paradigms pervade our language, on the one hand, and way of thinking, on the other.</p><blockquote>Scientific practice always involves the production and the explanation of generalizations about nature; those activities presuppose a language with some minimal richness; and the acquisition of such a language brings knowledge of nature with it. When the exhibit of examples is part of the process of learning terms like “motion,” ‘‘cell,‘‘ or ‘‘energy element,’’ what is acquired is knowledge of language and of the world together. <strong>On the one hand</strong>, the student learns what these terms mean, what features are relevant to attaching them to nature, what things cannot be said of them on pain of self-contradiction, and so on. <strong>On the other hand</strong>, the student learns what categories of things populate the world, what their salient features are, and something about the behavior that is and is not permitted to them. In much of language learning these two sorts of knowledge —<strong> knowledge of words and knowledge of nature</strong> — are acquired together, not really two sorts of knowledge at all, but two faces of the single coinage that a language provides. — Thomas Kuhn, <a href="http://sites.fas.harvard.edu/~hsci161/Sci._Rev._Reader/12_S6_Kuhn.pdf">What are Scientific Revolutions?</a></blockquote><p>As a result, a new discovery “that cannot be accommodated within the concepts in use before” may illicit surprise or even disbelief. “One cannot get from the old to the new simply by an addition to what was already known. Nor can one quite describe the new in the vocabulary of the old or vice versa.” (<a href="http://sites.fas.harvard.edu/~hsci161/Sci._Rev._Reader/12_S6_Kuhn.pdf">Thomas Kuhn</a>)</p><blockquote>Consider the compound sentence, “In the Ptolemaic system planets revolve about the earth; in the Copernican they revolve about the sun.” Strictly construed, that sentence is incoherent. The first occurrence of the term “planet” is Ptolemaic, the second Copernican, and the two attach to nature differently. For no univocal reading of the term “planet” is the compound sentence true. — Thomas Kuhn, <a href="http://sites.fas.harvard.edu/~hsci161/Sci._Rev._Reader/12_S6_Kuhn.pdf">What are Scientific Revolutions?</a></blockquote><p>Rather, in order to “make or to assimilate such a discovery one must alter the way one thinks about and describes some range of natural phenomena” — even the articulation of an observation that runs counter to the dominant paradigm can only be “formulated by altering the language with which nature [is] described.” (<a href="http://sites.fas.harvard.edu/~hsci161/Sci._Rev._Reader/12_S6_Kuhn.pdf">Thomas Kuhn</a>)</p><p>Similarly, object-orientation pervades our language, on the one hand. That “objects change as time elapses” is a statement of obvious fact betrays the object-oriented presumption embedded in our language. “Object” (and “identity”), “change” (and “state”), and “time” work together to describe a coherent <em>object-oriented</em> view. On the other hand, objects orient our perception of our own physical reality.</p><blockquote>Modeling with objects is powerful and intuitive, largely because this matches the perception of interacting with a world of which we are part. — SICP Section 3.5.5</blockquote><p>Look again around the room, bus, park or wherever you find yourself reading this sentence, and you will likely identify “a collection of distinct objects ,” such as dogs, people, and trees, “whose behaviors may change over time.”</p><p>Yet, the behavior of a functional program cannot be described in terms that attribute change to the enduring identity of objects as time elapses. And because of the dominance of object-orientation as reflected in the presumptions of our natural language, we cannot so much as describe the semantics of a functional program except through altering our language and reconstituting our physical reality. Meaningful “identity” must disappear in favor of change itself. “State” must describe the result of change instead of an object quality. “Time” must describe discrete state changes rather than any continuous dynamicness attributable to all objects.</p><p>No wonder the functional model may still illicit disbelief. This essay can be seen as an uphill climb against the gravity of a dominant paradigm. The functional view is perhaps expressible now, but only because of the arduous work put in above. Our natural language is not so easily distorted, violated and repurposed and our thought patterns are comorbid with our language.</p><blockquote>Until those changes had occurred, language itself resisted the invention and introduction of the sought after new theories. The same resistance by language is, I take it, the reason for Planck’s switch from ‘‘element’’ and ‘‘resonator’’ to ‘‘quantum’’ and ‘‘oscillator.’’ Violation or distortion of a previously unproblematic scientific language is the touchstone for revolutionary change. — Thomas Kuhn, <a href="http://sites.fas.harvard.edu/~hsci161/Sci._Rev._Reader/12_S6_Kuhn.pdf">What are Scientific Revolutions?</a></blockquote><p>As a result, teaching functional programming is like teaching a Ptolemaic astronomer about Copernican astronomy or a Newtonian physicist about quantum mechanics. We lack the basic language to articulate the underlying concepts. Worse still, the language we do have is endemic to a conflicting paradigm. Perhaps the disparity between the efficacy<a href="https://medium.com/p/1017699112d7/edit">⁹</a> and popularity<a href="#5a4c">¹⁰</a> of functional programming languages is best explained in this light.</p><blockquote>A new scientific truth does not triumph by convincing its opponents and making them see the light, but rather because its opponents eventually die, and a new generation grows up that is familiar with it — Max Plank, <a href="https://pubs.acs.org/doi/pdf/10.1021/ed027p288.1">autobiography</a>, quoted by Thomas Kuhn, <a href="https://en.wikipedia.org/wiki/The_Structure_of_Scientific_Revolutions">The Structure of Scientific Revolutions</a></blockquote><p>Nevertheless, the functional view is indeed expressible as a result of the work put in above. We can see change as creating something new, instead of altering something of old, and time as a series of successive states. We can alter our language and reimagine our physical reality to support a functional view of change, state and time.</p><p><a href="#c541">⁰</a> Many of these insights can be found in original form in the <a href="https://web.mit.edu/alexmv/6.037/sicp.pdf">Structure and Interpretation of Computer Programs </a>(SICP). There you will find a life-altering discussion of the same topics using Scheme, a Lisp dialect like Clojure. All code examples included here however, even if borrowed, will be couched in terms of JavaScript. If you know JavaScript and are unfamiliar with Scheme, this article may be immediately accessible to you without first learning how “<a href="https://crockford.com/javascript/javascript.html">to balance all those parens</a>.” Little is lost in translation as well. JavaScript has first-class functions (i.e. lambdas), closures (i.e. function-delimited lexical scoping) and generally thrives when used functionally.</p><blockquote>JavaScript’s functions are first class objects with (mostly) lexical scoping. JavaScript is the first lambda language to go mainstream. Deep down, JavaScript has more in common with Lisp and Scheme than with Java. It is Lisp in C’s clothing. — Douglas Crockford, <a href="https://www.oreilly.com/library/view/javascript-the-good/9780596517748/ch01s02.html">JavaScript: The Good Parts</a></blockquote><p>There is even an ongoing <a href="https://sicp.comp.nus.edu.sg/">academic effort</a> to translate the full text of SICP into JavaScript. Also considered, JavaScript is a close cousin of TypeScript, which enables traditional object-oriented constructs like private and public and functional constructs like readonly and as const at compile time. Perhaps in JavaScript (and TypeScript), we get enough support of functional and object-oriented programming paradigms to enable a discussion of both within a single, ubiquitous language.</p><p><a href="#0508">¹</a> Immutability is an important part of the equation as well. We’ll cover this soon in the section titled <em>Unchangeability is Fundamental to Functional Programming.</em></p><p><a href="#4742">²</a> Object-oriented programming is also traditionally associated with code reuse through inheritance, among other patterns, that reinforce the object model.</p><p><a href="#84c3">³</a> The creator of Clojure at it again:</p><blockquote>But as soon as we introduce… the idea that the value of a variable can change, a variable can no longer be simply a name. Now a variable somehow refers to a place where a value can be stored, and the value stored at this place can change.” — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p><a href="#ec67">⁴</a> Never has the delineation between syntax and semantics been more pronounced than with <a href="https://martinfowler.com/bliki/ValueObject.html">value objects</a>, which commandeer object-oriented syntax to effect <em>non</em>-object semantics — i.e. immutable values. If not for the divergence between syntax and semantics, so-called “value objects” would be a contradiction in terms. We’ll cover the inherent mutability of objects soon in the sections titled <em>Changeability is Fundamental to Object Semantics</em> and <em>“Object” Names Changeability</em>.</p><p><a href="#7daa">⁵</a> Contextual immutability says nothing of local variables. In fact, a variable that is reassigned within the same procedure in which it was initialized cannot impact the semantics of such procedure.</p><blockquote>…any mutation that is ever done to any of these is to rebind local variables…that doesn’t affect the fact that these objects are immutable from an outside perspective” Gary Bernhardt, <a href="https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell">Functional Core, Imperative Shell</a></blockquote><p>decrement100 may be implemented with internal mutability, for example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afdc12d71963c2c65bf308428fd34222/href">https://medium.com/media/afdc12d71963c2c65bf308428fd34222/href</a></iframe><p>without affecting external semantics; the output of decrement100 still depends only on the input. Even block-scoped looping constructs like while, for and do may be part of procedures that produce the same output provided the same input, notwithstanding reassignment of variables tracking iteration state (e.g. i, j, k, n, etc.) with every loop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cec6dcfce360be458459f6e677816e80/href">https://medium.com/media/cec6dcfce360be458459f6e677816e80/href</a></iframe><p>factorial will produce the same output provided the same input. On the other hand, changeability that is internal to one procedure definition may be positioned externally to another when <a href="https://en.wikipedia.org/wiki/Nested_function">lexical procedural nesting is supported</a>. balance, for example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fff3a15103e473f978484a1e92f497e/href">https://medium.com/media/3fff3a15103e473f978484a1e92f497e/href</a></iframe><p>is external to withdraw although internal to makeBankAccount and undermines the functional semantics of withdrawal as a result, as discussed above. <a href="https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example/750506">Notoriously unintuitive effects</a> manifest when looping is combined with procedural nesting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d39f77a0677d1a8a4a1eb6777453b747/href">https://medium.com/media/d39f77a0677d1a8a4a1eb6777453b747/href</a></iframe><p>As a result, comprehensive immutability can be seen as defending functional programming in the face of procedural nesting. It also appears that functional semantics could theoretically coincide with traditional looping constructs and other locally-scoped mutation so long as procedural nesting was prohibited. Nevertheless, immutability is generally considered an inseparable part of functional programming; no distinction is made in SICP and elsewhere (that I have encountered). Perhaps there is something else to be said here about lambda calculus and a more formal definition of functional programming. Or, perhaps the many benefits of nested procedures (e.g. modules, closures, etc.) so obviously outweigh the superficial “costs” of forgoing looping to even consider such crazy talk. Recursive procedures can do anything looping constructs can and without performance regressions because of tail recursion and other optimization techniques at the compiler level.</p><p><a href="#cebc">⁶</a> That two equivalent expressions may be substituted for one another without altering the meaning of the program is known as <a href="https://en.wikipedia.org/wiki/Referential_transparency">referential transparency</a>.</p><blockquote>A language that supports the concept that “equals can be substituted for equals” in an expression without changing the value of the expression is said to be referentially transparent — SICP Section 3.1.3</blockquote><p><a href="#cf6a">⁷</a> ❤️ The original insight️ ❤️</p><blockquote>In general, so long as we never modify data objects, we can regard a compound data object to be precisely the totality of its pieces. For example, a rational number is determined by giving its numerator and its denominator. But this view is no longer valid in the presence of change, where a compound data object has an “identity” that is something different from the pieces of which it is composed. A bank account is still “the same” bank account even if we change the balance by making a withdrawal; conversely, we could have two different bank accounts with the same state information. This complication is a consequence, not of our programming language, but of our perception of a bank account as an object. — SICP Section 3.1.3</blockquote><p>Rich Hickey on the same subject:</p><blockquote>If it is immutable, it now taps into that definition of value we saw before. Because by being immutable we can go and take a string value, and another string value, and say: are they the same? Do they have the same magnitude? Are they talking about the same thing? Are they expressing the same specific meaning? All of those definitions of values apply to something that is not mutable. So that relative worth thing kicks in. — Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p><a href="#d718">⁸</a> <a href="https://guide.elm-lang.org/">Elm</a> programs are trivially made to be stateful, notwithstanding the exclusive use of pure functions <em>and</em> the asynchrony of user interactions! This counter program</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c6ca4bd52d9a1d605353375da53c30e/href">https://medium.com/media/7c6ca4bd52d9a1d605353375da53c30e/href</a></iframe><p>can be seen <a href="https://elm-lang.org/examples/buttons">here</a> tracking counter state, even though a user may of course click the counter buttons asynchronously. Like garbage collection in JavaScript, Elm hides any imperative code dedicated to communication between asynchronous scripts from the programmer’s view.</p><p><a href="#cafa">⁹</a> There are many advantages to functional programming. Programs that deal with mutation are “drastically more difficult” to reason about than ones that do not.</p><blockquote>Referential transparency is violated when we include set! [i.e. assignment operations] in our computer language. This makes it tricky to determine when we can simplify expressions by substituting equivalent expressions. Consequently, reasoning about programs that use assignment becomes drastically more difficult — SICP Section 3.1.3</blockquote><p>In particular, functions avoid <a href="https://www.yegor256.com/2015/12/08/temporal-coupling-between-method-calls.html">temporal coupling</a> since there is no time,</p><blockquote>In general, programming with assignment forces us to carefully consider the relative orders of the assignments to make sure that each statement is using the correct version of the variables that have been changed. This issue simply does not arise in functional programs. — SICP Section 3.1.3</blockquote><p>and dramatically reduce debugging and unit testing complexity since there is no meaningful context.</p><blockquote>“And that is the problem with places. You have this sort of global state that you have to reproduce in order to debug a field problem. That is very very tough.” Rich Hickey, <a href="https://github.com/matthiasn/talk-transcripts/blob/master/Hickey_Rich/ValueOfValuesLong.md">The Value of Values</a></blockquote><p>Reified state couches in writing what must otherwise live as thoughts in programmers’ heads — each member of a team can read a function signature instead of building up (hopefully) the same working memory for each object. Couching state in language makes it accessible to static language analysis tools. <a href="https://blog.ploeh.dk/2019/07/01/yes-silver-bullet/#bd2d47d8dac2401e936ca7902bc9109d">A compiler may exhaustively permute the set of application states</a> without actually running manually-written (exhaust<em>ing</em>) unit tests. Functional programs are more easily parallelized since they are just functions with no internal model for time.</p><blockquote>Unfortunately, the complexities introduced by assignment become even more problematic in the presence of concurrency. — SICP Section 3.4</blockquote><p>These advantages have been known for decades. John Backus “gave high visibility to functional programming” (SICP Section 3.5.5; also see Simon Peyton-Jones, <a href="https://www.youtube.com/watch?v=re96UgMk6GQ">Escape from the ivory tower: the Haskel journey</a>) through his <a href="https://www.thocp.net/biographies/papers/backus_turingaward_lecture.pdf">Turing Award lecture</a> in 1978, seven years before the creation of <a href="https://en.wikipedia.org/wiki/C%2B%2B">C++</a> and thirteen before <a href="https://en.wikipedia.org/wiki/Java_%28programming_language%29">Java</a>.</p><p><a href="#cafa">¹⁰</a> The <a href="https://www.tiobe.com/tiobe-index/">20 most popular languages</a> are predominantly imperative or object-oriented.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1017699112d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[watch, watchGroup, watchCollection and Deep Watching in AngularJS]]></title>
            <link>https://medium.com/@jbmilgrom/watch-watchgroup-watchcollection-and-deep-watching-in-angularjs-6390f23508fe?source=rss-1f399d61fc99------2</link>
            <guid isPermaLink="false">https://medium.com/p/6390f23508fe</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[Jonathan Milgrom]]></dc:creator>
            <pubDate>Fri, 20 May 2016 12:37:59 GMT</pubDate>
            <atom:updated>2020-06-22T01:31:31.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol3us_IBiS6O3qi4VWYu9Q.jpeg" /></figure><h4>The Many Layers of Change Detection in Angular 1.x</h4><p>(<em>This post has been </em><a href="https://jonathanmilgrom.com/post/angular-change-detection/"><em>migrated here</em></a><em>.</em>)</p><p>A user clicks the “upvote” button,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/52/1*kU6Q7pi0coovXxIOy8UaEw.png" /></figure><p>attempting to increase the vote count to 1034. An action <em>$apply</em><strong>’</strong>ed through an <em>ng-click</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20073860802ff308e507627eb17fe4d0/href">https://medium.com/media/20073860802ff308e507627eb17fe4d0/href</a></iframe><p>would trigger a <em>$digest</em> cycle under the hood, which checks all registered <em>$watch</em>’es for changes. Then, an expression providing “voted” styling for answers<em>, </em>registered through <em>ng-class</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3f2143768324a69e23ef5fdc80994fe/href">https://medium.com/media/f3f2143768324a69e23ef5fdc80994fe/href</a></iframe><p>and an expression providing the aggregate number of votes, registered through double curly braces <em>{{}}</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fc4732bc90242f3ea00336a76828a90/href">https://medium.com/media/0fc4732bc90242f3ea00336a76828a90/href</a></iframe><p>would trigger the appropriate DOM updates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/1*CxheOXIunYTXze80R08l5A.png" /></figure><p>Change detection is a fundamental part of AngularJS applications. Whether utilizing native AngularJS directives or building your own, an understanding of the many layers of data watching is essential to understanding Angular.</p><h3><strong>Some I</strong>nteresting (but skippable)<strong> background</strong></h3><h4>An angular expression can produce different values over time.</h4><p>Watching consists of getting the value of an expression and performing a task when it has changed. In angular, an expression can take the form of a string or a javascript function:</p><p><em>1. any ol’ javascript function</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b5f53cbfed298263aa75955dc91e67c/href">https://medium.com/media/1b5f53cbfed298263aa75955dc91e67c/href</a></iframe><p><em>2. string</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c676a7f4571691e2e13ff581afccf7e4/href">https://medium.com/media/c676a7f4571691e2e13ff581afccf7e4/href</a></iframe><p><strong>Function or… string?</strong> Internally, the first thing the <em>$scope.$watch</em> method does is <a href="https://github.com/angular/angular.js/blob/v1.5.3/src/ng/rootScope.js#L387">pass its first parameter to the $parse service</a>. The <em>$parse</em> service is a function (obviously) that returns another function (let’s call it the “parseFn”). The <em>parseFn</em> expects to be called with the desired context object against which the original string or function may be evaluated e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3b63b23c359446dedc7e05d2383e6e6/href">https://medium.com/media/e3b63b23c359446dedc7e05d2383e6e6/href</a></iframe><p>If the <em>$parse</em> service receives a string, <a href="https://github.com/angular/angular.js/blob/v1.5.3/src/ng/parse.js#L1791">work needs to be performed</a> in order to translate the string into proper javascript that is capable of evaluation against an object i.e. a function. On the other hand, if it receives a function, well… <a href="https://github.com/angular/angular.js/blob/v1.5.3/src/ng/parse.js#L1822">not much needs to happen</a>. Since the service has received what it must produce, it may assume the function has been properly prepared. As you can see, most of the angular “magic” lies in parsing the string parameter into such a function to enable the intake of a string.</p><p><strong>At any point in time</strong>. There is a reason angular has chosen the function-with-context-object-parameter structure: <em>c</em>alls to the function reveal changes to underlying context, which means that the function can be invoked at any point in time to retrieve the value of the underlying expression or function <em>at such time</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b02130e1ec0aaaa9219340a0b8be69ca/href">https://medium.com/media/b02130e1ec0aaaa9219340a0b8be69ca/href</a></iframe><p>Since scope objects are…objects, this of course works with scope objects as well. The string <em>‘vm.answer.isVotedFor(vm.user)’ </em>from the “upvote” example above — after being passed to <em>parse </em>by <em>watch</em> and transformed into a function that is ready to accept an object — was ready to reveal any new <em>isVotedFor </em>status reflected in an updated scope object. Now the function-returning-a-function structure of the parse service also begins to make sense. The returned function (i.e the <em>parseFn</em>), prepped and ready to accept the latest scope object, is exactly what the digest cycle needs and <a href="https://github.com/angular/angular.js/blob/v1.5.3/src/ng/rootScope.js#L413">precisely what it receives</a> in order to get the latest value of an expression. Sensibly, the <em>parseFn</em> is <a href="https://github.com/angular/angular.js/blob/v1.5.3/src/ng/rootScope.js#L387">named “get” internally</a> because of these getter qualities.</p><p><strong>Against the last cached value</strong>. Now to determine change, all the <em>$digest</em> cycle has left to do is cache the <em>last</em> value retrieved by the registered <em>parseFn</em> and compare it to the next….which brings us to the topic of this post: this comparison between new and old values, what constitutes equality and the multiple levels of change detection in angular.</p><h3>$watch — type 1</h3><p>The simplest and most common, this type of <em>watch</em> uses javascript’s <em>===</em><strong><em> </em></strong>operator to compare old and new values, invoking the callback only upon <em>strict inequality</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc183fd38dc3a257ae0d3459d04fd58/href">https://medium.com/media/8fc183fd38dc3a257ae0d3459d04fd58/href</a></iframe><p>For expressions that evaluate to primitive types like Strings and Numbers, this has a predictable effect. Old and new values of <em>4</em> and <em>4</em> are considered equal, but<em> 4 </em>and <em>5</em> and<em> 4</em> and <em>‘4’ </em>are not. Similarly, <em>‘hello’</em> and <em>‘hello’</em> will not register a change, but <em>‘hello’</em> and <em>‘goodbye’</em> will. In the above “upvote” example, angular’s curly brackets <em>{{}}</em> registered <a href="https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L2782"><em>this</em> type of watch</a> for the expression <em>vm.answer.voteCount()</em>. When <em>1034</em> was compared against <em>1033</em>, a change was registered.</p><p>For expressions that evaluate to javascript<em> objects</em>, strict equality means something less intuitive. The same object, no matter how mutated between equality checks, will <em>not</em> register “change”, whereas, two different objects, no matter how similar, will:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90f6c6cb19633871284517ef9636bd03/href">https://medium.com/media/90f6c6cb19633871284517ef9636bd03/href</a></iframe><p>The important thing to note in determining how change is registered is not whether two objects have the same properties but whether two objects refer to the same address in memory i.e whether they are the same object. Notice in the above example that different objects with exactly the same properties and values nevertheless register change and print to the console with the latest object because they are different objects. Whereas, the same object reference prints nothing to the console no matter how mutated between equality checks.</p><h3>$watchGroup — type 2</h3><p>This type of watch can handle multiple expressions instead of being limited to just one, invoking the registered callback when <em>any</em> of the expressions have changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e267001df18b70bfa769ce62c51d372f/href">https://medium.com/media/e267001df18b70bfa769ce62c51d372f/href</a></iframe><p>You may want to use this type of watch if two or more properties are coupled. In the above “upvote” example, you could use this watch to disable further voting if an answer has been voted for <em>or</em> against:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd59f1d5e356a4bdf07e3ea81deb29dc/href">https://medium.com/media/bd59f1d5e356a4bdf07e3ea81deb29dc/href</a></iframe><p>The important thing to note is that the containing array itself is <em>not</em> watched by <em>watchGroup, </em>in stark contrast to (maybe the more familiar) <em>watchCollection; </em>rather<em>, </em>each member of the array is. Much like the subject of a regular type 1 <em>watch</em>, each member of the array can itself be a string expression capable of contextual evaluation or a function ready to be passed a context object. As a result, <em>watchGroup</em> can be seen as simply a way to group together multiple regular type 1 <em>watch’</em>es with a single callback function. When <em>any of the grouped </em>watches registers a change, the callback is invoked. This set up has the benefit of allowing expressions to be members of the group as described. But members of the group cannot be dynamically added or subtracted and order is not an applicable concept…which brings us to <em>watchCollection</em>.</p><h3>$watchCollection — type 3</h3><p>This type of watch is intended for javascript arrays, invoking the callback when collection level changes have occurred.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9570b898823bf163f1a30d020e0a1810/href">https://medium.com/media/9570b898823bf163f1a30d020e0a1810/href</a></iframe><p>Where <em>watchGroup</em> allows multiple expressions capable of contextual evaluation to point to one callback, <em>watchCollection</em> allows only one — in the above example, <em>‘firstTeam’</em>. On the other hand, the type of watch applied to such expression is more involved. Type 1 watchers care only about addresses for objects and values for primitives. As objects themselves, arrays are no different. Subject to a type 1 watch, expressions that evaluate to an array will not register change no matter how mutated between checks until switched out for an entirely new array and address in memory. <em>watchCollection</em> is vastly different. Mutation is the name of the game. In particular, <em>watchCollection</em> keeps its eye on two types of surface level array mutations: (1) addition/subtraction and (2) reordering. Adding or subtracting members of the array and reordering members of the array result in change being recognized and the registered callback being invoked. watchCollection only stops short of watching below-surface mutation i.e. deep mutation, mutations to the members themselves… which brings us to deep watching.</p><h3>$watch(…, …, true) — type 4</h3><p>The most expensive watch, this type of watch is also the most thorough, recursively scaling the depths of any complex object and invoking the registered callback when any branch of the tree has undergone change. Note the <em>true</em> flag, which tells angular to perform this type of watch instead of a type 1:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/877534adc52574bce1f2a32065f01cb8/href">https://medium.com/media/877534adc52574bce1f2a32065f01cb8/href</a></iframe><p>Deep watching has no limitations, other than performance of course — the last thing your application needs is recursive journeys into the depths of complex objects <em>every</em> digest cycle. On the other hand, deep watching can keep any complex data in sync with the view and, as a result, may be the easiest to understand: all change is change.</p><p>This has been a discussion of the many layers of data watching in AngularJS. I hope it helps inform your choice among them!</p><p>Quote of the Day:</p><blockquote>Reporter: Why do you shoot so many 3&#39;s?</blockquote><blockquote><a href="http://espn.go.com/blog/truehoop/post/_/id/22316/behold-the-4-pointer">Antoine Walker</a>: Because there aren’t any 4&#39;s.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6390f23508fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where Javascript Memory Management Ends and Angular $destroy Begins]]></title>
            <link>https://medium.com/@jbmilgrom/where-javascript-memory-management-ends-and-angulars-destroy-begins-d22d683430a6?source=rss-1f399d61fc99------2</link>
            <guid isPermaLink="false">https://medium.com/p/d22d683430a6</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jonathan Milgrom]]></dc:creator>
            <pubDate>Sat, 30 Apr 2016 19:30:39 GMT</pubDate>
            <atom:updated>2016-09-07T01:53:32.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNvM6iCGGdT0mXaohO3Fdg.jpeg" /></figure><h4>A brief look inside the source code (<em>inspired by this </em><a href="http://stackoverflow.com/questions/36273862/do-i-need-to-destroy-local-controller-variables-when-directive-is-destroyed/36390832#36390832"><em>SO question</em></a><em>)</em></h4><p>Keep this example controller function in mind:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce8179ec6b3bd230a1a5389411959cf3/href">https://medium.com/media/ce8179ec6b3bd230a1a5389411959cf3/href</a></iframe><h4>Javascript memory management — garbage collector</h4><p>Memory <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">will be allocated for an object when created</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaa0ade63f1c1bfc01e8f3ce93bcc440/href">https://medium.com/media/eaa0ade63f1c1bfc01e8f3ce93bcc440/href</a></iframe><p>You may then <em>console.log(o.iThink)</em> and <em>‘thereforeIAm’ </em>will be read from its place in memory and printed to the console.</p><p>If you wanted to create a new string and lost the <em>need</em> for the <em>{iThink: ‘thereforeIAm’}</em> object, you may decide to overwrite <em>o</em> instead of introducing a new variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2aa843adb04ca10b220b622083b0e8b/href">https://medium.com/media/d2aa843adb04ca10b220b622083b0e8b/href</a></iframe><p>Fortunately, references (or lack thereof) send a clear message internally to javascript’s garbage collector as to whether a piece of finite memory should remain allocated or freed to perform other tasks. In this case, no reference remains to the object and string previously allocated for <em>{iThink: ‘thereforeIAm’}</em> and the corresponding memory may be freed (i.e. “garbage-collected”) as result.</p><p>Importantly, note that garbage collection happens internally. No code has to be written by you to that effect. All you need to concern yourself with is the value of <em>o</em> and the garbage collector can <em>infer need</em>, more or less, <em>from remaining reference</em>.</p><h4>Angular memory management — $scope.$destroy</h4><p>Unfortunately, the cleanup tasks related to <em>$scope</em> removal<em> cannot be inferred</em> by the javascript garbage collector based on<em> reference alone</em>; additional code is required.</p><p>That is because <em>$scope</em> objects embody a concept more complex than any ol’ javascript object. In particular, when no use remains in your application for a certain <em>$scope</em> object, no use <em>must also remain </em>for any associated <em>$$watchers</em> previously registered with the <em>$scope.$watch</em> method and no use <em>must also remain</em> for “children” <em>$scope</em> objects. The javascript garbage collector cannot infer this relationship from simple reference removal. Setting <em>$scope</em> to <em>null </em>will certainly clear the memory allocated directly for such object, but not much else can be accomplished.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da926651a5fea089a2703a3ac13d9e8d/href">https://medium.com/media/da926651a5fea089a2703a3ac13d9e8d/href</a></iframe><p>In other words, the garbage collector has to be told what to do (<a href="https://github.com/angular/angular.js/blob/v1.5.5/src/ng/directive/ngIf.js#L113">and when to do it</a>), which is exactly what the <a href="https://github.com/angular/angular.js/blob/v1.5.3/src/ng/rootScope.js#L895"><em>$scope.$destroy</em> method</a> does. Note these lines in particular:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2652d920afc47f6b9ec9659ace8e855/href">https://medium.com/media/f2652d920afc47f6b9ec9659ace8e855/href</a></iframe><h4>The example controller function</h4><p>When a function is invoked, the memory allocated for internally scoped objects will only remain allocated to the extent references remain past the life of the invocation (non-coincidentally, the essence of a closure).</p><p>In the example of the controller, <em>uploader</em> and <em>reader</em> objects are created and <em>uploader</em> is set to scope. No references remain to <em>reader</em> at all after the controller function is run, rendering <em>reader</em> eligible for garbage collection immediately thereafter. On the other hand, <em>uploader</em> is attached to an object that outlives the function’s invocation and so must remain an occupant of allocated memory until such object is destroyed. As a result, only a call to <em>$scope.$destroy</em> would enable the reallocation of memory once allocated to <em>uploader </em>as the lack of need cannot be inferred from reference alone.</p><p><strong>Quote of the day:</strong></p><blockquote>Each product era can be divided into two phases: 1) <em>the gestation phase</em>, when the new platform is first introduced but is expensive, incomplete, and/or difficult to use, 2) <em>the growth phase</em>, when a new product comes along that solves those problems, kicking off a period of exponential growth. The Apple II was released in 1977 (and the Altair in 1975), but it was the release of the IBM PC in 1981 that kicked off the PC growth phase. The internet’s gestation phase took place in the <a href="https://en.wikipedia.org/wiki/National_Science_Foundation_Network">80s and early 90s</a> when it was mostly a text-based tool used by academia and government. The release of the Mosaic web browser in 1993 started the growth phase, which has continued ever since.There were feature phones in the 90s and early smartphones like the Sidekick and Blackberry in the early 2000s, but the smartphone growth phase really started in 2007–8 with the release of the iPhone and then Android.</blockquote><blockquote>— <a href="https://medium.com/software-is-eating-the-world/what-s-next-in-computing-e54b870b80cc#.jszig85hi">Chris Dixon</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d22d683430a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AngularJS 1.x: Building Reusable Directives]]></title>
            <link>https://medium.com/@jbmilgrom/angularjs-1-x-46a6dfe21007?source=rss-1f399d61fc99------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a6dfe21007</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[directives]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jonathan Milgrom]]></dc:creator>
            <pubDate>Tue, 23 Jun 2015 17:19:35 GMT</pubDate>
            <atom:updated>2018-08-21T23:11:12.982Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Power of Angular</h4><p>Angular offers many benefits to developers building complex web applications. Expressive HTML, model and view syncing and dependency injection are a few of the most powerful. But the true power of Angular comes from the whole being greater than the sum of its parts. This is something that is difficult to relay in its entirety through a blog post or a single example (and difficult to grasp period!). Like with all programming languages or deeply thoughtful frameworks, an understanding of best practices is probably best teased out through experience solving real problems and maintaining real code. Nonetheless, I think the best place to begin digging is reusable directives: Angular provides the developer the unique ability to underwrite simple, elegant and importantly, reusable components around which maintainable domain specific applications can come into shape. There, much of Angular’s power comes into focus. And with the release of Angular 2 on the horizon, there’s no better time to write reusable directives (component-based directives anyone?). So let’s begin!</p><h3>nullifyModel</h3><p>Client-side web applications often must expressly nullify “falsey” form data to correctly interact with a server-side API and effect the desired change to the database. Repeating such type conversion logic with every form would unnecessarily grow the code base, obscure the logic actually unique to each form and clearly violate the D.R.Y. (Don’t Repeat Yourself) principle. One solution might be to place such logic in a service and inject it into every controller or link function corresponding to the desired form. This is a fine solution that avoids repetition by ushering the logic into one place. However, this would require <strong>$watch</strong>ing each model of interest for any “falsey” value in order to expressly nullify the model upon such an event. This feels unnecessarily heavy handed. Why watch the model for all changes when the work that needs to be performed must happen only upon a prescribed and limited set of events (i.e. “falsey”ness)? Not to worry; with Angular, you can do one better. The ng-model controller API together with Angular’s powerful directive API allow you to cabin the logic in its proper place, avoid adding the unnecessary $watch and, ultimately, make your HTML come to life.</p><p>Here’s what the HTML consuming the directive might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb9540d2cfd9db7fd2e33cb4befcbb2/href">https://medium.com/media/3fb9540d2cfd9db7fd2e33cb4befcbb2/href</a></iframe><p>Notice how the interface is exceedingly simple. Type ‘nullify-model’ (13 characters by my count) into any input tag, even one that’s already part of another custom form component, and any “falsey” value will be translated to ‘null’ for correct server-side processing. And the HTML is expressive! The behavior added to the input tag can be easily surmised from the attribute aptly named “nullifyModel”. Now, looking under the hood at the directive’s implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae58dad0f3340fdaffda41149d8e7f5c/href">https://medium.com/media/ae58dad0f3340fdaffda41149d8e7f5c/href</a></iframe><p>Notice that I’ve moved the nullify logic into a separate filter so it’s accessible/reusable elsewhere throughout the application if necessary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d945fe240142636cc286514a315a6566/href">https://medium.com/media/d945fe240142636cc286514a315a6566/href</a></iframe><p>Ahhhh… so easy to read and so simple! All values inputted into the input element by a user will be <strong>$parse</strong>d for “falsey” values and converted expressly to null. Ng-model controller’s $parse method runs the ‘nullify’ filter <em>prior to </em>assigning any <em>return value</em> to the model. As a result, the model may never reference a “falsey” value and no longer needs to be <strong>$watch</strong>ed for such an event. Dependency injection allows the nullify logic to be what it is — a filter replacing one value with another — and only injected when needed, in this case, into the ‘nullifyModel’ directive. The true “trick”, however, is that all of Angular’s power is on display. Data and view syncing, dependency injection and the Angular directive API allow for expressive HTML and the creation of a (hopefully!) reusable directive.</p><p>Quotes of the Day:</p><blockquote>Writing software as multiple layers is a powerful technique even within applications. Bottom-up programming means writing a program as a series of layers, each of which serves as a language for the one above. This approach tends to yield smaller, more flexible programs. It’s also the best route to that holy grail, reusability. A language is by definition reusable. The more of your application you can push down into a language for writing that type of application, the more of your software will be reusable. — <a href="http://www.paulgraham.com/hundred.html">Paul Graham</a></blockquote><blockquote>Code is inert. How do you make it ert? You run software that transforms it into machine language. The word “language” is a little ambitious here, given that you can make a computing device with wood and marbles. Your goal is to turn your code into an explicit list of instructions that can be carried out by interconnected logic gates, thus turning your code into something that can be executed — software. — <a href="http://www.bloomberg.com/graphics/2015-paul-ford-what-is-code/">Paul Ford</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a6dfe21007" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Record: Many-to-Many Self Join Table]]></title>
            <link>https://medium.com/@jbmilgrom/active-record-many-to-many-self-join-table-e0992c27c1e?source=rss-1f399d61fc99------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0992c27c1e</guid>
            <dc:creator><![CDATA[Jonathan Milgrom]]></dc:creator>
            <pubDate>Mon, 04 Aug 2014 23:52:10 GMT</pubDate>
            <atom:updated>2024-02-18T17:41:19.481Z</atom:updated>
            <content:encoded><![CDATA[<h2>Active Record Join Tables</h2><h3>From “Plain Vanilla” to Many-to-Many Self Join</h3><p><em>(This post has been </em><a href="https://softwarefordays.com/post/active-record-join-tables/"><em>migrated here</em></a><em>.)</em></p><h4>Plain Vanilla Join Table</h4><p>Ordinarily, a join table works to account for a many-to-many relationship between two otherwise independent models. As an example, a <strong>Player</strong> may be a member of many :teams over the course of a career. Conversely, each <strong>Team</strong> may have many <strong>:</strong>players. Each <strong>Contract</strong> joins a <strong>Player</strong> to a <strong>Team</strong>.</p><p><a href="https://github.com/jbmilgrom/rails_crud_rspec/blob/master/app/models/team.rb">app/models/team.rb</a></p><pre>class Team &lt; ActiveRecord::Base<br>  has_many :players, through: :contracts<br>  has_many :contracts<br>end</pre><p><a href="https://github.com/jbmilgrom/rails_crud_rspec/blob/master/app/models/player.rb">app/models/player.rb</a></p><pre>class Player &lt; ActiveRecord::Base<br>  has_many :teams, through: :contracts<br>  has_many :contracts<br>end</pre><p><a href="https://github.com/jbmilgrom/rails_crud_rspec/blob/master/app/models/contract.rb">app/models/contract.rb</a></p><pre>class Contract &lt; ActiveRecord::Base<br>  belongs_to :player<br>  belongs_to :team<br>end</pre><p><a href="https://github.com/jbmilgrom/rails_crud_rspec/blob/master/db/schema.rb">db/schema.rb</a></p><pre>ActiveRecord::Schema.define(version: 20140706210328) do<br><br> create_table &quot;contracts&quot;, force: true do |t|<br>   t.integer &quot;team_id&quot;<br>   t.integer &quot;player_id&quot;<br>   t.integer &quot;term&quot;<br>   t.integer &quot;deal_value&quot;<br> end<br><br> create_table &quot;players&quot;, force: true do |t|<br>   t.string &quot;name&quot;<br>   t.integer &quot;height&quot;<br>   t.datetime &quot;created_at&quot;<br>   t.datetime &quot;updated_at&quot;<br> end<br><br> create_table &quot;teams&quot;, force: true do |t|<br>   t.string &quot;name&quot;<br>   t.string &quot;city&quot;<br>   t.datetime &quot;created_at&quot;<br>   t.datetime &quot;updated_at&quot;<br> end<br><br>end</pre><p>Under the hood, the “player” in player_id and “team” in team_id in any instance of <strong>Contract</strong> are understood by Active Record to join such <strong>Player</strong> and <strong>Team</strong> through (as foreign keys of) an instance of <strong>Contract.</strong> @player.teams may then query the database for all :teams sharing an instance of <strong>Contract</strong> with @player and @team.players may query the database for all players sharing an instance of <strong>Contract</strong> with @team.</p><h4>Has_many | Belongs_to — Self Join Table</h4><p>A table may have models that have relationships with other models in the same table. Instead of creating two independent tables, it often makes more sense to create a self-join table to account for these types of relationships. Rails documentation provides <a href="http://guides.rubyonrails.org/association_basics.html#self-joins">a great example</a>. In addition to having a name, phone number and other attributes, an <strong>Employee</strong> may also be a manager of <em>other</em> <strong>Employees</strong>. In this example, a :subordinate may only have one :manager. Nonetheless, splitting the Employee model into two separate tables (maybe called Managers and Subordinates), duplicating code, and muddying entity relationships (what do you do when a subordinate gets promoted? How do you account for multilevel management, where a manager is the subordinate of another manager), offers a less-than-optimal solution. Here’s how a has_many | belongs_to self-join might work (taken from rails documentation linked above):</p><p>app/models/employee.rb</p><pre>class Employee &lt; ActiveRecord::Base<br> has_many :subordinates, class_name: “Employee”, <br>                         foreign_key: “manager_id”<br><br> belongs_to :manager, class_name: “Employee”<br>end</pre><p>As can be seen in the above code, self referential relationships offer added complexity. :manager and :subordinates are both <strong>Employees</strong> in the database, but must be identified as such and distinguished. This is handled by supplying the :subordinates and :manager “names” expressly, and explicitly referencing, in each case, the class_name: to which such names apply, in each case, “Employee”.</p><p>Since each :subordinate may have only one :manager, a single column may be added when creating the <strong>Employee</strong> table to store the manager_id of each <strong>Employee</strong>’s (:subordinate’s) :manager, as is done below:</p><pre>class CreateEmployees &lt; ActiveRecord::Migration<br>  def change <br>    create_table :employees do |t|<br>      t.references :manager<br><br>      t.timestamps<br>    end<br>  end<br>end</pre><p>To determine a :manager’s :subordinates (upon an @employee.subordinates call), Active Record may now look at each instance of <strong>Employee</strong> where the manager_id (i.e. foreign_key: :manager_id) of such :manager is stored in such <strong>Employee</strong>’s :manager column. To determine a :subordinate’s :manager (upon an @employee.manager call), Active Record may simply look at the :manager corresponding to the :manager_id stored in such <strong>Employee</strong>’s :manager column.</p><h4>Has_many | Has_many — Self Join Table</h4><p>The above :subordinates | :manager example is useful only if a :subordinate belongs_to a single :manager. A different data structure is required if a :subordinate may have more than one :manager. The :follower | :followee paradigm used by Twitter and Instagram is analogous. A <strong>User</strong> can follow and be followed by any number of :users. In other words, a <strong>User</strong> can be both a :subordinate (:followee) and a :manager (:follower) without any restrictions on the number of :managers (:followers) associated with it in its :subordinate (:followee) capacity and the number of :subordinates (:followees) associated with it in its :manager (:follower) capacity. Here’s how a has_many | has_many self-join might work:</p><p><a href="https://github.com/jbmilgrom/LEAf/blob/master/app/models/user.rb">app/models/user.rb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ae8lXxaCS6rwaJ6dV9BKaQ.png" /></figure><p><a href="https://github.com/jbmilgrom/LEAf/blob/master/app/models/follow.rb">app/models/follow.rb</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LFc2vG8Rk2PNgt3rjsM2eg.png" /></figure><p>The most important things to note are probably the terms :follower_follows and :followee_follows in user.rb, terms which I named as such for the following reasons (but could just as well been named :route_a and :route_b). Ordinarily, a join table between two independent objects is referenced identically in each model class. In the <strong>Player</strong> | <strong>Team</strong> example above, a <strong>Team</strong> may have many :players through :contracts. This is no different for a <strong>Player</strong>, who may have many :teams through :contracts as well. But in this case, where only one named model exists (i.e. a <strong>User</strong>), naming the through: relationship identically (i.e. through: :follow) would result in a naming collision for different use cases of, or access points into, the join table. Follower_follows and :followee_follows were created to avoid such a naming collision. Now, a <strong>User</strong> can have many :followers through :follower_follows and many :followees through :followee_follows.</p><p>To determine a <strong>User</strong>’s :followees (upon an @user.followees call), Active Record may now look at each instance of class_name: “Follow” where such <strong>User</strong> is the follower (i.e. foreign_key: :follower_id) through: such <strong>User</strong>’s :followee_follows. To determine a <strong>User</strong>’s :followers (upon an @user.followers call), Active Record may now look at each instance of class_name: “Follow” where such <strong>User </strong>is the followee (i.e. foreign_key: :followee_id) through: such <strong>User</strong>’s :follower_follows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0992c27c1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Months Ago I was a Lawyer]]></title>
            <link>https://medium.com/@jbmilgrom/two-months-ago-i-was-a-lawyer-d00c57d8bc5a?source=rss-1f399d61fc99------2</link>
            <guid isPermaLink="false">https://medium.com/p/d00c57d8bc5a</guid>
            <dc:creator><![CDATA[Jonathan Milgrom]]></dc:creator>
            <pubDate>Sun, 03 Aug 2014 19:56:57 GMT</pubDate>
            <atom:updated>2018-07-29T14:26:36.191Z</atom:updated>
            <content:encoded><![CDATA[<h2>Transitioning to Software Engineering</h2><p>I had a birthday this year despite disliking my job. Apparently, my daily fight against workflow did not slow down time. Practicing law is not a peculiar result for someone who went to law school, but nonetheless that’s what it felt like to me, and increasingly so, every week, month and year that passed.</p><p>In retrospect, the seed that ultimately grew into my career move was planted in college. When curiosity was my only motivator, I studied math and physics as part of an applied math major that required that I take an introduction to programming class in C++. I loved that class because it appeared to almost completely flesh out the core of what I enjoyed most about my major. To quote one of my new favorite authors:</p><blockquote>“Refactor, not because you know<em> </em>the abstraction, but because you want to find<em> </em>it.” — <a href="http://confreaks.com/videos/240-goruco2009-solid-object-oriented-design">Sandi Metz</a></blockquote><p>Remembering this, the gulf between what I was <em>doing </em>and what I wanted <em>to do </em>shrank every time I shed a reason for staying put.</p><p>Recently, I left corporate law and began a web development immersive, a 3 month intensive into computer science fundamentals, information architecture and web development. And now, a little over three months into a profession into which I look forward to investing my time and energy, I know I have a lot to learn. But I’m eager to share what I’m learning.</p><p>If you’re an experienced programmer, great. I hope I don’t reveal so many nautical miles between myself and the boat, that I’ve missed the boat completely. But I also would love to hear what you think. I’m more concerned with learning than anything. If any of my posts find you, please comment. For anyone else that might stumble upon this post or another, I hope that it is relatable in some way. Happy coding!</p><p>Quotes of the day:</p><blockquote>There are these two young fish swimming along and they happen to meet<br>an older fish swimming the other way, who nods at them and says<br>“Morning, boys. How’s the water?” And the two young fish swim on for a<br>bit, and then eventually one of them looks over at the other and goes<br>“What the hell is water?” — <a href="http://web.ics.purdue.edu/~drkelly/DFWKenyonAddress2005.pdf">David Foster Wallace</a></blockquote><blockquote>“Everything should be made as simple as possible, but not simpler.” — <a href="http://en.wikiquote.org/wiki/Albert_Einstein">I like to think this was Albert Einstein</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d00c57d8bc5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>