Specialization Patterns, Which Describ E How to Apply Program Sp Ecialization to Optimize Uses

Total Page:16

File Type:pdf, Size:1020Kb

Specialization Patterns, Which Describ E How to Apply Program Sp Ecialization to Optimize Uses INSTITUT NATIONAL DE RECHERCHE EN INFORMATIQUE ET EN AUTOMATIQUE Specialization Patterns Ulrik Pagh Schultz, Julia L. Lawall, and Charles Consel N˚3853 Janvier 1999 THÈME 2 apport de recherche ISSN 0249-6399 ISRN INRIA/RR--3853--FR+ENG Sp ecialization Patterns Ulrik Pagh Schultz, Julia L. Lawall, and Charles Consel Thème 2 Génie logiciel et calcul symb olique Pro jet COMPOSE Rapp ort de recherche n3853 Janvier 1999 28 pages Abstract: Design patterns oer numerous advantages for software development, but can intro duce ineciency into the nished program. Program sp ecialization can eliminate such overheads, but is most eective when targeted by the user to sp ecic b ottlenecks. Con- sequently, we prop ose to consider program sp ecialization and design patterns as comple- mentary concepts. On the one hand, program sp ecialization can optimize ob ject-oriented programs written using design patterns. On the other hand, design patterns provide infor- mation ab out the program structure that can guide sp ecialization. Concretely,we prop ose specialization patterns, which describ e how to apply program sp ecialization to optimize uses of design patterns. In this pap er, we analyze the sp ecialization opp ortunities provided by sp ecic uses of design patterns. Based on the analysis of each design pattern, we dene the asso ciated sp ecialization pattern. These sp ecialization opp ortunities can b e declared straightforwardly using the sp ecialization classes framework, develop ed in earlier work. Our exp eriments show that such sp ecialization leads to signicant p erformance improvements. Key-words: design patterns, program sp ecialization, ob ject-oriented programming, Java, optimization Résumé : tsvp Supp orted in part by BULL, and in part by Alcatel under the Reutel 2000 contract. Unité de recherche INRIA Rennes IRISA, Campus universitaire de Beaulieu, 35042 RENNES Cedex (France) Téléphone : 02 99 84 71 00 - International : +33 2 99 84 71 00 Télécopie : 02 99 84 71 71 - International : +33 2 99 84 71 71 Schémas de sp écialisation Résumé : Les schémas de conception sont reconnus p our faciliter le développ ement de programmes à ob jets. Cep endant, ils intro duisent souvent une certaine inecacité au sein du logiciel nal. La sp écialisation de programmes est une technique particulièrement adaptée à l'optimisation des programmes à ob jets. Toutefois, l'utilisation ecace de la sp écialisation sur des logiciels de grande taille requiert une connaissance détaillée des goulots d'étranglement de la part du programmeur. Dans cet article, nous prop osons d'asso cier sp écialisation de programmes et schémas de conception. Notre prop os est double. D'une part, la sp écialisation p ermet de supprimer les inecacités intro duites par les schémas de conception. D'autre part, les schémas de concep- tion fournissent des informations sur la structure du programme qui p ermettent de guider le pro cessus de sp écialisation. Plus précisément, nous intro duisons la notion de schémas de spécialisation an de mémoriser comment la sp écialisation de programmes p eut optimiser l'utilisation d'un schéma de conception. Nous démontrons l'applicabilité des schémas de sp écialisation, en caractérisant les opp ortunités de sp écialisation présentes dans plusieurs schémas de conception. Nous intro duisons notre appro che en présentant des exemples de programmes sp écialisés automatiquementaumoyen des schémas de sp écialisation. Mots-clé : schémas de conception, sp écialization de programmes, programmation orientée ob ject, Java, optimisation Specialization Patterns 3 1 Intro duction Design patterns, as presented by Gamma et al. [16], describ e well-tested program structures that enhance mo dularity and co de reuse. A program written using design patterns is struc- tured into indep endent units that interact through generic interfaces, and that evolveover time in resp onse to changing conditions. Because design patterns are well-do cumented, their use simplies the understanding of programs constructed from many indep endent units. The exibility inherent in this use of generic interfaces, however, intrinsically blo cks optimiza- tion across ob jects, and thus can carry a signicant p erformance p enalty. This issue remains largely unaddressed in the design pattern community. Many applications do not fully exploit the exibility oered by design patterns. For a simple example, consider a typical use of the iterator design pattern [16], which sepa- rates traversal of a data structure from its representation. Using the iterator pattern, an implementation of a Set data structure might dene the member metho d as follows: public class Set { MinimalCollection coll; // underlying collection public boolean member Object o { Iterator e = coll.iterator; // obtain iterator while e.hasNext { // while iterator has elements Object x = e.next ; // obtain next iterator element if x.equals o return true; } return false; } ... } This denition of the member metho d can b e used with any underlying MinimalCollection implementation, letting the programmer freely cho ose the most appropriate concrete rep- resentation for the task at hand. Nevertheless, our exp eriments show that the use of the iterator pattern blo cks compiler optimization of the element retrieval op erations. When the member metho d is used rep eatedly to search MinimalCollection ob jects that have the same representation, the exibility provided by accessing the data through an abstract interface is not needed. In this case, the member metho d can b e optimized, by replacing the generic uses of the iterator pattern underlined in the metho d denition by direct accesses to the 1 underlying data structure. This transformation gives a sp eedup ranging from 20 to 80. These measurements suggest that the optimizations p erformed by state-of-the-art compilers do not completely comp ensate for the genericityintro duced by design patterns. When the data representation is invariantover a p erio d of time, sp ecializing the program to this representation b efore execution improves eciency. However, manual sp ecialization is error-prone, and intro duces excessive program-maintenance overhead. Recently, automatic program sp ecialization has b een shown to be eective in the context of ob ject-oriented 1 Exp eriments done with JDK 1.2.1 JIT and HotSp ot compilers on SPARC architecture, with array and linked list representations of the underlying MinimalCollection data structure. RR n3853 4 Ulrik Pagh Schultz, Julia L. Lawal l, and Charles Consel languages, sp ecically Java [22,28]. Automatic program sp ecialization systematically elimi- nates b oth algorithmic and structural overheads, and consequently can signicantly improve p erformance. For example, program sp ecialization has b een shown to b e eective for elimi- nating overheads intro duced by software architectures [24]. Nevertheless, sp ecialization is not always b enecial; for example sp ecializing with resp ect to to o many dierent representations can cause co de explosion. Therefore, the user must explicitly target the sp ecializer toward particular invariants and regions of co de. The spe- cialization classes framework prop osed byVolanschi et al. [32] provides a simple and declar- ative notation for expressing such sp ecialization opp ortunities. Nevertheless, the problem of identifying sp ecialization opp ortunities remains. Proling can help, however, it may not reveal systematic structural overheads that blo ck optimization throughout the program. A systematic approach taking into account the program design is needed. This pap er We observe that the use of design patterns in a program gives rise to patterns of structural prop erties, which in turn give rise to patterns of overheads. These patterns of overheads form patterns of opp ortunities for sp ecialization. We prop ose the use of specialization patterns as a complement to design patterns, to describ e when, how, and why a program structured using design patterns can b enet from sp ecialization. This approach retains the program structuring advantages of design patterns, while relying on an automated transformation to map generic co de into an ecient implementation. The contributions of this pap er are as follows: We address the muchoverlo oked problem of p erformance of programs written using design patterns, by analyzing the overheads systematically intro duced by the use of design patterns. We describ e how to systematically apply program sp ecialization to eliminate these overheads, automatically mapping well-structured generic implementations into mono- lithic ecient ones. We dene sp ecialization patterns for three well-known design patterns: the builder pattern, the bridge pattern, and the strategy pattern. We provide several examples of how sp ecialization can optimize uses of design patterns, and provide b enchmarks showing the eect of sp ecialization on realistic versions of these examples. Earlier work has addressed the declaration of what to sp ecialize in the form of sp ecialization classes [32] and how to sp ecialize in the form of a prototyp e Java sp ecializer [28]. Here, we address the key issue of selecting where to sp ecialize. First, Section 2 describ es our p ersp ective on design patterns, followed by Section 3, which explains program sp ecialization. Section 4 describ es sp ecialization of design patterns by means of sp ecialization patterns. Afterwards, Section 5 provides a substantial example, INRIA Specialization Patterns 5 combining several design patterns. Then, Section 6 assesses
Recommended publications
  • Lecture 26: Creational Patterns
    Creational Patterns CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 26 — 11/29/2012 © Kenneth M. Anderson, 2012 1 Goals of the Lecture • Cover material from Chapters 20-22 of the Textbook • Lessons from Design Patterns: Factories • Singleton Pattern • Object Pool Pattern • Also discuss • Builder Pattern • Lazy Instantiation © Kenneth M. Anderson, 2012 2 Pattern Classification • The Gang of Four classified patterns in three ways • The behavioral patterns are used to manage variation in behaviors (think Strategy pattern) • The structural patterns are useful to integrate existing code into new object-oriented designs (think Bridge) • The creational patterns are used to create objects • Abstract Factory, Builder, Factory Method, Prototype & Singleton © Kenneth M. Anderson, 2012 3 Factories & Their Role in OO Design • It is important to manage the creation of objects • Code that mixes object creation with the use of objects can become quickly non-cohesive • A system may have to deal with a variety of different contexts • with each context requiring a different set of objects • In design patterns, the context determines which concrete implementations need to be present © Kenneth M. Anderson, 2012 4 Factories & Their Role in OO Design • The code to determine the current context, and thus which objects to instantiate, can become complex • with many different conditional statements • If you mix this type of code with the use of the instantiated objects, your code becomes cluttered • often the use scenarios can happen in a few lines of code • if combined with creational code, the operational code gets buried behind the creational code © Kenneth M. Anderson, 2012 5 Factories provide Cohesion • The use of factories can address these issues • The conditional code can be hidden within them • pass in the parameters associated with the current context • and get back the objects you need for the situation • Then use those objects to get your work done • Factories concern themselves just with creation, letting your code focus on other things © Kenneth M.
    [Show full text]
  • Prof. Catalin Boja, Phd [email protected] Source Code Quality
    Design patterns Prof. Catalin Boja, PhD [email protected] http://acs.ase.ro/software-quality-testing Source code quality Principles for writing the code: • Easy to read / understand - clear • Easy to modify - structured • Easy to reuse • Simple (complexity) • Easy to test • Implement patterns for the standard problem Left: Simply Explained: Code Reuse 2009-12- acs.ase.ro [email protected] 03.By Oliver Widder, Webcomics Geek Aad Poke.2 Source code quality Forces that influence it: • Available time (delivery terms) • Costs • The experience of the programmer • Programmer competences • Specifications clarity • Solution complexity • Change rates for specifications, requirements, team, etc http://khristianmcfadyen.com/ acs.ase.ro [email protected] 3 Anti-Pattern: Big ball of mud “A Big Ball of Mud is a haphazardly structured, sprawling, sloppy, duct-tape- and-baling-wire, spaghetti- code jungle.” Brian Foote and Joseph Yoder, Big Ball of Mud, September 1997 acs.ase.ro [email protected] 4 Anti-Pattern: Big ball of mud Where from ? Why ? • Throwaway code - Temporary (Prototyping) solutions to be replaced / rewritten • Cut and Paste code • Adapting code by commenting / deleting other solutions • Very short or unrealistic deadlines • Lack of experience • Lack of standards / procedures acs.ase.ro [email protected] 5 Anti-Pattern: Big ball of mud How do you avoid it? • Rewriting the code (Refactoring) to an acceptable maturity level • Use Clean Code Principles • Design Patterns Implementation acs.ase.ro [email protected] 6 Design-pattern • A pattern is a reusable solution for a standard problem in a given context • Facilitates the reuse of architectures and software design • They are not data structures acs.ase.ro [email protected] 7 Design-pattern “A pattern involves a general “..
    [Show full text]
  • Design Patterns in Ocaml
    Design Patterns in OCaml Antonio Vicente [email protected] Earl Wagner [email protected] Abstract The GOF Design Patterns book is an important piece of any professional programmer's library. These patterns are generally considered to be an indication of good design and development practices. By giving an implementation of these patterns in OCaml we expected to better understand the importance of OCaml's advanced language features and provide other developers with an implementation of these familiar concepts in order to reduce the effort required to learn this language. As in the case of Smalltalk and Scheme+GLOS, OCaml's higher order features allows for simple elegant implementation of some of the patterns while others were much harder due to the OCaml's restrictive type system. 1 Contents 1 Background and Motivation 3 2 Results and Evaluation 3 3 Lessons Learned and Conclusions 4 4 Creational Patterns 5 4.1 Abstract Factory . 5 4.2 Builder . 6 4.3 Factory Method . 6 4.4 Prototype . 7 4.5 Singleton . 8 5 Structural Patterns 8 5.1 Adapter . 8 5.2 Bridge . 8 5.3 Composite . 8 5.4 Decorator . 9 5.5 Facade . 10 5.6 Flyweight . 10 5.7 Proxy . 10 6 Behavior Patterns 11 6.1 Chain of Responsibility . 11 6.2 Command . 12 6.3 Interpreter . 13 6.4 Iterator . 13 6.5 Mediator . 13 6.6 Memento . 13 6.7 Observer . 13 6.8 State . 14 6.9 Strategy . 15 6.10 Template Method . 15 6.11 Visitor . 15 7 References 18 2 1 Background and Motivation Throughout this course we have seen many examples of methodologies and tools that can be used to reduce the burden of working in a software project.
    [Show full text]
  • Creational Patterns
    9. Creational Pattern Venkat Subramaniam CDP-1 Creational Patterns • Abstracts instantiation process • Makes system independent of how its objects are œ created œ composed œ represented • Encapsulates knowledge about which concrete classes the system uses • Hides how instances of these classes are created and put together Venkat Subramaniam CDP-2 Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes Venkat Subramaniam CDP-3 Example that would benefit from Abstract Factory ComputerModelA MemoryType A CPUTypeA ModemTypeA BuildComputer(ComputerModelA& comp) { comp.Add(new MemoryTypeA); comp.Add(new CPUTypeA); comp.Add(new ModemTypeA); } What if I want to build a Computer of Model B with Model B Memory,CPU and Modem? Venkat Subramaniam CDP-4 Using Abstract Factory ComputerFactory Client Computer createComputer() createMemory() createCPU() Computer Computer createModem() ModelA ModelB Memory CompFactoryB CompFactoryA createComputer() createComputer() Memory Memory createMemory() createMemory() ModelA ModelB createCPU() createCPU() createModem() createModem() Venkat Subramaniam CDP-5 Using Abstract Factory... BuildComputer(Computer& comp, ComputerFactory& compFactory) { comp.Add(compFactory.createMemory()) ; comp.Add(compFactory.createCPU()); comp.Add(compFactory.createModem()); } Venkat Subramaniam CDP-6 .hen to use Abstract Factory? • Use Abstract Factory when: œ system should be independent of how its products are created, composed and represented œ system should
    [Show full text]
  • Java Design Patterns I
    Java Design Patterns i Java Design Patterns Java Design Patterns ii Contents 1 Introduction to Design Patterns 1 1.1 Introduction......................................................1 1.2 What are Design Patterns...............................................1 1.3 Why use them.....................................................2 1.4 How to select and use one...............................................2 1.5 Categorization of patterns...............................................3 1.5.1 Creational patterns..............................................3 1.5.2 Structural patterns..............................................3 1.5.3 Behavior patterns...............................................3 2 Adapter Design Pattern 5 2.1 Adapter Pattern....................................................5 2.2 An Adapter to rescue.................................................6 2.3 Solution to the problem................................................7 2.4 Class Adapter..................................................... 11 2.5 When to use Adapter Pattern............................................. 12 2.6 Download the Source Code.............................................. 12 3 Facade Design Pattern 13 3.1 Introduction...................................................... 13 3.2 What is the Facade Pattern.............................................. 13 3.3 Solution to the problem................................................ 14 3.4 Use of the Facade Pattern............................................... 16 3.5 Download the Source Code.............................................
    [Show full text]
  • Table of Contents
    Table of Contents ± -—T^jTp^om Object-Oriented to Functional Programming 5 Chajava- an introduction 5 java programming paradigms 6 CO imperative programming CD Real-life imperative example Object-oriented paradigm 7 Objects and classes 7 Encapsulation 7 Abstraction 8 Inheritance 8 Polymorphism 9 Declarative programming 10 Functional programming 11 Working with collections versus working with streams 11 An introduction to Unified Modeling Language 12 Class relations 14 Generalization 15 Realization 15 Dependency 16 Association 16 Aggregation 16 Composition 17 Design patterns and principles 17 Single responsibility principle 18 Open/closed principle 20 Liskov Substitution Principle 20 Interface Segregation Principle 22 Dependency inversion principle 23 Summary 24 Chapter 2: Creational Patterns 27 Singleton pattern 27 Synchronized singletons 29 Synchronized singleton with double-checked locking mechanism 30 Lock-free thread-safe singleton 30 tu * y and lazy loacling 31 i he factory pattern 31 Simple factory pattern 32 Table of Contents Static factory 33 Simple factory with class registration using reflection 34 Simple factory with class registration using Product.newlnstance 35 Factory method pattern 36 Anonymous concrete factory 38 Abstract factory 38 Simple factory versus factory method versus abstract factory 40 Builder pattern 40 Car builder example 41 Simplified builder pattern 43 Anonymous builders with method chaining 44 Prototype pattern 45 Shallow clone versus deep clone Object pool pattern Summary аэоэсБ Chapter 3: Behavioral Patterns
    [Show full text]
  • Object-Oriented Design Patterns
    Object-Oriented Design Patterns David Janzen EECS 816 Object-Oriented Software Development University of Kansas Outline • Introduction – Design Patterns Overview – Strategy as an Early Example – Motivation for Creating and Using Design Patterns – History of Design Patterns • Gang of Four (GoF) Patterns – Creational Patterns – Structural Patterns – Behavioral Patterns Copyright © 2006 by David S. 2 Janzen. All rights reserved. What are Design Patterns? • In its simplest form, a pattern is a solution to a recurring problem in a given context • Patterns are not created, but discovered or identified • Some patterns will be familiar? – If you’ve been designing and programming for long, you’ve probably seen some of the patterns we will discuss – If you use Java Foundation Classes (Swing), Copyright © 2006 by David S. 3 you have certaJiannzleyn. Aulls rieghdts rsesoervmed.e design patterns Design Patterns Definition1 • Each pattern is a three-part rule, which expresses a relation between – a certain context, – a certain system of forces which occurs repeatedly in that context, and – a certain software configuration which allows these forces to resolve themselves 1. Dick Gabriel, http://hillside.net/patterns/definition.html Copyright © 2006 by David S. 4 Janzen. All rights reserved. A Good Pattern1 • Solves a problem: – Patterns capture solutions, not just abstract principles or strategies. • Is a proven concept: – Patterns capture solutions with a track record, not theories or speculation 1. James O. Coplien, http://hillside.net/patterns/definition.html Copyright © 2006 by David S. 5 Janzen. All rights reserved. A Good Pattern • The solution isn't obvious: – Many problem-solving techniques (such as software design paradigms or methods) try to derive solutions from first principles.
    [Show full text]
  • Verifying Object Construction
    Verifying Object Construction Martin Kellogg Manli Ran Manu Sridharan U. of Washington, USA UC Riverside, USA UC Riverside, USA [email protected] [email protected] [email protected] Martin Schäf Michael D. Ernst Amazon Web Services, USA U. of Washington, USA [email protected] [email protected] ABSTRACT ACM Reference Format: In object-oriented languages, constructors often have a combina- Martin Kellogg, Manli Ran, Manu Sridharan, Martin Schäf, and Michael D. tion of required and optional formal parameters. It is tedious and Ernst. 2020. Verifying Object Construction. In 42nd International Conference on Software Engineering (ICSE ’20), May 23–29, 2020, Seoul, Republic of Korea. inconvenient for programmers to write a constructor by hand for ACM, New York, NY, USA, 12 pages. https://doi.org/10.1145/3377811.3380341 each combination. The multitude of constructors is error-prone for clients, and client code is difficult to read due to the large number of constructor arguments. Therefore, programmers often use design 1 INTRODUCTION patterns that enable more flexible object construction—the builder This paper concerns verification of flexible object construction pat- pattern, dependency injection, or factory methods. terns in Java-like languages. Objects in such languages often have However, these design patterns can be too flexible: not all com- a combination of required and optional properties. For example, an binations of logical parameters lead to the construction of well- API for a point might require x and y values, with color being op- formed objects. When a client uses the builder pattern to construct tional. It would be legal for a client to supply fx;yg or fx;y; colorg, an object, the compiler does not check that a valid set of values was but not fx; colorg.
    [Show full text]
  • Non-Software Examples of Software Design Patterns Автор: Michael Duell
    Non-Software Examples of Software Design Patterns Автор: Michael Duell. Хорошая, хоть и старая (97 год) статья в которой приведены примеры применения паттернов в вещах, которые не имеют отношения к разработке. Такой подход отлично иллюстрирует паттерны и делает их более доступными для понимания. Например отлично показан паттерн Фасад: интерфейсы офисных устройств можно сильно упростить с помощью секретарши. Или например паттерн Бридж, который показан на примере выключателя которым можно управлять лампочкой, вентилятором или любым другим прибором. Non-Software Examples of Software Design Patterns by Michael Duell Abstract Software design patterns have roots in the architectural patterns of Christopher Alexander, and in the object movement. According to Alexander, patterns repeat themselves, since they are a generic solution to a given system of forces. The object movement looks to the real world for insights into modeling software relationships. With these dual roots, it seems reasonable that software design patterns should be repeated in real world objects. This paper presents a real world, non software instance of each design pattern from the book, Design Patterns - Elements of Reusable Object-Oriented Software [13]. The paper also discusses the implications of non-software examples on the communicative power of a pattern language, and on design pattern training. 1. Introduction Within the software industry, a growing community of patterns proponents exists. The roots of the patterns movement are found in the writings of architect Christopher Alexander, who describes a pattern as a generic solution to a given system of forces in the world [1]. Alexander's patterns can be observed in everyday structures. Each pattern in A Pattern Language[2] includes a picture of an archetypal example of the pattern.
    [Show full text]
  • Design Patterns Chapter 3
    A Brief Introduction to Design Patterns Jerod Weinman Department of Computer Science Grinnell College [email protected] Contents 1 Introduction 2 2 Creational Design Patterns 4 2.1 Introduction ...................................... 4 2.2 Factory ........................................ 4 2.3 Abstract Factory .................................... 5 2.4 Singleton ....................................... 8 2.5 Builder ........................................ 8 3 Structural Design Patterns 10 3.1 Introduction ...................................... 10 3.2 Adapter Pattern .................................... 10 3.3 Façade ......................................... 11 3.4 Flyweight ....................................... 12 3.5 Proxy ......................................... 13 3.6 Decorator ....................................... 14 4 Behavioral Design Patterns 20 4.1 Introduction ...................................... 20 4.2 Chain of Responsibility ................................ 20 4.3 Observer ........................................ 20 4.4 Visitor ......................................... 22 4.5 State .......................................... 25 1 Chapter 1 Introduction As you have probably experienced by now, writing correct computer programs can sometimes be quite a challenge. Writing the programs is fairly easy, it can be the “correct” part that maybe is a bit hard. One of the prime culprits is the challenge in understanding a great number of complex interactions. We all have probably experienced the crash of some application program
    [Show full text]
  • Abstract Factory Pattern Real World Example
    Abstract Factory Pattern Real World Example Sparry Reuven blackmails some spiritual and outact his swimming so fumblingly! Gasper remains unilateral: she embow her observatories allegorize too ninefold? Whining Dirk wince some menstruation and traps his Alain-Fournier so banteringly! Can You Improve This Article? Abstract factory code and features, when there are different flavors of elements of each service and every shape based on objects will implement modular gui design pattern real object step is. Do this pattern is hard before uploading a level, we are prototypical instance creation logic on desktop or dependent products are design pattern is often. Living in real world design pattern real factory world example, real world has a generic interfaces that will post helpful example, amazon web api like services. If i like this Decorator design pattern tutorial in Java then my share remains your friends and colleagues. Let's you factory method with own factory voil here read the. So basically, we release another attribute of abstraction which will identify the location and internally use again car factory implementation without even giving a single hint you the user. Sometimes, it think of patterns as recipes. It is not related to that. This is the Elven Army! In their state, we have been made up of objects of objects. What medium the intent of the merit Pool pattern? Given a real object as needed. This differs from the Observer pattern determined it allows any subscriber implementing an advance event handler to register what and vague topic notifications broadcast radio the publisher. And think is real world you have new instance property from a partial classes one place here abstract container, we have no review stack exchange is not.
    [Show full text]
  • Design Patterns As Higher-Order Datatype-Generic Programs
    Design Patterns as Higher-Order Datatype-Generic Programs Jeremy Gibbons Oxford University Computing Laboratory http://www.comlab.ox.ac.uk/jeremy.gibbons/ Abstract to what is provided by essentially every programming language, Design patterns are reusable abstractions in object-oriented soft- are higher-order (parametrization by code) and datatype-generic ware. However, using current mainstream programming languages, (parametrization by type constructor) features. Higher-order con- these elements can only be expressed extra-linguistically: as prose, structs have been available for decades in functional programming pictures, and prototypes. We believe that this is not inherent in languages such as ML [37] and Haskell [42]. Datatype genericity the patterns themselves, but evidence of a lack of expressivity in can be simulated in existing programming languages [7, 24, 39], the languages of today. We expect that, in the languages of the but we already have significant experience with robust prototypes future, the code parts of design patterns will be expressible as of languages that support it natively [25, 33]. reusable library components. Indeed, we claim that the languages We argue our case by capturing as higher-order datatype- of tomorrow will suffice; the future is not far away. All that is generic programs a small subset ORIGAMI of the Gang of Four needed, in addition to commonly-available features, are higher- (GOF) patterns. (For the sake of rhetorical style, we equate ‘GOF order and datatype-generic constructs; these features are already patterns’ with ‘design patterns’.) These programs are parametrized or nearly available now. We argue the case by presenting higher- along three dimensions: by the shape of the computation, which is determined by the shape of the underlying data, and repre- order datatype-generic programs capturing ORIGAMI, a small suite of patterns for recursive data structures.
    [Show full text]