How Implementation Language Affects Design Patterns

Total Page:16

File Type:pdf, Size:1020Kb

How Implementation Language Affects Design Patterns How Implementation Language Affects Design Patterns A Comparison of Gang of Four Design Pattern Implementations in Different Languages Kristian Pedersen Thesis submitted for the degree of Master in Programming and Networks 30 credits Department of Informatics Faculty of mathematics and natural sciences UNIVERSITY OF OSLO Spring 2019 How Implementation Language Affects Design Patterns A Comparison of Gang of Four Design Pattern Implementations in Different Languages Kristian Pedersen © 2019 Kristian Pedersen How Implementation Language Affects Design Patterns http://www.duo.uio.no/ Printed: Reprosentralen, University of Oslo Abstract In the present work the impact of implementation language on code quality for implementations based on the Gang of Four design patterns is examined. These are used by many developers and system architects to improve their development process. The patterns Composite, Prototype, Adapter and Decorator are exam- ined in the context of the programming languages Python, JavaScript, C#, Go and Smalltalk. A case was designed and implemented in these lan- guages for each pattern and then analyzed based on a gauntlet of metrics. It was found that there were differences between the languages. Having mechanics solving problems similar to the problem the design pattern is solving was positive. In addition it was positive for a language to have flexible typing schemes, little overhead and attribute visibility control. No language was found to be clearly best suited, but individual strengths and weaknesses are discussed. i ii Contents I Introduction 1 1 Introduction 3 1.1 Motivation . .3 1.2 Scope and Problem Statement . .4 1.3 Goal . .4 1.4 Approach . .4 1.5 Evaluation . .5 1.6 Work Done . .5 1.7 Results . .6 1.8 Conclusion . .6 1.9 Thesis Outline . .7 II Theory 9 2 Background 11 2.1 Introduction . 11 2.2 Design Patterns Implementation . 11 2.2.1 Introduction . 11 2.2.2 Implementation Description . 11 2.2.3 Implementation Studies . 12 2.2.4 Implementation and Language . 12 2.3 Individual Papers . 13 2.3.1 Introduction . 13 2.3.2 GoHotDraw . 13 2.3.3 Empirical Study of Github . 13 2.3.4 On the Issue of Language Support . 14 III Method 15 3 Methodology 17 3.1 Introduction . 17 3.2 Setting . 17 3.3 Outline . 18 3.4 Metrics . 19 3.4.1 Introduction . 19 3.4.2 Metric Selection . 19 iii 3.4.3 Example . 20 3.4.4 Lines of code . 21 3.4.5 Cyclomatic complexity . 23 3.4.6 Object Oriented Measures . 24 3.4.7 Shallow References . 26 3.4.8 NCLOC aggregation . 27 3.4.9 Code as Data . 28 3.5 Validity . 29 3.5.1 Introduction . 29 3.5.2 Definition . 29 3.5.3 Need For Validity . 29 3.5.4 Design and Implementation Philosophy . 29 3.5.5 Well defined requirements . 30 3.5.6 Model Design . 30 3.5.7 Visibility Relaxation . 31 3.5.8 Order of implementation . 31 3.5.9 Agile selection of patterns . 31 3.5.10 Pseudocode . 32 3.5.11 Adapting Metrics to Go . 32 3.5.12 Further threats to validity . 33 4 Cases 35 4.1 Introduction . 35 4.2 Composite . 35 4.2.1 Pattern . 35 4.2.2 The case . 35 4.2.3 Usage example . 37 4.2.4 Choices . 37 4.2.5 Results . 38 4.2.6 Analysis . 38 4.2.7 Summary . 40 4.3 Prototype . 40 4.3.1 Pattern . 40 4.3.2 Case . 41 4.3.3 Choices . 41 4.3.4 Usage example . 42 4.3.5 Results . 42 4.3.6 Analysis . 43 4.4 Adapter . 45 4.4.1 Pattern . 45 4.4.2 Case . 45 4.4.3 Choices . 46 4.4.4 Usage example . 47 4.4.5 Results . 47 4.4.6 Analysis . 47 4.5 Decorator . 51 4.5.1 Pattern . 51 4.5.2 Case . 51 iv 4.5.3 Usage Example . 52 4.5.4 Modeling choices . 52 4.5.5 Results . 53 4.5.6 Analysis . 53 IV Discussion and Conclusion 57 5 Analysis 59 5.1 Introduction . 59 5.2 Aggregates . 59 5.2.1 Introduction . 59 5.2.2 Proportion of Case’s NCLOC . 60 5.2.3 Proportion of Language’s NCLOC . 60 5.2.4 Relative Size . 60 5.2.5 Relative Verbosity of Language . 61 5.2.6 Summary . 61 5.3 Cross case comparison . 61 5.3.1 Introduction . 61 5.3.2 NCLOC . 61 5.3.3 Cyclomatic complexity . 62 5.3.4 Tree Related Metrics . 62 5.3.5 Shallow References . 63 5.3.6 Summary . 63 5.4 Summary . 63 6 Discussion 65 6.1 Introduction . 65 6.2 Core Issues . 65 6.2.1 Introduction . 65 6.2.2 The Issues . 65 6.2.3 Relevance . 66 6.2.4 Validity . 67 6.2.5 Implications . 67 6.3 Languages . 68 6.3.1 Introduction . 68 6.3.2 Python . 68 6.3.3 JavaScript . 69 6.3.4 C# . 70 6.3.5 Go . 72 6.3.6 Smalltalk . 73 6.3.7 Comparison . 75 6.3.8 Generalization . 76 6.4 Metric Validity . 78 6.4.1 Introduction . 78 6.4.2 Lines of Code . 79 6.4.3 Cyclomatic Complexity . 79 6.4.4 Tree Metrics . 80 v 6.4.5 Loose Class Cohesion . 80 6.4.6 Shallow References . 81 6.4.7 Metric Coverage . 81 6.5 Comparing to Literature . 82 6.5.1 Introduction . 82 6.5.2 GoHotDraw . 82 6.5.3 Empirical Study of Github . 82 6.5.4 On the Issue of Language Support . 83 6.5.5 Conclusion . ..
Recommended publications
  • Acceptor-Connector an Object Creational Pattern for Connecting and Initializing Communication Services
    Acceptor-Connector An Object Creational Pattern for Connecting and Initializing Communication Services Douglas C. Schmidt [email protected] Department of Computer Science Washington University St. Louis, MO 63130, USA An earlier version of this paper appeared in a chapter in TRACKING the book Pattern Languages of Program Design 3, edited SATELLITES STATION by Robert Martin, Frank Buschmann, and Dirke Riehle pub- PEERS lished by Addison-Wesley, 1997. 1Intent STATUS INFO The Acceptor-Connector design pattern decouples connec- WIDE AREA NETWORK tion establishment and service initialization in a distributed COMMANDS BULK DATA system from the processing performed once a service is ini- TRANSFER tialized. This decoupling is achieved with three compo- nents: acceptors, connectors,andservice handlers. A con- GATEWAY nector actively establishes a connection with a remote ac- ceptor component and initializes a service handler to pro- cess data exchanged on the connection. Likewise, an ac- LOCAL AREA NETWORK ceptor passively waits for connection requests from remote GROUND connectors, establishing a connection upon arrival of such a STATION PEERS request, and initializing a service handler to process data ex- changed on the connection. The initialized service handlers Figure 1: The Physical Architecture of a Connection- then perform application-specific processing and communi- oriented Application-level Gateway cate via the connection established by the connector and ac- ceptor components. The Gateway transmits data between its Peers using the connection-oriented TCP/IP protocol [1]. In our exam- 2 Example ple network configuration, each service is bound to a con- nection endpoint designated by an IP host address and a TCP To illustrate the Acceptor-Connector pattern, consider the port number.
    [Show full text]
  • 1 More on Type Checking Type Checking Done at Compile Time Is
    More on Type Checking Type Checking done at compile time is said to be static type checking. Type Checking done at run time is said to be dynamic type checking. Dynamic type checking is usually performed immediately before the execution of a particular operation. Dynamic type checking is usually implemented by storing a type tag in each data object that indicates the data type of the object. Dynamic type checking languages include SNOBOL4, LISP, APL, PERL, Visual BASIC, Ruby, and Python. Dynamic type checking is more often used in interpreted languages, whereas static type checking is used in compiled languages. Static type checking languages include C, Java, ML, FORTRAN, PL/I and Haskell. Static and Dynamic Type Checking The choice between static and dynamic typing requires some trade-offs. Many programmers strongly favor one over the other; some to the point of considering languages following the disfavored system to be unusable or crippled. Static typing finds type errors reliably and at compile time. This should increase the reliability of delivered program. However, programmers disagree over how common type errors are, and thus what proportion of those bugs which are written would be caught by static typing. Static typing advocates believe programs are more reliable when they have been type-checked, while dynamic typing advocates point to distributed code that has proven reliable and to small bug databases. The value of static typing, then, presumably increases as the strength of the type system is inc reased. Advocates of languages such as ML and Haskell have suggested that almost all bugs can be considered type errors, if the types used in a program are sufficiently well declared by the programmer or inferred by the compiler.
    [Show full text]
  • Design and Performance of a Modular Portable Object Adapter for Distributed, Real-Time, and Embedded CORBA Applications
    Design and Performance of a Modular Portable Object Adapter for Distributed, Real-Time, and Embedded CORBA Applications Raymond Klefstad, Arvind S. Krishna, and Douglas C. Schmidt g fklefstad, krishnaa, schmidt @uci.edu Electrical and Computer Engineering Dept. University of California, Irvine, CA 92697, USA Abstract of distributed computing from application developers to mid- dleware developers. It has been used successfully in large- ZEN is a CORBA ORB designed to support distributed, real- scale business systems where scalability, evolvability, and in- time, and embedded (DRE) applications that have stringent teroperability are essential for success. memory constraints. This paper discusses the design and per- Real-time CORBA [5] is a rapidly maturing DOC middle- formance of ZENs portable object adapter (POA) which is ware technology standardized by the OMG that can simplify an important component in a CORBA object request broker many challenges for DRE applications, just as CORBA has (ORB). This paper makes the following three contributions for large-scale business systems. Real-time CORBA is de- to the study of middleware for memory-constrained DRE ap- signed for applications with hard real-time requirements, such plications. First, it presents three alternative designs of the as avionics mission computing [6]. It can also handle ap- CORBA POA. Second, it explains how design patterns can be plications with stringent soft real-time requirements, such as applied to improve the quality and performance of POA im- telecommunication call processing and streaming video [7]. plementations. Finally, it presents empirical measurements ZEN [8] is an open-source Real-time CORBA object re- based on the ZEN ORB showing how memory footprint can quest broker (ORB) implemented in Real-time Java [9].
    [Show full text]
  • Design Pattern Interview Questions
    DDEESSIIGGNN PPAATTTTEERRNN -- IINNTTEERRVVIIEEWW QQUUEESSTTIIOONNSS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright © tutorialspoint.com Dear readers, these Design Pattern Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Design Pattern. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: What are Design Patterns? Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. What is Gang of Four GOF? In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four GOF. Name types of Design Patterns? Design patterns can be classified in three categories: Creational, Structural and Behavioral patterns. Creational Patterns - These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case. Structural Patterns - These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
    [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]
  • Servant Documentation Release
    servant Documentation Release Servant Contributors February 09, 2018 Contents 1 Introduction 3 2 Tutorial 5 2.1 A web API as a type...........................................5 2.2 Serving an API.............................................. 10 2.3 Querying an API............................................. 28 2.4 Generating Javascript functions to query an API............................ 31 2.5 Custom function name builder...................................... 38 2.6 Documenting an API........................................... 38 2.7 Authentication in Servant........................................ 43 3 Cookbook 51 3.1 Structuring APIs............................................. 51 3.2 Serving web applications over HTTPS................................. 54 3.3 SQLite database............................................. 54 3.4 PostgreSQL connection pool....................................... 56 3.5 Using a custom monad.......................................... 58 3.6 Basic Authentication........................................... 60 3.7 Combining JWT-based authentication with basic access authentication................ 62 3.8 File Upload (multipart/form-data)............................... 65 4 Example Projects 69 5 Helpful Links 71 i ii servant Documentation, Release servant is a set of packages for declaring web APIs at the type-level and then using those API specifications to: • write servers (this part of servant can be considered a web framework), • obtain client functions (in haskell), • generate client functions for other programming
    [Show full text]
  • Learning Javascript Design Patterns
    Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani. All rights reserved. Revision History for the : 2012-05-01 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details. ISBN: 978-1-449-33181-8 1335906805 Table of Contents Preface ..................................................................... ix 1. Introduction ........................................................... 1 2. What is a Pattern? ...................................................... 3 We already use patterns everyday 4 3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three ...................... 7 4. The Structure Of A Design Pattern ......................................... 9 5. Writing Design Patterns ................................................. 11 6. Anti-Patterns ......................................................... 13 7. Categories Of Design Pattern ............................................ 15 Creational Design Patterns 15 Structural Design Patterns 16 Behavioral Design Patterns 16 8. Design Pattern Categorization ........................................... 17 A brief note on classes 17 9. JavaScript Design Patterns .............................................. 21 The Creational Pattern 22 The Constructor Pattern 23 Basic Constructors 23 Constructors With Prototypes 24 The Singleton Pattern 24 The Module Pattern 27 iii Modules 27 Object Literals 27 The Module Pattern
    [Show full text]
  • Concepts in Programming Languages Supervision 1 – 18/19 V1 Supervisor: Joe Isaacs (Josi2)
    Concepts in Programming Languages Supervision 1 { 18/19 v1 Supervisor: Joe Isaacs (josi2). All work should be submitted in PDF form 24 hours before the supervision to the email [email protected], ideally written in LATEX. If you have any questions on the course please include these at the top of the supervision work and we can talk about them in the supervision. Note: there is a revision guide http://www.cl.cam.ac.uk/teaching/1718/ConceptsPL/RG. pdf for this course. 1. What is the different between a static and dynamic typing. Give with justification which languages and static or dynamic. 2. What is the different between strong and weak typing. 3. What is type safety. How are type safety and type soundness distinct? 4. What type system does LISP have what are the basic types?, where have you seen a similar type system before. 5. What is a abstract machine, why are they useful? Where have you seen or used them before? 6. Name at least six different function calling schemes and which languages use each of them. 7. Give an overview of block-structured languages, include which ideas were first introduced in a programming language and how they influenced each other. Making sure to list the main characteristics of each language. You should talk about three distinct languages, then for each language make sure to make distinctions between different version of each language. Make a timeline using pen and paper or a diagram tool. 8. Using the type inference algorithm given in the notes (a typing checker with constraints) find the most general type for fn x ) fn y ) y x 9.
    [Show full text]
  • From Perl to Python
    From Perl to Python Fernando Pineda 140.636 Oct. 11, 2017 version 0.1 3. Strong/Weak Dynamic typing The notion of strong and weak typing is a little murky, but I will provide some examples that provide insight most. Strong vs Weak typing To be strongly typed means that the type of data that a variable can hold is fixed and cannot be changed. To be weakly typed means that a variable can hold different types of data, e.g. at one point in the code it might hold an int at another point in the code it might hold a float . Static vs Dynamic typing To be statically typed means that the type of a variable is determined at compile time . Type checking is done by the compiler prior to execution of any code. To be dynamically typed means that the type of variable is determined at run-time. Type checking (if there is any) is done when the statement is executed. C is a strongly and statically language. float x; int y; # you can define your own types with the typedef statement typedef mytype int; mytype z; typedef struct Books { int book_id; char book_name[256] } Perl is a weakly and dynamically typed language. The type of a variable is set when it's value is first set Type checking is performed at run-time. Here is an example from stackoverflow.com that shows how the type of a variable is set to 'integer' at run-time (hence dynamically typed). $value is subsequently cast back and forth between string and a numeric types (hence weakly typed).
    [Show full text]
  • Principles of Programming Languages
    David Liu Principles of Programming Languages Lecture Notes for CSC324 (Version 2.1) Department of Computer Science University of Toronto principles of programming languages 3 Many thanks to Alexander Biggs, Peter Chen, Rohan Das, Ozan Erdem, Itai David Hass, Hengwei Guo, Kasra Kyanzadeh, Jasmin Lantos, Jason Mai, Sina Rezaeizadeh, Ian Stewart-Binks, Ivan Topolcic, Anthony Vandikas, Lisa Zhang, and many anonymous students for their helpful comments and error-spotting in earlier versions of these notes. Dan Zingaro made substantial contributions to this version of the notes. Contents Prelude: The Study of Programming Languages 7 Programs and programming languages 7 Models of computation 11 A paradigm shift in you 14 Course overview 15 1 Functional Programming: Theory and Practice 17 The baseline: “universal” built-ins 18 Function expressions 18 Function application 19 Function purity 21 Name bindings 22 Lists and structural recursion 26 Pattern-matching 28 Higher-order functions 35 Programming with abstract syntax trees 42 Undefined programs and evaluation order 44 Lexical closures 50 Summary 56 6 david liu 2 Macros, Objects, and Backtracking 57 Object-oriented programming: a re-introduction 58 Pattern-based macros 61 Objects revisited 74 The problem of self 78 Manipulating control flow I: streams 83 Manipulating control flow II: the ambiguous operator -< 87 Continuations 90 Using continuations in -< 93 Using choices as subexpressions 94 Branching choices 98 Towards declarative programming 101 3 Type systems 109 Describing type systems 110
    [Show full text]
  • Concurrency Patterns for Easier Robotic Coordination
    Concurrency Patterns for Easier Robotic Coordination Andrey Rusakov∗ Jiwon Shin∗ Bertrand Meyer∗† ∗Chair of Software Engineering, Department of Computer Science, ETH Zurich,¨ Switzerland †Software Engineering Lab, Innopolis University, Kazan, Russia fandrey.rusakov, jiwon.shin, [email protected] Abstract— Software design patterns are reusable solutions to Guarded suspension – are chosen for their concurrent nature, commonly occurring problems in software development. Grow- applicability to robotic coordination, and evidence of use ing complexity of robotics software increases the importance of in existing robotics frameworks. The paper aims to help applying proper software engineering principles and methods such as design patterns to robotics. Concurrency design patterns programmers who are not yet experts in concurrency to are particularly interesting to robotics because robots often have identify and then to apply one of the common concurrency- many components that can operate in parallel. However, there based solutions for their applications on robotic coordination. has not yet been any established set of reusable concurrency The rest of the paper is organized as follows: After design patterns for robotics. For this purpose, we choose six presenting related work in Section II, it proceeds with a known concurrency patterns – Future, Periodic timer, Invoke later, Active object, Cooperative cancellation, and Guarded sus- general description of concurrency approach for robotics pension. We demonstrate how these patterns could be used for in Section III. Then the paper presents and describes in solving common robotic coordination tasks. We also discuss detail a number of concurrency patterns related to robotic advantages and disadvantages of the patterns and how existing coordination in Section IV.
    [Show full text]
  • Servant Documentation Release
    servant Documentation Release Servant Contributors March 07, 2016 Contents 1 Introduction 3 2 Tutorial 5 2.1 A web API as a type...........................................5 2.2 Serving an API..............................................9 2.3 Querying an API............................................. 25 2.4 Generating Javascript functions to query an API............................ 28 2.5 Documenting an API........................................... 30 3 Helpful Links 35 i ii servant Documentation, Release servant is a set of packages for declaring web APIs at the type-level and then using those API specifications to: • write servers (this part of servant can be considered a web framework), • obtain client functions (in haskell), • generate client functions for other programming languages, • generate documentation for your web applications • and more... All in a type-safe manner. Contents 1 servant Documentation, Release 2 Contents CHAPTER 1 Introduction servant has the following guiding principles: • concision This is a pretty wide-ranging principle. You should be able to get nice documentation for your web servers, and client libraries, without repeating yourself. You should not have to manually serialize and deserialize your resources, but only declare how to do those things once per type. If a bunch of your handlers take the same query parameters, you shouldn’t have to repeat that logic for each handler, but instead just “apply” it to all of them at once. Your handlers shouldn’t be where composition goes to die. And so on. • flexibility If we haven’t thought of your use case, it should still be easily achievable. If you want to use templating library X, go ahead. Forms? Do them however you want, but without difficulty.
    [Show full text]