More C++ Idioms/Print Version 1 More C++ Idioms/Print Version

Total Page:16

File Type:pdf, Size:1020Kb

More C++ Idioms/Print Version 1 More C++ Idioms/Print Version More C++ Idioms/Print Version 1 More C++ Idioms/Print Version Preface [1] C++ has indeed become too "expert friendly" --- Bjarne Stroustrup, The Problem with Programming , Technology Review, Nov 2006. Stroustrup's saying is true because experts are intimately familiar with the idioms in the language. With the increase in the idioms a programmer understands, the language becomes friendlier to him or her. The objective of this open content book is to present modern C++ idioms to programmers who have moderate level of familiarity with C++, and help elevate their knowledge so that C++ feels much friendlier to them. It is designed to be an exhaustive catalog of reusable idioms that expert C++ programmers often use while programming or designing using C++. This is an effort to capture their techniques and vocabulary into a single work. This book describes the idioms in a regular format: Name-Intent-Motivation-Solution-References, which is succinct and helps speed learning. By their nature, idioms tend to have appeared in the C++ community and in published work many times. An effort has been made to refer to the original source(s) where possible; if you find a reference incomplete or incorrect, please feel free to suggest or make improvements. The world is invited to catalog reusable pieces of C++ knowledge (similar to the book on design patterns by GoF). The goal here is to first build an exhaustive catalog of modern C++ idioms and later evolve it into an idiom language, just like a pattern language. Finally, the contents of this book can be redistributed under the terms of the GNU Free Documentation License. Aimed toward: Anyone with an intermediate level of knowledge in C++ and supported language paradigms Authors • Sumant Tambe talk -- The initiator and lead contributor since July 2007. • Many other C++ aficionados who continuously improve the writeup, examples, and references where necessary. Praise of the Book • "Great and valuable work!" -- Bjarne Stroustrup (February, 2009) Table of Contents Note: synonyms for each idiom are listed in parentheses. 1. Adapter Template 2. Address Of 3. Algebraic Hierarchy 4. Attach by Initialization 5. Barton-Nackman trick 6. Base-from-Member 7. Boost mutant 8. Calling Virtuals During Initialization 9. Capability Query 10. Checked delete 11. Clear-and-minimize 12. Coercion by Member Template 13. Compile Time Control Structures 14. Computational Constructor 15. Concrete Data Type More C++ Idioms/Print Version 2 16. Const auto_ptr 17. Construct On First Use 18. Construction Tracker 19. Copy-and-swap 20. Copy-on-write 21. Counted Body (intrusive reference counting) 22. Curiously Recurring Template Pattern 23. Detached Counted Body (non-intrusive reference counting) 24. Empty Base Optimization 25. Emulated Exception 26. enable-if 27. Envelope Letter 28. Erase-Remove 29. Examplar 30. Execute-Around Pointer 31. Export Guard Macro 32. Expression-template 33. Fake Vtable 34. Fast Pimpl 35. Final Class 36. Free Function Allocators 37. Friendship and the Attorney-Client 38. Function Object 39. Generic Container Idioms 40. Hierarchy Generation 41. Include Guard Macro 42. Inline Guard Macro 43. Inner Class 44. Int-To-Type 45. Interface Class 46. Iterator Pair 47. Making New Friends 48. Metafunction 49. Move Constructor 50. Multi-statement Macro 51. Multiple Member Initialization 52. Member Detector 53. Named Constructor 54. Named External Argument 55. Named Loop (labeled loop) 56. Named Parameter 57. Named Template Parameters 58. Nifty Counter (Schwarz Counter) 59. Non-copyable Mixin 60. Non-member get 61. Non-member Non-friend Function 62. Non-throwing swap More C++ Idioms/Print Version 3 63. Non-Virtual Interface (Public Overloaded Non-Virtuals Call Protected Non-Overloaded Virtuals) 64. nullptr 65. Object Generator 66. Object Template 67. Overload Set Creation 68. Parameterized Base Class (Parameterized Inheritance) 69. Pimpl (Handle Body, Compilation Firewall, Cheshire Cat) 70. Policy Clone (Metafunction wrapper) 71. Policy-based Design 72. Polymorphic Exception 73. Recursive Type Composition 74. Requiring or Prohibiting Heap-based Objects 75. Resource Acquisition Is Initialization (RAII, Execute-Around Object, Scoped Locking) 76. Resource Return 77. Return Type Resolver 78. Runtime Static Initialization Order Idioms 79. Safe bool 80. Scope Guard 81. Substitution Failure Is Not An Error (SFINAE) 82. Shortening Long Template Names 83. Shrink-to-fit 84. Small Object Optimization 85. Smart Pointer 86. Storage Class Tracker 87. Tag Dispatching 88. Temporary Base Class 89. Temporary Proxy 90. The result_of technique 91. Thin Template 92. Traits 93. Type Erasure 94. Type Generator (Templated Typedef) 95. Type Safe Enum 96. Type Selection 97. Virtual Constructor 98. Virtual Friend Function Address Of Intent Find address of a object of a class that has an overloaded unary ampersand (&) operator. Motivation C++ allows overloading of unary ampersand (&) operator for class types. The return type of such an operator need not be the actual address of the object. Intentions of such a class are highly debatable but the language allows it nevertheless. Address-of idiom is way to find the real address of an object irrespective of the overloaded unary More C++ Idioms/Print Version 4 ampersand operator and its access protection. In the example below, main function fails to compile because operator & of nonaddressable class is private. Even if it were accessible, a conversion from its return type double to a pointer would not been possible or meaningful. class nonaddressable { public: typedef double useless_type; private: useless_type operator&() const; }; int main(void) { nonaddressable na; nonaddressable * naptr = &na; // Compiler error here. return 0; } Solution and Sample Code The Address-of idiom retrieves the address of an object using a series of casts. template <class T> T * addressof(T & v) { return reinterpret_cast<T *>(& const_cast<char&>(reinterpret_cast<const volatile char &>(v))); } int main(void) { nonaddressable na; nonaddressable * naptr = addressof(na); // No more compiler error. return 0; } More C++ Idioms/Print Version 5 Known Uses • Boost addressof utility [2] Algebraic Hierarchy Intent To hide multiple closely related algebraic abstractions (numbers) behind a single generic abstraction and provide a generic interface to it. Also Known As • State (Gamma et al.) Motivation In pure object-oriented languages like Smalltalk, variables are run-time bindings to objects that act like labels. Binding a variable to an object is like sticking a label on it. Assignment in these languages is analogous to peeling a label off one object and putting it on another. On the other hand, in C and C++, variables are synonyms for addresses or offsets instead of being labels for objects. Assignment does not mean re-labelling, it means overwriting old contents with new one. Algebraic Hierarchy idiom uses delegated polymorphism to simulate weak variable to object binding in C++. Algebraic Hierarchy uses Envelope Letter idiom in its implementation. The motivation behind this idiom is to be able write code like the one below. Number n1 = Complex (1, 2); // Label n1 for a complex number Number n2 = Real (10); // Label n2 for a real number Number n3 = n1 + n2; // Result of addition is labelled n3 Number n2 = n3; // Re-labelling Solution and Sample Code Complete code showing implementation of Algebraic Hierarchy idiom is shown below. #include <iostream> using namespace std; struct BaseConstructor { BaseConstructor(int=0) {} }; class RealNumber; class Complex; class Number; class Number { friend class RealNumber; friend class Complex; public: Number (); Number & operator = (const Number &n); More C++ Idioms/Print Version 6 Number (const Number &n); virtual ~Number(); virtual Number operator + (Number const &n) const; void swap (Number &n) throw (); static Number makeReal (double r); static Number makeComplex (double rpart, double ipart); protected: Number (BaseConstructor); private: void redefine (Number *n); virtual Number complexAdd (Number const &n) const; virtual Number realAdd (Number const &n) const; Number *rep; short referenceCount; }; class Complex : public Number { friend class RealNumber; friend class Number; Complex (double d, double e); Complex (const Complex &c); virtual ~Complex (); virtual Number operator + (Number const &n) const; virtual Number realAdd (Number const &n) const; virtual Number complexAdd (Number const &n) const; double rpart, ipart; }; class RealNumber : public Number { friend class Complex; friend class Number; RealNumber (double r); RealNumber (const RealNumber &r); virtual ~RealNumber (); virtual Number operator + (Number const &n) const; More C++ Idioms/Print Version 7 virtual Number realAdd (Number const &n) const; virtual Number complexAdd (Number const &n) const; double val; }; /// Used only by the letters. Number::Number (BaseConstructor) : rep (0), referenceCount (1) {} /// Used by user and static factory functions. Number::Number () : rep (0), referenceCount (0) {} /// Used by user and static factory functions. Number::Number (const Number &n) : rep (n.rep), referenceCount (0) { cout << "Constructing a Number using Number::Number\n"; if (n.rep) n.rep->referenceCount++; } Number Number::makeReal (double r) { Number n; n.redefine (new RealNumber (r)); return n; } Number Number::makeComplex (double rpart, double ipart) { Number n; n.redefine (new Complex (rpart, ipart)); return n; } Number::~Number() { if (rep && --rep->referenceCount == 0) delete rep; } More C++ Idioms/Print Version
Recommended publications
  • X10 Language Specification
    X10 Language Specification Version 2.6.2 Vijay Saraswat, Bard Bloom, Igor Peshansky, Olivier Tardieu, and David Grove Please send comments to [email protected] January 4, 2019 This report provides a description of the programming language X10. X10 is a class- based object-oriented programming language designed for high-performance, high- productivity computing on high-end computers supporting ≈ 105 hardware threads and ≈ 1015 operations per second. X10 is based on state-of-the-art object-oriented programming languages and deviates from them only as necessary to support its design goals. The language is intended to have a simple and clear semantics and be readily accessible to mainstream OO pro- grammers. It is intended to support a wide variety of concurrent programming idioms. The X10 design team consists of David Grove, Ben Herta, Louis Mandel, Josh Milthorpe, Vijay Saraswat, Avraham Shinnar, Mikio Takeuchi, Olivier Tardieu. Past members include Shivali Agarwal, Bowen Alpern, David Bacon, Raj Barik, Ganesh Bikshandi, Bob Blainey, Bard Bloom, Philippe Charles, Perry Cheng, David Cun- ningham, Christopher Donawa, Julian Dolby, Kemal Ebcioglu,˘ Stephen Fink, Robert Fuhrer, Patrick Gallop, Christian Grothoff, Hiroshi Horii, Kiyokuni Kawachiya, Al- lan Kielstra, Sreedhar Kodali, Sriram Krishnamoorthy, Yan Li, Bruce Lucas, Yuki Makino, Nathaniel Nystrom, Igor Peshansky, Vivek Sarkar, Armando Solar-Lezama, S. Alexander Spoon, Toshio Suganuma, Sayantan Sur, Toyotaro Suzumura, Christoph von Praun, Leena Unnikrishnan, Pradeep Varma, Krishna Nandivada Venkata, Jan Vitek, Hai Chuan Wang, Tong Wen, Salikh Zakirov, and Yoav Zibin. For extended discussions and support we would like to thank: Gheorghe Almasi, Robert Blackmore, Rob O’Callahan, Calin Cascaval, Norman Cohen, Elmootaz El- nozahy, John Field, Kevin Gildea, Sara Salem Hamouda, Michihiro Horie, Arun Iyen- gar, Chulho Kim, Orren Krieger, Doug Lea, John McCalpin, Paul McKenney, Hiroki Murata, Andrew Myers, Filip Pizlo, Ram Rajamony, R.
    [Show full text]
  • Encapsulation and Data Abstraction
    Data abstraction l Data abstraction is the main organizing principle for building complex software systems l Without data abstraction, computing technology would stop dead in its tracks l We will study what data abstraction is and how it is supported by the programming language l The first step toward data abstraction is called encapsulation l Data abstraction is supported by language concepts such as higher-order programming, static scoping, and explicit state Encapsulation l The first step toward data abstraction, which is the basic organizing principle for large programs, is encapsulation l Assume your television set is not enclosed in a box l All the interior circuitry is exposed to the outside l It’s lighter and takes up less space, so it’s good, right? NO! l It’s dangerous for you: if you touch the circuitry, you can get an electric shock l It’s bad for the television set: if you spill a cup of coffee inside it, you can provoke a short-circuit l If you like electronics, you may be tempted to tweak the insides, to “improve” the television’s performance l So it can be a good idea to put the television in an enclosing box l A box that protects the television against damage and that only authorizes proper interaction (on/off, channel selection, volume) Encapsulation in a program l Assume your program uses a stack with the following implementation: fun {NewStack} nil end fun {Push S X} X|S end fun {Pop S X} X=S.1 S.2 end fun {IsEmpty S} S==nil end l This implementation is not encapsulated! l It has the same problems as a television set
    [Show full text]
  • Contents Credits & Contacts
    overload issue 72 april 2006 contents credits & contacts Multithreading 101 Overload Editor: Alan Griffiths Tim Penhey 7 [email protected] [email protected] To Grin Again Contributing Editor: Alan Griffiths 10 Mark Radford [email protected] A Fistful of Idioms Steve Love 14 Advisors: Phil Bass C++ Best Practice: [email protected] Designing Header Files Thaddaeus Frogley Alan Griffiths 19 [email protected] Richard Blundell Visiting Alice [email protected] Phil Bass 24 Pippa Hennessy [email protected] Tim Penhey [email protected] Advertising: Thaddaeus Frogley [email protected] Overload is a publication of the ACCU. For details of the ACCU and other ACCU publications and activities, see the ACCU website. ACCU Website: http://www.accu.org/ Information and Membership: Join on the website or contact David Hodge [email protected] Publications Officer: John Merrells [email protected] Copy Deadlines All articles intended for publication in Overload 73 should be submitted to the editor by ACCU Chair: May 1st 2006, and for Overload 74 by July 1st 2006. Ewan Milne [email protected] 3 overload issue 72 april 2006 Editorial: Doing What You Can Your magazine needs you! f you look at the contents of this issue of Overload you’ll see that most of the feature content has been written by the editorial team.You might even notice that the remaining Iarticle is not new material. To an extent this is a predictable consequence of the time of year: many of the potential contributors are busy preparing for the conference. However, as editor for the last couple of years I’ve noticed More on WG14 that there is a worrying decline in proposals for articles Last time I commented on the fact that I was hearing from authors.
    [Show full text]
  • 9. Abstract Data Types
    COMPUTER SCIENCE COMPUTER SCIENCE SEDGEWICK/WAYNE SEDGEWICK/WAYNE 9. Abstract Data Types •Overview 9. Abstract Data Types •Color •Image processing •String processing Section 3.1 http://introcs.cs.princeton.edu http://introcs.cs.princeton.edu Abstract data types Object-oriented programming (OOP) A data type is a set of values and a set of operations on those values. Object-oriented programming (OOP). • Create your own data types (sets of values and ops on them). An object holds a data type value. Primitive types • Use them in your programs (manipulate objects). Variable names refer to objects. • values immediately map to machine representations data type set of values examples of operations • operations immediately map to Color three 8-bit integers get red component, brighten machine instructions. Picture 2D array of colors get/set color of pixel (i, j) String sequence of characters length, substring, compare We want to write programs that process other types of data. • Colors, pictures, strings, An abstract data type is a data type whose representation is hidden from the user. • Complex numbers, vectors, matrices, • ... Impact: We can use ADTs without knowing implementation details. • This lecture: how to write client programs for several useful ADTs • Next lecture: how to implement your own ADTs An abstract data type is a data type whose representation is hidden from the user. 3 4 Sound Strings We have already been using ADTs! We have already been using ADTs! A String is a sequence of Unicode characters. defined in terms of its ADT values (typical) Java's String ADT allows us to write Java programs that manipulate strings.
    [Show full text]
  • Abstract Data Types
    Chapter 2 Abstract Data Types The second idea at the core of computer science, along with algorithms, is data. In a modern computer, data consists fundamentally of binary bits, but meaningful data is organized into primitive data types such as integer, real, and boolean and into more complex data structures such as arrays and binary trees. These data types and data structures always come along with associated operations that can be done on the data. For example, the 32-bit int data type is defined both by the fact that a value of type int consists of 32 binary bits but also by the fact that two int values can be added, subtracted, multiplied, compared, and so on. An array is defined both by the fact that it is a sequence of data items of the same basic type, but also by the fact that it is possible to directly access each of the positions in the list based on its numerical index. So the idea of a data type includes a specification of the possible values of that type together with the operations that can be performed on those values. An algorithm is an abstract idea, and a program is an implementation of an algorithm. Similarly, it is useful to be able to work with the abstract idea behind a data type or data structure, without getting bogged down in the implementation details. The abstraction in this case is called an \abstract data type." An abstract data type specifies the values of the type, but not how those values are represented as collections of bits, and it specifies operations on those values in terms of their inputs, outputs, and effects rather than as particular algorithms or program code.
    [Show full text]
  • Abstract Data Types (Adts)
    Data abstraction: Abstract Data Types (ADTs) CSE 331 University of Washington Michael Ernst Outline 1. What is an abstract data type (ADT)? 2. How to specify an ADT – immutable – mutable 3. The ADT design methodology Procedural and data abstraction Recall procedural abstraction Abstracts from the details of procedures A specification mechanism Reasoning connects implementation to specification Data abstraction (Abstract Data Type, or ADT): Abstracts from the details of data representation A specification mechanism + a way of thinking about programs and designs Next lecture: ADT implementations Representation invariants (RI), abstraction functions (AF) Why we need Abstract Data Types Organizing and manipulating data is pervasive Inventing and describing algorithms is rare Start your design by designing data structures Write code to access and manipulate data Potential problems with choosing a data structure: Decisions about data structures are made too early Duplication of effort in creating derived data Very hard to change key data structures An ADT is a set of operations ADT abstracts from the organization to meaning of data ADT abstracts from structure to use Representation does not matter; this choice is irrelevant: class RightTriangle { class RightTriangle { float base, altitude; float base, hypot, angle; } } Instead, think of a type as a set of operations create, getBase, getAltitude, getBottomAngle, ... Force clients (users) to call operations to access data Are these classes the same or different? class Point { class Point { public float x; public float r; public float y; public float theta; }} Different: can't replace one with the other Same: both classes implement the concept "2-d point" Goal of ADT methodology is to express the sameness Clients depend only on the concept "2-d point" Good because: Delay decisions Fix bugs Change algorithms (e.g., performance optimizations) Concept of 2-d point, as an ADT class Point { // A 2-d point exists somewhere in the plane, ..
    [Show full text]
  • Csci 658-01: Software Language Engineering Python 3 Reflexive
    CSci 658-01: Software Language Engineering Python 3 Reflexive Metaprogramming Chapter 3 H. Conrad Cunningham 4 May 2018 Contents 3 Decorators and Metaclasses 2 3.1 Basic Function-Level Debugging . .2 3.1.1 Motivating example . .2 3.1.2 Abstraction Principle, staying DRY . .3 3.1.3 Function decorators . .3 3.1.4 Constructing a debug decorator . .4 3.1.5 Using the debug decorator . .6 3.1.6 Case study review . .7 3.1.7 Variations . .7 3.1.7.1 Logging . .7 3.1.7.2 Optional disable . .8 3.2 Extended Function-Level Debugging . .8 3.2.1 Motivating example . .8 3.2.2 Decorators with arguments . .9 3.2.3 Prefix decorator . .9 3.2.4 Reformulated prefix decorator . 10 3.3 Class-Level Debugging . 12 3.3.1 Motivating example . 12 3.3.2 Class-level debugger . 12 3.3.3 Variation: Attribute access debugging . 14 3.4 Class Hierarchy Debugging . 16 3.4.1 Motivating example . 16 3.4.2 Review of objects and types . 17 3.4.3 Class definition process . 18 3.4.4 Changing the metaclass . 20 3.4.5 Debugging using a metaclass . 21 3.4.6 Why metaclasses? . 22 3.5 Chapter Summary . 23 1 3.6 Exercises . 23 3.7 Acknowledgements . 23 3.8 References . 24 3.9 Terms and Concepts . 24 Copyright (C) 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Note: This chapter adapts David Beazley’s debugly example presentation from his Python 3 Metaprogramming tutorial at PyCon’2013 [Beazley 2013a].
    [Show full text]
  • Exploring Languages with Interpreters and Functional Programming Chapter 22
    Exploring Languages with Interpreters and Functional Programming Chapter 22 H. Conrad Cunningham 5 November 2018 Contents 22 Overloading and Type Classes 2 22.1 Chapter Introduction . .2 22.2 Polymorphism in Haskell . .2 22.3 Why Overloading? . .2 22.4 Defining an Equality Class and Its Instances . .4 22.5 Type Class Laws . .5 22.6 Another Example Class Visible ..................5 22.7 Class Extension (Inheritance) . .6 22.8 Multiple Constraints . .7 22.9 Built-In Haskell Classes . .8 22.10Comparison to Other Languages . .8 22.11What Next? . .9 22.12Exercises . 10 22.13Acknowledgements . 10 22.14References . 11 22.15Terms and Concepts . 11 Copyright (C) 2017, 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Browser Advisory: The HTML version of this textbook requires use of a browser that supports the display of MathML. A good choice as of November 2018 is a recent version of Firefox from Mozilla. 1 22 Overloading and Type Classes 22.1 Chapter Introduction Chapter 5 introduced the concept of overloading. Chapters 13 and 21 introduced the related concepts of type classes and instances. The goal of this chapter and the next chapter is to explore these concepts in more detail. The concept of type class was introduced into Haskell to handle the problem of comparisons, but it has had a broader and more profound impact upon the development of the language than its original purpose. This Haskell feature has also had a significant impact upon the design of subsequent languages (e.g.
    [Show full text]
  • General Specification of Basic Software Modules AUTOSAR CP R19-11
    General Specification of Basic Software Modules AUTOSAR CP R19-11 Document Title General Specification of Basic Software Modules Document Owner AUTOSAR Document Responsibility AUTOSAR Document Identification No 578 Document Status published Part of AUTOSAR Standard Classic Platform Part of Standard Release R19-11 Document Change History Date Release Changed by Change Description 2019-11-28 R19-11 AUTOSAR Include guard for header files Release minor corrections / clarifications / Management editorial changes; For details please refer to the ChangeDocumentation Changed Document Status from Final to published 2018-10-31 4.4.0 AUTOSAR minor corrections / clarifications / Release editorial changes; For details please Management refer to the ChangeDocumentation 2017-12-08 4.3.1 AUTOSAR minor corrections / clarifications / Release editorial changes; For details please Management refer to the ChangeDocumentation 2016-11-30 4.3.0 AUTOSAR Meta Data handling Release Changed to MISRA C 2012 Management Standard Debugging support was removed minor corrections / clarifications / editorial changes; For details please refer to the ChangeDocumentation 2015-07-31 4.2.2 AUTOSAR Debugging support marked as Release obsolete Management minor corrections / clarifications / editorial changes; For details please refer to the ChangeDocumentation 1 of 86 Document ID 578: AUTOSAR_SWS_BSWGeneral - AUTOSAR confidential - General Specification of Basic Software Modules AUTOSAR CP R19-11 Document Change History Date Release Changed by Change Description 2014-10-31
    [Show full text]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]
  • Software II: Principles of Programming Languages
    Software II: Principles of Programming Languages Lecture 6 – Data Types Some Basic Definitions • A data type defines a collection of data objects and a set of predefined operations on those objects • A descriptor is the collection of the attributes of a variable • An object represents an instance of a user- defined (abstract data) type • One design issue for all data types: What operations are defined and how are they specified? Primitive Data Types • Almost all programming languages provide a set of primitive data types • Primitive data types: Those not defined in terms of other data types • Some primitive data types are merely reflections of the hardware • Others require only a little non-hardware support for their implementation The Integer Data Type • Almost always an exact reflection of the hardware so the mapping is trivial • There may be as many as eight different integer types in a language • Java’s signed integer sizes: byte , short , int , long The Floating Point Data Type • Model real numbers, but only as approximations • Languages for scientific use support at least two floating-point types (e.g., float and double ; sometimes more • Usually exactly like the hardware, but not always • IEEE Floating-Point Standard 754 Complex Data Type • Some languages support a complex type, e.g., C99, Fortran, and Python • Each value consists of two floats, the real part and the imaginary part • Literal form real component – (in Fortran: (7, 3) imaginary – (in Python): (7 + 3j) component The Decimal Data Type • For business applications (money)
    [Show full text]
  • An Analysis of the Dynamic Behavior of Javascript Programs
    An Analysis of the Dynamic Behavior of JavaScript Programs Gregor Richards Sylvain Lebresne Brian Burg Jan Vitek S3 Lab, Department of Computer Science, Purdue University, West Lafayette, IN fgkrichar,slebresn,bburg,[email protected] Abstract becoming a general purpose computing platform with office appli- The JavaScript programming language is widely used for web cations, browsers and development environments [15] being devel- programming and, increasingly, for general purpose computing. oped in JavaScript. It has been dubbed the “assembly language” of the Internet and is targeted by code generators from the likes As such, improving the correctness, security and performance of 2;3 JavaScript applications has been the driving force for research in of Java and Scheme [20]. In response to this success, JavaScript type systems, static analysis and compiler techniques for this lan- has started to garner academic attention and respect. Researchers guage. Many of these techniques aim to reign in some of the most have focused on three main problems: security, correctness and dynamic features of the language, yet little seems to be known performance. Security is arguably JavaScript’s most pressing prob- about how programmers actually utilize the language or these fea- lem: a number of attacks have been discovered that exploit the lan- tures. In this paper we perform an empirical study of the dynamic guage’s dynamism (mostly the ability to access and modify shared behavior of a corpus of widely-used JavaScript programs, and an- objects and to inject code via eval). Researchers have proposed ap- alyze how and why the dynamic features are used.
    [Show full text]