Towards a Catalog of Java Dependency Injection Anti-Patterns

Total Page:16

File Type:pdf, Size:1020Kb

Towards a Catalog of Java Dependency Injection Anti-Patterns Towards a Catalog of Java Dependency Injection Anti-Patterns Rodrigo Laigner Marcos Kalinowski Luiz Carvalho PUC-Rio, Brazil PUC-Rio, Brazil PUC-Rio, Brazil [email protected] [email protected] [email protected] Diogo Mendonça Alessandro Garcia CEFET/RJ, Brazil PUC-Rio, Brazil [email protected] [email protected] ABSTRACT ACM Reference Format: [Context] Dependency Injection (DI) is a commonly applied mech- Rodrigo Laigner, Marcos Kalinowski, Luiz Carvalho, Diogo Mendonça, and Alessandro Garcia. 2019. Towards a Catalog of Java Dependency Injec- anism to decouple classes from their dependencies in order to pro- tion Anti-Patterns. In SBES ’19: Brazilian Symposium on Software Engineering, vide better modularization of software. In the context of Java, the September 23–27, 2019, Salvador, BA. ACM, New York, NY, USA, 10 pages. availability of a DI specification and popular frameworks, such as https://doi.org/10.1145/1122445.1122456 Spring, facilitate DI usage in software projects. However, bad DI implementation practices can have negative consequences. Even though the literature suggests the existence of DI anti-patterns, 1 INTRODUCTION there is no detailed catalog of such bad practices. Moreover, there Dependency injection (DI) is a mechanism for improving software is no evidence on their occurrence and perceived usefulness from modularity. DI enables less coupling among modules by refraining the developer’s point of view. [Goal] Our goal is to review the them from being aware of implementation details of each other reported DI anti-patterns in order to analyze their completeness [15]. DI has become a common practice in the software industry, and to propose and evaluate a novel catalog of DI anti-patterns in as characterized by the existence of DI frameworks and industry- the context of Java. [Method] We propose an initial catalog con- oriented publications [12][16]. For instance, Spring1, one of the taining twelve Java DI anti-patterns. We selected four open source most popular Java frameworks, and Google AdWords2, a large- software projects that adopt a DI framework and developed a tool scale web application, have its components interconnected through to statically analyze the occurrence of the DI anti-patterns within DI. Furthermore, Java defines a specification targeted at DI and their source code. Also, we conducted a survey through face to Microsoft .NET Core provides native DI capabilities. face interviews with three experienced developers that regularly Despite the existence of well designed frameworks, such as apply DI. [Results] At least nine different DI anti-patterns appeared Spring and Guice3, the implementation of DI is not trivial and in each analyzed project. In addition, the feedback received from demands in-depth knowledge on object-oriented design. Hence, the developers confirmed their relevance and the importance of while DI might support providing a better modularization, once investing further effort towards a catalog. [Conclusion] The results system modules do not need to concern about dependence resolu- indicate that the initial catalog contains Java DI anti-patterns that tion, improper DI usage may hinder the effective achievement of occur in practice and are useful. Sharing it with practitioners may this goal. help them to avoid such anti-patterns. Sharing it with the research Although the technical literature [16][20] suggests the existence community will enable further improving the catalog. of DI anti-patterns, there is no evidence about their occurrence, acceptance and perceived usefulness from developers’ point of view. CCS CONCEPTS Furthermore, such anti-patterns can lead to negative consequences, such as high coupling and potential overuse of memory. Therefore, • Software and its engineering → Object oriented develop- it is necessary to properly document DI anti-patterns. Considering ment; Software design engineering. this scenario, our study aims at reviewing the completeness of the DI anti-patterns reported in the literature. We also propose a KEYWORDS catalog of DI anti-patterns in the context of Java, and investigate dependency injection, anti-pattern, java, pattern, framework their occurrence by mining open source repositories. Additionally, this study seeks to gather the perception of developers through an expert survey in order to validate the proposed catalog. The contributions of this paper are: (i) an initial effort towards Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed documenting a catalog of Java DI anti-patterns; (ii) an investigation for profit or commercial advantage and that copies bear this notice and the full citation on the occurrence of the proposed anti-patterns, indicating that they on the first page. Copyrights for components of this work owned by others than the author(s) must be honored. Abstracting with credit is permitted. To copy otherwise, or are general and occur within different projects; and (iii) gathering republish, to post on servers or to redistribute to lists, requires prior specific permission the perception of developers on the proposed catalog by an expert and/or a fee. Request permissions from [email protected]. SBES ’19, September 23–27, 2019, Salvador, BA © 2019 Copyright held by the owner/author(s). Publication rights licensed to ACM. 1https://spring.io ACM ISBN 978-1-4503-9999-9/18/06...$15.00 2https://github.com/google/guice/wiki/AppsThatUseGuice https://doi.org/10.1145/1122445.1122456 3https://github.com/google/guice SBES ’19, September 23–27, 2019, Salvador, BA R. Laigner, M. Kalinowski, L. Matheus, D. Mendonça, A. Garcia survey, indicating that the catalog is perceived as relevant and Table 1: Annotations defined in JSR-330 useful. The remainder of this paper is organized as follows. In Section 2 Annotation Description we provide the background on dependency injection and DI anti- A type annotated with @Singleton will be patterns and discuss related work. In Section 3, we describe our instantiated only once across the run-time goal and research questions. Next, the proposed catalog of DI anti- Singleton of the application patterns is introduced in Section 4. An evaluation of the occurrence of the cataloged DI anti-patterns is presented on Section 5. Section Scopes are rules applied to the life-cycle 6 presents the expert survey on the acceptance and perceived use- of a given object. Depending on the fulness of the catalog. Section 7 discusses the threats of validity. framework, the default implementation Scope Finally, Section 8 presents the concluding remarks. varies from retaining the instance for reuse or providing a new instance every 2 BACKGROUND AND RELATED WORK time a dependence is requested This section provides a brief background on the principles behind The value associated with a Qualifier DI and its main concepts. Also, previously reported DI anti-patterns Qualifier annotation is used to distinguish which are reviewed and related work is presented. concrete implementation should be provided Used to identify an object instance. It aims 2.1 Dependency Injection Named at assigning a specific name to a dependence The term Inversion of Control (IoC) was first introduced by Johnson and Foote [8] in the context of software frameworks. In order to Defines an injection point for which aDI container must provide an object instance. make use of functionalities provided by a framework, it is usually Inject needed to extend a set of classes. Meanwhile, this extension often It can be placed in constructors, methods, refrains the system from controlling its own execution, incurring in and fields an inversion of control. Later, the dependency inversion principle (DIP) was introduced by Martin [11]. The DIP states that modules should not depend on details of another module. Instead, abstrac- Table 2: DI anti-patterns extracted from [16] tions should be used in place of direct dependencies in order to enable reuse [11]. Based on Martin’s [11] description, Yang et al. Name Description [22] assert that in Java, DIP means that "a class should depend on Dependencies are controlled interface or abstract types, not on concrete types". These concepts Control Freak directly, as opposed to IoC form a basis for comprehending DI. Foreign defaults are used as According to Crasso et al. [4], DI is a programming mechanism Bastard Injection that "builds on the decoupling given by isolating components be- default values for dependencies hind interfaces, and focuses on delegating the responsibility for Constructors are assumed Constrained Construction component [or module] creation and binding to a DI container". to have a particular signature As noted by Yang et al. [22], DI is a specific structural form of DIP. Indeed, DI implements the DIP principle, once components are An implicit service can serve decoupled through an interface oriented design. Service Locator dependencies to consumers However, although we achieve better modularity through ab- but isn’t guaranteed to do so stractions, we still have to deal with instantiation of concrete classes, as noted by the Gamma et al. [7]. In the context of DI, Crasso et al. [4] assert that the responsibility for component creation is given to 2.2 DI Anti-Patterns a DI container. In particular, the DI container is usually employed According to Brown et al. [2], an anti-pattern is a "description in order to enable the IoC principle in DI. In the context of DI, IoC of a commonly occurring solution to a problem that generates is about delegating responsibilities that are outside of the scope of a decidedly negative consequences". In line with this definition, we given class to other classes of the system, the ones that can actually can understand a DI anti-pattern as a recurring DI usage pattern in be accountable for these given responsibilities, such as instance source code that degrades aspects that DI is supposed to improve, provision.
Recommended publications
  • What Is Spring Framework?
    Software Engineering a.a. 2019-2020 Introduction to Spring Framework Prof. Luca Mainetti Università del Salento Roadmap ■ Introduction to Spring ■ Dependency Injection and IoC ■ Bean ■ AoP ■ Module Architecture Introduction to Spring Framework 2 Luca Mainetti What Is Spring Framework? ■ Spring is the most popular application development framework for Java enterprise ■ Open source Java platform since 2003. ■ Spring supports all main application servers and JEE standards ■ Spring handles the infrastructure so you can focus on your application ■ Current version: 5.0.X Introduction to Spring Framework 3 Luca Mainetti What does Spring offer? ■ Dependency Injection – Also known as IoC (Inversion of Control) ■ Aspect Oriented Programming – Runtime injection-based ■ Portable Service Abstractions – The rest of spring • ORM, DAO, Web MVC, Web, etc. • Allows access to these without knowing how they actually work Introduction to Spring Framework 4 Luca Mainetti Dependency Injection ■ The technology that actually defines Spring (Heart of Spring). ■ Dependency Injection helps us to keep our classes as indepedent as possible. – Increase reuse by applying low coupling – Easy testing – More understandable An injection is the passing of a dependency (a service) to a dependent object (a client). Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. Introduction to Spring Framework 5 Luca Mainetti Dependency Injection and Inversion of Control (IoC) In software engineering, inversion of control (IoC) describes a design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library. ■ The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and dependency Injection is merely one concrete example of Inversion of Control.
    [Show full text]
  • Ioc Containers in Spring
    301AA - Advanced Programming Lecturer: Andrea Corradini [email protected] http://pages.di.unipi.it/corradini/ AP-2018-11: Frameworks and Inversion of Control Frameworks and Inversion of Control • Recap: JavaBeans as Components • Frameworks, Component Frameworks and their features • Frameworks vs IDEs • Inversion of Control and Containers • Frameworks vs Libraries • Decoupling Components • Dependency Injection • IoC Containers in Spring 2 Components: a recap A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only. A software component can be deployed independently and is subject to composition by third party. Clemens Szyperski, ECOOP 1996 • Examples: Java Beans, CLR Assemblies • Contractually specified interfaces: events, methods and properties • Explicit context dependencies: serializable, constructor with no argument • Subject to composition: connection to other beans – Using connection oriented programming (event source and listeners/delegates) 3 Towards Component Frameworks • Software Framework: A collection of common code providing generic functionality that can be selectively overridden or specialized by user code providing specific functionality • Application Framework: A software framework used to implement the standard structure of an application for a specific development environment. • Examples: – GUI Frameworks – Web Frameworks – Concurrency Frameworks 4 Examples of Frameworks Web Application Frameworks GUI Toolkits 5 Examples: General Software Frameworks – .NET – Windows platform. Provides language interoperability – Android SDK – Supports development of apps in Java (but does not use a JVM!) – Cocoa – Apple’s native OO API for macOS. Includes C standard library and the Objective-C runtime. – Eclipse – Cross-platform, easily extensible IDE with plugins 6 Examples: GUI Frameworks • Frameworks for Application with GUI – MFC - Microsoft Foundation Class Library.
    [Show full text]
  • Inversion of Control in Spring – Using Annotation
    Inversion of Control in Spring – Using Annotation In this chapter, we will configure Spring beans and the Dependency Injection using annotations. Spring provides support for annotation-based container configuration. We will go through bean management using stereotypical annotations and bean scope using annotations. We will then take a look at an annotation called @Required, which allows us to specify which dependencies are actually required. We will also see annotation-based dependency injections and life cycle annotations. We will use the autowired annotation to wire up dependencies in the same way as we did using XML in the previous chapter. You will then learn how to add dependencies by type and by name. We will also use qualifier to narrow down Dependency Injections. We will also understand how to perform Java-based configuration in Spring. We will then try to listen to and publish events in Spring. We will also see how to reference beans using Spring Expression Language (SpEL), invoke methods using SpEL, and use operators with SpEL. We will then discuss regular expressions using SpEL. Spring provides text message and internationalization, which we will learn to implement in our application. Here's a list of the topics covered in this chapter: • Container configuration using annotations • Java-based configuration in Spring • Event handling in Spring • Text message and internationalization [ 1 ] Inversion of Control in Spring – Using Annotation Container configuration using annotation Container configuration using Spring XML sometimes raises the possibility of delays in application development and maintenance due to size and complexity. To solve this issue, the Spring Framework supports container configuration using annotations without the need of a separate XML definition.
    [Show full text]
  • Dependency Injection with Unity
    D EPEN DEPENDENCY INJECTION WITH UNITY Over the years software systems have evolutionarily become more and more patterns & practices D ENCY complex. One of the techniques for dealing with this inherent complexity Proven practices for predictable results of software systems is dependency injection – a design pattern that I allows the removal of hard-coded dependencies and makes it possible to Save time and reduce risk on your NJECT assemble a service by changing dependencies easily, whether at run-time software development projects by or compile-time. It promotes code reuse and loosely-coupled design which incorporating patterns & practices, I leads to more easily maintainable and flexible code. Microsoft’s applied engineering ON guidance that includes both production The guide you are holding in your hands is a primer on using dependency quality source code and documentation. W I injection with Unity – a lightweight extensible dependency injection TH DEPENDENCY INJECTION container built by the Microsoft patterns & practices team. It covers The guidance is designed to help U software development teams: various styles of dependency injection and also additional capabilities N I of Unity container, such as object lifetime management, interception, Make critical design and technology TY and registration by convention. It also discusses the advanced topics of selection decisions by highlighting WITH UNITY enhancing Unity with your custom extensions. the appropriate solution architectures, technologies, and Microsoft products The guide contains plenty of trade-off discussions and tips and tricks for for common scenarios managing your application cross-cutting concerns and making the most out of both dependency injection and Unity. These are accompanied by a Understand the most important Dominic Betts real world example that will help you master the techniques.
    [Show full text]
  • Designpatternsphp Documentation Release 1.0
    DesignPatternsPHP Documentation Release 1.0 Dominik Liebler and contributors Jul 18, 2021 Contents 1 Patterns 3 1.1 Creational................................................3 1.1.1 Abstract Factory........................................3 1.1.2 Builder.............................................8 1.1.3 Factory Method......................................... 13 1.1.4 Pool............................................... 18 1.1.5 Prototype............................................ 21 1.1.6 Simple Factory......................................... 24 1.1.7 Singleton............................................ 26 1.1.8 Static Factory.......................................... 28 1.2 Structural................................................. 30 1.2.1 Adapter / Wrapper....................................... 31 1.2.2 Bridge.............................................. 35 1.2.3 Composite............................................ 39 1.2.4 Data Mapper.......................................... 42 1.2.5 Decorator............................................ 46 1.2.6 Dependency Injection...................................... 50 1.2.7 Facade.............................................. 53 1.2.8 Fluent Interface......................................... 56 1.2.9 Flyweight............................................ 59 1.2.10 Proxy.............................................. 62 1.2.11 Registry............................................. 66 1.3 Behavioral................................................ 69 1.3.1 Chain Of Responsibilities...................................
    [Show full text]
  • Monadic Functional Reactive Programming
    Monadic Functional Reactive Programming Atze van der Ploeg Centrum Wiskunde & Informatica [email protected] Abstract FRP is based on the notion of a reactive computation: a monadic Functional Reactive Programming (FRP) is a way to program reac- computation which may require the occurrence of external events tive systems in functional style, eliminating many of the problems to continue. The Monadic FRP variant of a signal is a signal that arise from imperative techniques. In this paper, we present an computation: a reactive computation that may also emit values alternative FRP formulation that is based on the notion of a reac- during the computation. tive computation: a monadic computation which may require the This novel formulation has two differences with other FRP occurrence of external events to continue. A signal computation approaches: is a reactive computation that may also emit values. In contrast to • In contrast to signals in other FRP formulations, signal compu- signals in other FRP formulations, signal computations can end, tations can end. This leads to a simple, monadic interface for leading to a monadic interface for sequencing behavioral changes. sequencing behavioral changes. This interface has several advantages: routing is implicit, sequencing • behaviors is easier and more intuitive than the switching combina- In other FRP approaches, either the entire FRP expression is tors found in other FRP approaches, and dynamic lists require much re-evaluated on each external stimulus, or impure techniques less boilerplate code. In other FRP approaches, either the entire are used to prevent redundant re-computations: re-computing FRP expression is re-evaluated on each external stimulus, or impure the current value of signal while the input it depends on has not techniques are used to prevent redundant re-computations.
    [Show full text]
  • Simple Injector Documentation Release 5
    Simple Injector Documentation Release 5 Simple Injector Contributors Jul 27, 2021 Contents 1 Quick Start 3 1.1 Overview.................................................3 1.2 Getting started..............................................3 1.3 A Quick Example............................................4 1.3.1 Dependency Injection......................................4 1.3.2 Introducing Simple Injector...................................5 1.4 More information.............................................6 2 Using Simple Injector 7 2.1 Resolving instances...........................................9 2.2 Configuring Simple Injector....................................... 10 2.2.1 Auto-Registration/Batch-registration.............................. 13 2.3 Collections................................................ 14 2.3.1 Collection types......................................... 16 2.3.2 Auto-registering collections.................................. 16 2.3.3 Adding registrations to an existing collection......................... 17 2.4 Verifying the container’s configuration................................. 17 2.5 Automatic constructor injection / auto-wiring.............................. 18 2.6 More information............................................. 19 3 Object Lifetime Management 21 3.1 Transient Lifestyle............................................ 22 3.2 Singleton Lifestyle............................................ 22 3.3 Scoped Lifestyle............................................. 23 3.3.1 Disposing a Scope......................................
    [Show full text]
  • The Spring Framework: an Open Source Java Platform for Developing Robust Java Applications
    International Journal of Innovative Technology and Exploring Engineering (IJITEE) ISSN: 2278-3075, Volume-3 Issue-2, July 2013 The Spring Framework: An Open Source Java Platform for Developing Robust Java Applications Dashrath Mane, Ketaki Chitnis, Namrata Ojha Abstract— The fundamental concepts of Spring Framework is Supported deployment platforms range from standalone presented in this paper.Spring framework is an open source Java applications to Tomcat and Java EE servers such as platform that provides comprehensive infrastructure support for WebSphere. Spring is also a first-class citizen on major developing robust Java applications very easily and very rapidly. cloud platforms with Java support, e.g. on Heroku, Google The Spring Framework is a lightweight solution and a potential App Engine, Amazon Elastic Beanstalk and VMware's one-stop-shop for building your enterprise-ready applications. Cloud Foundry.[1] IndexTerms— Aspect Oriented Programming, Dependency Injection, IoC Container, ORM. II. SPRING FRAMEWORK ARCHITECTURE Spring could potentially be a one-stop shop for all your I. INTRODUCTION enterprise applications; however, Spring is modular, Spring is the most popular application development allowing you to pick and choose which modules are framework for enterprise Java. Millions of developers applicable to you, without having to bring in the rest. around the world use Spring Framework to create high The Spring Framework provides about 20 modules which performing, easily testable, reusable code. Spring can be used based on an application requirement. framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
    [Show full text]
  • An Introduction to Dependency Inversion Page 1 of 12
    Peruse Muse Infuse: An Introduction to Dependency Inversion Page 1 of 12 An Introduction to Dependency Inversion Originaly posted by AdrianK, 1-Nov-2010 at: http://www.morphological.geek.nz/blogs/viewpost/Peruse Muse Infuse/An Introduction to Dependency Inversion.aspx Tagged under: Architecture, Web Development, Patterns An Introduction to Dependency Inversion This article is for anyone (mainly developers, and specifically .Net developers) who is unfamiliar with Dependency Inversion or design patterns in general. The basic rationale behind the Dependency Inversion Principle [1] (DIP, or simply DI) is very simple; and like most other simple design principles it is suitable in many different situations. Once you understand it you’ll wonder how you managed without it. The key benefit it brings is control over dependencies – by removing them (or perhaps more correctly – by “inverting” them), and this isn’t just limited to “code” – you’ll find this also opens up new opportunities regarding how you can structure and run the actual development process. Implementing DI and is fairly straight forward and will often involve other design patterns, such as the Factory pattern [2] and Lazy Load pattern [3] ; and embodies several other principles including the Stable Abstractions Principle and Interface Segregation Principle. I’ll be using acronyms where I can, here’s a quick glossary for them. • BL: Business Logic, sometimes referred to as the Business Logic Layer. • DA: Data Access, often referred to as the DAL or Data Access Layer. • DI: can refer to either Dependency Inversion or Dependency Injection – both of which (at least for this article) essentially mean the same thing.
    [Show full text]
  • Isolated Actors for Race-Free Concurrent Programming
    Isolated Actors for Race-Free Concurrent Programming THÈSE NO 4874 (2010) PRÉSENTÉE LE 26 NOVEMBRE 2010 À LA FACULTÉ INFORMATIQUE ET COMMUNICATIONS LABORATOIRE DE MÉTHODES DE PROGRAMMATION 1 PROGRAMME DOCTORAL EN INFORMATIQUE, COMMUNICATIONS ET INFORMATION ÉCOLE POLYTECHNIQUE FÉDÉRALE DE LAUSANNE POUR L'OBTENTION DU GRADE DE DOCTEUR ÈS SCIENCES PAR Philipp HALLER acceptée sur proposition du jury: Prof. B. Faltings, président du jury Prof. M. Odersky, directeur de thèse Prof. D. Clarke, rapporteur Prof. V. Kuncak, rapporteur Prof. P. Müller, rapporteur Suisse 2010 ii Abstract Message-based concurrency using actors has the potential to scale from multi- core processors to distributed systems. However, several challenges remain until actor-based programming can be applied on a large scale. First, actor implementations must be efficient and highly scalable to meet the demands of large-scale distributed applications. Existing implementations for mainstream platforms achieve high performance and scalability only at the cost of flexibility and ease of use: the control inversion introduced by event-driven designs and the absence of fine-grained message filtering complicate the logic of application programs. Second, common requirements pertaining to performance and interoperability make programs prone to concurrency bugs: reusing code that relies on lower-level synchronization primitives may introduce livelocks; passing mutable messages by reference may lead to data races. This thesis describes the design and implementation of Scala Actors. Our sys- tem offers the efficiency and scalability required by large-scale production sys- tems, in some cases exceeding the performance of state-of-the-art JVM-based ac- tor implementations. At the same time, the programming model (a) avoids the control inversion of event-driven designs, and (b) supports a flexible message re- ception operation.
    [Show full text]
  • 1. Difference Between Factory Pattern and Abstract Factory Pattern S.No
    1. Difference between Factory Pattern and Abstract Factory Pattern S.No Factory Pattern Abstract Factory Pattern 1 Create object through inheritance Create object through composition 2 Produce only one product Produce families of products 3 Implements code in the abstract creator Concrete factories implements factory that make use of the concrete type that method to create product sub class produces 2.Difference between Abstract Factory Pattern And Builder Pattern S.No Builder Pattern Abstract Factory Pattern 1 In Builder Pattern, there will be one Abstract Factory Pattern will return the Director class which will instruct Builder instance directly. class to build the different parts/properties of our object and finally retrieve the object. 2 It will have reference to the created It does not keep the track of it's created object. object. 3.Difference between Builder Pattern And Composite Pattern S.No Builder Pattern Composite Pattern 1 It is used to create group of objects of It creates Parent - Child relations between predefined types. our objects. 4.Difference between MVC and MVP S.No MVP MVC 1 MVP is a bit more complex to MVC is easier to implement than MVP. implement than MVC .Also, it has additional layer for view interfaces. 2 The request is always received by the The request is received by the controller View and delegated to the presenter which in turn gets the required data and which in turn gets the data does the loads up the appropriate view processing 3 The presentation and view logic an be The controller logic can be unit tested.
    [Show full text]
  • Scala-Language.Pdf
    Scala Language #scala Table of Contents About 1 Chapter 1: Getting started with Scala Language 2 Remarks 2 Versions 2 Examples 3 Hello World by Defining a 'main' Method 3 Hello World by extending App 4 Delayed Initialization 4 Delayed Initialization 4 Hello World as a script 5 Using the Scala REPL 5 Scala Quicksheet 6 Chapter 2: Annotations 8 Syntax 8 Parameters 8 Remarks 8 Examples 8 Using an Annotation 8 Annotating the main constructor 8 Creating Your Own Annotations 9 Chapter 3: Best Practices 11 Remarks 11 Examples 11 Keep it simple 11 Don't pack too much in one expression. 11 Prefer a Functional Style, Reasonably 12 Chapter 4: Case Classes 13 Syntax 13 Examples 13 Case Class Equality 13 Generated Code Artifacts 13 Case Class Basics 15 Case Classes and Immutabilty 15 Create a Copy of an Object with Certain Changes 16 Single Element Case Classes for Type Safety 16 Chapter 5: Classes and Objects 18 Syntax 18 Examples 18 Instantiate Class Instances 18 Instantiating class with no parameter: {} vs () 19 Singleton & Companion Objects 20 Singleton Objects 20 Companion Objects 20 Objects 21 Instance type checking 21 Constructors 23 Primary Constructor 23 Auxiliary Constructors 24 Chapter 6: Collections 25 Examples 25 Sort A List 25 Create a List containing n copies of x 26 List and Vector Cheatsheet 26 Map Collection Cheatsheet 27 Map and Filter Over A Collection 28 Map 28 Multiplying integer numbers by two 28 Filter 28 Checking pair numbers 28 More Map and Filter examples 29 Introduction to Scala Collections 29 Traversable types 30 Fold 31 Foreach 32 Reduce 32 Chapter 7: Continuations Library 34 Introduction 34 Syntax 34 Remarks 34 Examples 34 Callbacks are Continutations 34 Creating Functions That Take Continuations 35 Chapter 8: Currying 37 Syntax 37 Examples 37 A configurable multiplier as a curried function 37 Multiple parameter groups of different types, currying parameters of arbitrary positions 37 Currying a function with a single parameter group 37 Currying 38 Currying 38 When to use Currying 39 A real world use of Currying.
    [Show full text]