Composing Software an Exploration of Functional Programming and Object Composition in Javascript

Total Page:16

File Type:pdf, Size:1020Kb

Composing Software an Exploration of Functional Programming and Object Composition in Javascript Composing Software An Exploration of Functional Programming and Object Composition in JavaScript Eric Elliott This book is for sale at http://leanpub.com/composingsoftware This version was published on 2019-02-24 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2017 - 2019 Eric Elliott Contents Thank You ................................................... 1 Composing Software: An Introduction ................................. 2 You Compose Software Every Day .................................. 3 Conclusion ................................................. 10 The Dao of Immutability (The Way of the Functional Programmer) .............. 11 Forward .................................................. 11 The Rise and Fall and Rise of Functional Programming (Composable Software) ....... 13 The Rise of Functional Programming ................................. 13 The Fall of Functional Programming ................................. 16 The Rise of Functional Programming ................................. 16 Functional Programming Has Always Been Alive and Well ................... 17 Why Learn Functional Programming in JavaScript? ........................ 18 Pure Functions ................................................ 25 What is a Function? ........................................... 25 Mapping .................................................. 25 Pure Functions .............................................. 26 The Trouble with Shared State ..................................... 27 Same Input, Same Output ........................................ 28 No Side Effects .............................................. 29 Conclusion ................................................. 32 What is Functional Programming? .................................... 33 Pure Functions .............................................. 34 Function Composition .......................................... 34 Shared State ................................................ 34 Immutability ............................................... 37 Side Effects ................................................ 38 Reusability Through Higher Order Functions ............................ 38 Containers, Functors, Lists, and Streams ............................... 39 Declarative vs Imperative ........................................ 40 CONTENTS Conclusion ................................................. 41 A Functional Programmer’s Introduction to JavaScript ...................... 43 Expressions and Values ......................................... 43 Types .................................................... 44 Destructuring ............................................... 45 Comparisons and Ternaries ....................................... 46 Functions .................................................. 47 Currying .................................................. 51 Function Composition .......................................... 53 Arrays ................................................... 54 Method Chaining ............................................. 54 Conclusion ................................................. 55 Higher Order Functions ........................................... 56 Curry and Function Composition .................................... 59 What is a curried function? ....................................... 59 What is a partial application? ..................................... 60 What’s the Difference? ......................................... 60 What is point-free style? ........................................ 60 Why do we curry? ............................................ 61 Trace .................................................... 63 Curry and Function Composition, Together ............................. 64 Conclusion ................................................. 69 Abstraction & Composition ........................................ 71 Abstraction is simplification. ...................................... 72 Abstraction in Software ......................................... 72 Abstraction through composition ................................... 73 How to Do More with Less Code ................................... 74 Conclusion ................................................. 75 Reduce ................................................... 75 Reduce is Versatile ............................................ 76 Conclusion ................................................. 80 Functors & Categories ............................................ 81 Why Functors? .............................................. 82 Functor Laws ............................................... 86 Category Theory ............................................. 87 Build Your Own Functor ........................................ 89 Curried Map ................................................ 90 Conclusion ................................................. 91 CONTENTS Monads ..................................................... 92 You’re probably already using monads. ............................... 94 What Monads are Made of ....................................... 99 Building a Kleisli Composition Function ...............................102 The Monad Laws .............................................105 Conclusion .................................................109 The Forgotten History of OOP ...................................... 110 The Big Idea ................................................111 The Essence of OOP ...........................................113 What OOP Doesn’t Mean ........................................114 What is an object? ............................................116 We’ve lost the plot. ............................................117 Object Composition ............................................. 119 What is Object Composition? .....................................120 Three Different Forms of Object Composition . 121 Notes on Code Examples ........................................121 Aggregation ................................................122 Concatenation ...............................................124 Delegation .................................................125 Conclusion .................................................127 Factory Functions ............................................... 129 Literals for One, Factories for Many .................................130 Returning Objects ............................................131 Destructuring ...............................................131 Computed Property Keys ........................................132 Default Parameters ............................................133 Type Inference ..............................................134 Factory Functions for Mixin Composition ..............................136 Conclusion .................................................138 Functional Mixins .............................................. 140 Motivation .................................................140 What are mixins? .............................................141 What is functional inheritance? ....................................142 What is a functional mixin? ......................................143 Composing Functional Mixins .....................................144 When to Use Functional Mixins ....................................145 Caveats ...................................................145 Conclusion .................................................150 Why Composition is Harder with Classes ............................... 151 CONTENTS The Delegate Prototype .........................................151 The .constructor Property .......................................153 Class to Factory is a Breaking Change ................................156 Composable Custom Data Types ..................................... 162 You can do this with any data type ..................................165 Composable Currency ..........................................165 Lenses ...................................................... 167 Why Lenses? ...............................................168 Background ................................................168 Lens Laws .................................................169 Composing Lenses ............................................171 Transducers .................................................. 174 Why Transducers? ............................................175 Background and Etymology ......................................177 A Musical Analogy for Transducers .................................179 Transducers compose top-to-bottom. .................................185 Transducer Rules .............................................185 Transducing ................................................187 The Transducer Protocol ........................................189 Conclusion .................................................190 Elements of JavaScript Style ........................................ 192 1. Make the function the unit of composition. One job for each function. 192 2. Omit needless code. ..........................................193 3. Use active voice. ............................................197 4. Avoid a succession of loose statements. ..............................198 5. Keep related code together. .....................................200 6. Put statements and expressions in positive form. 200 7. Use parallel
Recommended publications
  • Retrocomputing As Preservation and Remix
    Retrocomputing as Preservation and Remix Yuri Takhteyev Quinn DuPont University of Toronto University of Toronto [email protected] [email protected] Abstract This paper looks at the world of retrocomputing, a constellation of largely non-professional practices involving old computing technology. Retrocomputing includes many activities that can be seen as constituting “preservation.” At the same time, it is often transformative, producing assemblages that “remix” fragments from the past with newer elements or joining together historic components that were never combined before. While such “remix” may seem to undermine preservation, it allows for fragments of computing history to be reintegrated into a living, ongoing practice, contributing to preservation in a broader sense. The seemingly unorganized nature of retrocomputing assemblages also provides space for alternative “situated knowledges” and histories of computing, which can sometimes be quite sophisticated. Recognizing such alternative epistemologies paves the way for alternative approaches to preservation. Keywords: retrocomputing, software preservation, remix Recovering #popsource In late March of 2012 Jordan Mechner received a shipment from his father, a box full of old floppies. Among them was a 3.5 inch disk labelled: “Prince of Persia / Source Code (Apple) / ©1989 Jordan Mechner (Original).” Mechner’s announcement of this find on his blog the next day took the world of nerds by storm.1 Prince of Persia, a game that Mechner single-handedly developed in the late 1980s, revolutionized computer games when it came out due to its surprisingly realistic representation of human movement. After being ported to DOS and Apple’s Mac OS in the early 1990s the game sold 2 million copies (Pham, 2001).
    [Show full text]
  • Functional Javascript
    www.it-ebooks.info www.it-ebooks.info Functional JavaScript Michael Fogus www.it-ebooks.info Functional JavaScript by Michael Fogus Copyright © 2013 Michael Fogus. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editor: Mary Treseler Indexer: Judith McConville Production Editor: Melanie Yarbrough Cover Designer: Karen Montgomery Copyeditor: Jasmine Kwityn Interior Designer: David Futato Proofreader: Jilly Gagnon Illustrator: Robert Romano May 2013: First Edition Revision History for the First Edition: 2013-05-24: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449360726 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Functional JavaScript, the image of an eider duck, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
    [Show full text]
  • The Past, Present, and Future of Software Evolution
    The Past, Present, and Future of Software Evolution Michael W. Godfrey Daniel M. German Software Architecture Group (SWAG) Software Engineering Group School of Computer Science Department of Computer Science University of Waterloo, CANADA University of Victoria, CANADA email: [email protected] email: [email protected] Abstract How does our system compare to that of our competitors? How easy would it be to port to MacOS? Are users still Change is an essential characteristic of software devel- angry about the spyware incident? As new features are de- opment, as software systems must respond to evolving re- vised and deployed, as new runtime platforms are envis- quirements, platforms, and other environmental pressures. aged, as new constraints on quality attributes are requested, In this paper, we discuss the concept of software evolu- so must software systems continually be adapted to their tion from several perspectives. We examine how it relates changing environment. to and differs from software maintenance. We discuss in- This paper explores the notion of software evolution. We sights about software evolution arising from Lehman’s laws start by comparing software evolution to the related idea of software evolution and the staged lifecycle model of Ben- of software maintenance and briefly explore the history of nett and Rajlich. We compare software evolution to other both terms. We discuss two well known research results of kinds of evolution, from science and social sciences, and we software evolution: Lehman’s laws of software evolution examine the forces that shape change. Finally, we discuss and the staged lifecycle model of Bennett and Rajlich. We the changing nature of software in general as it relates to also relate software evolution to biological evolution, and evolution, and we propose open challenges and future di- discuss their commonalities and differences.
    [Show full text]
  • A Brief History of Software Engineering Niklaus Wirth ([email protected]) (25.2.2008)
    1 A Brief History of Software Engineering Niklaus Wirth ([email protected]) (25.2.2008) Abstract We present a personal perspective of the Art of Programming. We start with its state around 1960 and follow its development to the present day. The term Software Engineering became known after a conference in 1968, when the difficulties and pitfalls of designing complex systems were frankly discussed. A search for solutions began. It concentrated on better methodologies and tools. The most prominent were programming languages reflecting the procedural, modular, and then object-oriented styles. Software engineering is intimately tied to their emergence and improvement. Also of significance were efforts of systematizing, even automating program documentation and testing. Ultimately, analytic verification and correctness proofs were supposed to replace testing. More recently, the rapid growth of computing power made it possible to apply computing to ever more complicated tasks. This trend dramatically increased the demands on software engineers. Programs and systems became complex and almost impossible to fully understand. The sinking cost and the abundance of computing resources inevitably reduced the care for good design. Quality seemed extravagant, a loser in the race for profit. But we should be concerned about the resulting deterioration in quality. Our limitations are no longer given by slow hardware, but by our own intellectual capability. From experience we know that most programs could be significantly improved, made more reliable, economical and comfortable to use. The 1960s and the Origin of Software Engineering It is unfortunate that people dealing with computers often have little interest in the history of their subject.
    [Show full text]
  • The Power of Interoperability: Why Objects Are Inevitable
    The Power of Interoperability: Why Objects Are Inevitable Jonathan Aldrich Carnegie Mellon University Pittsburgh, PA, USA [email protected] Abstract 1. Introduction Three years ago in this venue, Cook argued that in Object-oriented programming has been highly suc- their essence, objects are what Reynolds called proce- cessful in practice, and has arguably become the dom- dural data structures. His observation raises a natural inant programming paradigm for writing applications question: if procedural data structures are the essence software in industry. This success can be documented of objects, has this contributed to the empirical success in many ways. For example, of the top ten program- of objects, and if so, how? ming languages at the LangPop.com index, six are pri- This essay attempts to answer that question. After marily object-oriented, and an additional two (PHP reviewing Cook’s definition, I propose the term ser- and Perl) have object-oriented features.1 The equiva- vice abstractions to capture the essential nature of ob- lent numbers for the top ten languages in the TIOBE in- jects. This terminology emphasizes, following Kay, that dex are six and three.2 SourceForge’s most popular lan- objects are not primarily about representing and ma- guages are Java and C++;3 GitHub’s are JavaScript and nipulating data, but are more about providing ser- Ruby.4 Furthermore, objects’ influence is not limited vices in support of higher-level goals. Using examples to object-oriented languages; Cook [8] argues that Mi- taken from object-oriented frameworks, I illustrate the crosoft’s Component Object Model (COM), which has unique design leverage that service abstractions pro- a C language interface, is “one of the most pure object- vide: the ability to define abstractions that can be ex- oriented programming models yet defined.” Academ- tended, and whose extensions are interoperable in a ically, object-oriented programming is a primary focus first-class way.
    [Show full text]
  • The Principles of Object-Oriented Javascript Zakas
    TAKETAKE CONTROLCONTROL OFOF Foreword by Cody Lindley, Best-selling Author and Principal Frontend Architect JAVASCRIPT THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT JAVASCRIPT THE PRINCIPLES OF OBJECT-ORIENTED JAVASCRIPT THETHE PRINCIPLESPRINCIPLES OFOF OBJECTSOBJECTS at TandemSeven OBJECT-ORIENTEDOBJECT-ORIENTED If you’ve used a more traditional object-oriented • How to define your own constructors JAVASCRIPTJAVASCRIPT language, such as C++ or Java, JavaScript probably • How to work with and understand prototypes doesn’t seem object-oriented at all. It has no concept of classes, and you don’t even need to define any • Inheritance patterns for types and objects objects in order to write code. But don’t be fooled — The Principles of Object-Oriented JavaScript will leave NICHOLAS C. ZAKAS JavaScript is an incredibly powerful and expressive even experienced developers with a deeper understand- object-oriented language that puts many design ing of JavaScript. Unlock the secrets behind how objects decisions right into your hands. work in JavaScript so you can write clearer, more In The Principles of Object-Oriented JavaScript, flexible, and more efficient code. Nicholas C. Zakas thoroughly explores JavaScript’s object-oriented nature, revealing the language’s A B O U T T H E A U T H O R unique implementation of inheritance and other key characteristics. You’ll learn: Nicholas C. Zakas is a software engineer at Box and is known for writing on and speaking about the latest • The difference between primitive and reference in JavaScript best practices. He honed his experience values during his five years at Yahoo!, where he was principal • What makes JavaScript functions so unique frontend engineer for the Yahoo! home page.
    [Show full text]
  • The History of Computing in the History of Technology
    The History of Computing in the History of Technology Michael S. Mahoney Program in History of Science Princeton University, Princeton, NJ (Annals of the History of Computing 10(1988), 113-125) After surveying the current state of the literature in the history of computing, this paper discusses some of the major issues addressed by recent work in the history of technology. It suggests aspects of the development of computing which are pertinent to those issues and hence for which that recent work could provide models of historical analysis. As a new scientific technology with unique features, computing in turn can provide new perspectives on the history of technology. Introduction record-keeping by a new industry of data processing. As a primary vehicle of Since World War II 'information' has emerged communication over both space and t ime, it as a fundamental scientific and technological has come to form the core of modern concept applied to phenomena ranging from information technolo gy. What the black holes to DNA, from the organization of English-speaking world refers to as "computer cells to the processes of human thought, and science" is known to the rest of western from the management of corporations to the Europe as informatique (or Informatik or allocation of global resources. In addition to informatica). Much of the concern over reshaping established disciplines, it has information as a commodity and as a natural stimulated the formation of a panoply of new resource derives from the computer and from subjects and areas of inquiry concerned with computer-based communications technolo gy.
    [Show full text]
  • Evolution and Composition of Object-Oriented Frameworks
    Evolution and Composition of Object-Oriented Frameworks Michael Mattsson University of Karlskrona/Ronneby Department of Software Engineering and Computer Science ISBN 91-628-3856-3 © Michael Mattsson, 2000 Cover background: Digital imagery® copyright 1999 PhotoDisc, Inc. Printed in Sweden Kaserntryckeriet AB Karlskrona, 2000 To Nisse, my father-in-law - who never had the opportunity to study as much as he would have liked to This thesis is submitted to the Faculty of Technology, University of Karlskrona/Ronneby, in partial fulfillment of the requirements for the degree of Doctor of Philosophy in Engineering. Contact Information: Michael Mattsson Department of Software Engineering and Computer Science University of Karlskrona/Ronneby Soft Center SE-372 25 RONNEBY SWEDEN Tel.: +46 457 38 50 00 Fax.: +46 457 27 125 Email: [email protected] URL: http://www.ipd.hk-r.se/rise Abstract This thesis comprises studies of evolution and composition of object-oriented frameworks, a certain kind of reusable asset. An object-oriented framework is a set of classes that embodies an abstract design for solutions to a family of related prob- lems. The work presented is based on and has its origin in industrial contexts where object-oriented frameworks have been developed, used, evolved and managed. Thus, the results are based on empirical observations. Both qualitative and quanti- tative approaches have been used in the studies performed which cover both tech- nical and managerial aspects of object-oriented framework technology. Historically, object-oriented frameworks are large monolithic assets which require several design iterations and are therefore costly to develop. With the requirement of building larger applications, software engineers have started to compose multiple frameworks, thereby encountering a number of problems.
    [Show full text]
  • An Overview of Software Evolution
    An Overview of Software Evolution CPRE 416-Software Evolution and Maintenance-Lecture 2 1 Software Evolution • What is it? • How important is it? • What to do about it? 2 An early history of software engineering • The following slides provide a condensation of the ideas of Robert L. Glass in his book "In the Beginning: Recollections of Software Pioneers" about the history of software engineering. 3 The Pioneering Era (1955-1965) • New computers were coming out every year or two. • Programmers did not have computers on their desks and had to go to the "machine room". • Jobs were run by signing up for machine time. Punch cards were used. • Computer hardware was application-specific. Scientific and business tasks needed different machines. 4 The Pioneering Era (1955-1965) • High-level languages like FORTRAN, COBOL, and ALGOL were developed. • No software companies were selling packaged software. • Academia did not yet teach the principles of computer science. 5 The Stabilizing Era (1965-1980) • Came the IBM 360. • This was the largest software project to date. • The 360 also combined scientific and business applications onto one machine. 6 The Stabilizing Era (1965-1980) • Programmers had to use the job control language (JCL) to tell OS what to do. • PL/I, introduced by IBM to merge all programming languages into one, failed. • The notion of timesharing emerged. • Software became a corporate asset and its value became huge. • Academic computing started in the late 60's. • Software engineering discipline did not yet exist. 7 The Stabilizing Era (1965-1980) • High-hype disciplines like Artificial Intelligence emerged.. • Structured Programming burst on the scene.
    [Show full text]
  • Obstacl: a Language with Objects, Subtyping, and Classes
    OBSTACL: A LANGUAGE WITH OBJECTS, SUBTYPING, AND CLASSES A DISSERTATION SUBMITTED TO THE DEPARTMENT OF COMPUTER SCIENCE AND THE COMMITTEE ON GRADUATE STUDIES OF STANFORD UNIVERSITY IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE DEGREE OF DOCTOR OF PHILOSOPHY By Amit Jayant Patel December 2001 c Copyright 2002 by Amit Jayant Patel All Rights Reserved ii I certify that I have read this dissertation and that in my opin- ion it is fully adequate, in scope and quality, as a dissertation for the degree of Doctor of Philosophy. John Mitchell (Principal Adviser) I certify that I have read this dissertation and that in my opin- ion it is fully adequate, in scope and quality, as a dissertation for the degree of Doctor of Philosophy. Kathleen Fisher I certify that I have read this dissertation and that in my opin- ion it is fully adequate, in scope and quality, as a dissertation for the degree of Doctor of Philosophy. David Dill Approved for the University Committee on Graduate Studies: iii Abstract Widely used object-oriented programming languages such as C++ and Java support soft- ware engineering practices but do not have a clean theoretical foundation. On the other hand, most research languages with well-developed foundations are not designed to support software engineering practices. This thesis bridges the gap by presenting OBSTACL, an object-oriented extension of ML with a sound theoretical basis and features that lend themselves to efficient implementation. OBSTACL supports modular programming techniques with objects, classes, structural subtyping, and a modular object construction system. OBSTACL's parameterized inheritance mechanism can be used to express both single inheritance and most common uses of multiple inheritance.
    [Show full text]
  • The History of Unix in the History of Software Haigh Thomas
    The History of Unix in the History of Software Haigh Thomas To cite this version: Haigh Thomas. The History of Unix in the History of Software. Cahiers d’histoire du Cnam, Cnam, 2017, La recherche sur les systèmes : des pivots dans l’histoire de l’informatique – II/II, 7-8 (7-8), pp77-90. hal-03027081 HAL Id: hal-03027081 https://hal.archives-ouvertes.fr/hal-03027081 Submitted on 9 Dec 2020 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. 77 The History of Unix in the History of Software Thomas Haigh University of Wisconsin - Milwaukee & Siegen University. You might wonder what I am doing The “software crisis” and here, at an event on this history of Unix. the 1968 NATO Conference As I have not researched or written about on Software Engineering the history of Unix I had the same question myself. But I have looked at many other The topic of the “software crisis” things around the history of software and has been written about a lot by profes- this morning will be talking about how sional historians, more than anything some of those topics, including the 1968 else in the entire history of software2.
    [Show full text]
  • Combinatorial Species and Labelled Structures Brent Yorgey University of Pennsylvania, [email protected]
    University of Pennsylvania ScholarlyCommons Publicly Accessible Penn Dissertations 1-1-2014 Combinatorial Species and Labelled Structures Brent Yorgey University of Pennsylvania, [email protected] Follow this and additional works at: http://repository.upenn.edu/edissertations Part of the Computer Sciences Commons, and the Mathematics Commons Recommended Citation Yorgey, Brent, "Combinatorial Species and Labelled Structures" (2014). Publicly Accessible Penn Dissertations. 1512. http://repository.upenn.edu/edissertations/1512 This paper is posted at ScholarlyCommons. http://repository.upenn.edu/edissertations/1512 For more information, please contact [email protected]. Combinatorial Species and Labelled Structures Abstract The theory of combinatorial species was developed in the 1980s as part of the mathematical subfield of enumerative combinatorics, unifying and putting on a firmer theoretical basis a collection of techniques centered around generating functions. The theory of algebraic data types was developed, around the same time, in functional programming languages such as Hope and Miranda, and is still used today in languages such as Haskell, the ML family, and Scala. Despite their disparate origins, the two theories have striking similarities. In particular, both constitute algebraic frameworks in which to construct structures of interest. Though the similarity has not gone unnoticed, a link between combinatorial species and algebraic data types has never been systematically explored. This dissertation lays the theoretical groundwork for a precise—and, hopefully, useful—bridge bewteen the two theories. One of the key contributions is to port the theory of species from a classical, untyped set theory to a constructive type theory. This porting process is nontrivial, and involves fundamental issues related to equality and finiteness; the recently developed homotopy type theory is put to good use formalizing these issues in a satisfactory way.
    [Show full text]