Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Scala Functional Programming Patterns
Scala Functional Programming Patterns

Scala Functional Programming Patterns: Grok and perform effective functional programming in Scala

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Scala Functional Programming Patterns

Chapter 2. Singletons, Factories, and Builders

It may sound funny—and I may be stating the obvious—but everyone needs to be born at some point. Go ahead and have a good laugh at that. It is that obvious. Objects, too, need to be born at some point to do useful work. Objects have a lifetime as well. An object is constructed—and hopefully it does something useful before it eventually dies.

In Java we can see the object such as:

           Point p = new Point(23, 94);

We know what is going on—an object of class point is created; its constructor-invoked p is a reference to this newly created object.

At times, we want explicit control of the object-creation process. There are times when we want to allow creation of only one instance of a class. Creational design patterns deal with object-creation mechanisms. Refer to https://sourcemaking.com/design_patterns/creational_patterns for more information on creational patterns.

Creational patterns help create objects...

Singletons – being one and only one

A singleton is a class of which only a single instance can exist. How do we prevent anyone from creating yet another instance? The solution is to make the constructor inaccessible. Here it is:

public class Singleton {
      // Eager initialization
  private static final Singleton instance = new Singleton(); // 1
 
  private Singleton() { // 2
  /* client code cannot create instance */
 }
 
      // Static factory method 
 public static Singleton getInstance() { // 3
  return instance;
 }

 // Driver code
 public static void main(String[] args) {
  System.out.println(Singleton.getInstance());
  System.out.println(Singleton.getInstance());
 }
}

Dissecting the code:

  • At 1, the static initializer creates the instance—also the final keyword ensures that the instance cannot be redefined.
  • At 2, the constructor access is private, so only the class methods can access it.
  • At 3, the public factory method gives access to the client code.

If you run the Java...

Null Objects – singletons in another garb

One popular form in which singletons are used is the Null Object pattern. Let's see what a Null Object is.

Java gives us the null reference to indicate a missing value. We are not supposed to call a method on it as there is no object. If, erroneously, we do, we are greeted with a Null Pointer Exception (NPE). When we design methods to return nulls, the client code that calls the method needs to check assiduously. This is what a typical null check-based Java code looks like:

       Point p = makeAPoint(); // a method that returns null in some cases
       if (p != null) { // the dreaded null check – onus is on us...
            // We are on sure grounds
       }

The problem is that the onus term is on us to check for a reference being null. Every call to makeAPoint() needs to be checked, as shown earlier. This soon becomes tedious.

Note

The inventor of the null keyword called it his billion-dollar mistake!!! Please see http://www.infoq...

Scala singletons

Scala has singleton objects called companion objects. A companion object is an object with the same name as a class. A companion object also can access private methods and fields of its companion class. Both a class and its companion object must be defined in the same source file. The companion object is where the apply() factory method may be defined. Let's have a look at the following example of a companion class:

class Singleton {  // Companion class
  def m() {
    println("class")
  }         
}

And then its companion object as:

object Singleton { // Companion Object
  def m() {
    println("companion")
  }         
}

It is that simple, when a case class is defined, Scala automatically generates a companion object for it.

The apply() factory method

If a companion object defines an apply() method, the Scala compiler calls it when it sees the class name followed by (). So, for example, when Scala sees something like:

                 Singleton(arg1...

Singletons – being one and only one


A singleton is a class of which only a single instance can exist. How do we prevent anyone from creating yet another instance? The solution is to make the constructor inaccessible. Here it is:

public class Singleton {
      // Eager initialization
  private static final Singleton instance = new Singleton(); // 1
 
  private Singleton() { // 2
  /* client code cannot create instance */
 }
 
      // Static factory method 
 public static Singleton getInstance() { // 3
  return instance;
 }

 // Driver code
 public static void main(String[] args) {
  System.out.println(Singleton.getInstance());
  System.out.println(Singleton.getInstance());
 }
}

Dissecting the code:

  • At 1, the static initializer creates the instance—also the final keyword ensures that the instance cannot be redefined.

  • At 2, the constructor access is private, so only the class methods can access it.

  • At 3, the public factory method gives access to the client code.

If you run the Java program, you...

Null Objects – singletons in another garb


One popular form in which singletons are used is the Null Object pattern. Let's see what a Null Object is.

Java gives us the null reference to indicate a missing value. We are not supposed to call a method on it as there is no object. If, erroneously, we do, we are greeted with a Null Pointer Exception (NPE). When we design methods to return nulls, the client code that calls the method needs to check assiduously. This is what a typical null check-based Java code looks like:

       Point p = makeAPoint(); // a method that returns null in some cases
       if (p != null) { // the dreaded null check – onus is on us...
            // We are on sure grounds
       }

The problem is that the onus term is on us to check for a reference being null. Every call to makeAPoint() needs to be checked, as shown earlier. This soon becomes tedious.

Note

The inventor of the null keyword called it his billion-dollar mistake!!! Please see http://www.infoq.com/presentations...

Left arrow icon Right arrow icon

Key benefits

  • Understand functional programming patterns by comparing them with the traditional object-oriented design patterns
  • Write robust, safer, and better code using the declarative programming paradigm
  • An illustrative guide for programmers to create functional programming patterns with Scala

Description

Scala is used to construct elegant class hierarchies for maximum code reuse and extensibility and to implement their behavior using higher-order functions. Its functional programming (FP) features are a boon to help you design “easy to reason about” systems to control the growing software complexities. Knowing how and where to apply the many Scala techniques is challenging. Looking at Scala best practices in the context of what you already know helps you grasp these concepts quickly, and helps you see where and why to use them. This book begins with the rationale behind patterns to help you understand where and why each pattern is applied. You will discover what tail recursion brings to your table and will get an understanding of how to create solutions without mutations. We then explain the concept of memorization and infinite sequences for on-demand computation. Further, the book takes you through Scala’s stackable traits and dependency injection, a popular technique to produce loosely-coupled software systems. You will also explore how to currying favors to your code and how to simplify it by de-construction via pattern matching. We also show you how to do pipeline transformations using higher order functions such as the pipes and filters pattern. Then we guide you through the increasing importance of concurrent programming and the pitfalls of traditional code concurrency. Lastly, the book takes a paradigm shift to show you the different techniques that functional programming brings to your plate. This book is an invaluable source to help you understand and perform functional programming and solve common programming problems using Scala’s programming patterns.

Who is this book for?

If you have done Java programming before and have a basic knowledge of Scala and its syntax, then this book is an ideal choice to help you to understand the context, the traditional design pattern applicable, and the Scala way. Having previous knowledge of design patterns will help, though it is not strictly necessary.

What you will learn

  • Get to know about functional programming and the value Scala s FP idioms bring to the table
  • Solve day-to-day programming problems using functional programming idioms
  • Cut down the boiler-plate and express patterns simply and elegantly using Scala s concise syntax
  • Tame system complexity by reducing the moving parts
  • Write easier to reason about concurrent code using the actor paradigm and the Akka library
  • Apply recursive thinking and understand how to create solutions without mutation
  • Reuse existing code to compose new behavior
  • Combine the object-oriented and functional programming approaches for effective programming using Scala

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 29, 2015
Length: 298 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985852
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 29, 2015
Length: 298 pages
Edition : 1st
Language : English
ISBN-13 : 9781783985852
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 134.97
Scala Functional Programming Patterns
€41.99
Scala Design Patterns
€45.99
Scala for Data Science
€46.99
Total 134.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Grokking the Functional Way Chevron down icon Chevron up icon
2. Singletons, Factories, and Builders Chevron down icon Chevron up icon
3. Recursion and Chasing your Own Tail Chevron down icon Chevron up icon
4. Lazy Sequences – Being Lazy, Being Good Chevron down icon Chevron up icon
5. Taming Multiple Inheritance with Traits Chevron down icon Chevron up icon
6. Currying Favors with Your Code Chevron down icon Chevron up icon
7. Of Visitors and Chains of Responsibilities Chevron down icon Chevron up icon
8. Traversals – Mapping/Filtering/Folding/Reducing Chevron down icon Chevron up icon
9. Higher Order Functions Chevron down icon Chevron up icon
10. Actors and Message Passing Chevron down icon Chevron up icon
11. It's a Paradigm Shift Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(2 Ratings)
5 star 0%
4 star 50%
3 star 50%
2 star 0%
1 star 0%
cust: Feb 05, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
-gets you up to speed in knowning basics in fp world
Amazon Verified review Amazon
Mark V. Jan 14, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
While this book introduces functional programming principles, it does so without any real plan. Deconstruction and pattern matching are mixed in a chapter on recursion. The book does pick up some pace after the first half, where it does a decent job of introducing flatMap, map, monads and monoids.This book contains a lot of Java (namely unit tests) along with Scala. I feel like the tests should have been written in Scala too, this is a Scala book after all.What annoyed me most about this book, were the links to more information. Instead of explaining the concepts briefly, there are some 10 links provided, such as "Some expensive objects may need to be lazy-initialized. Refer to http://martinfowler.com/bliki/LazyInitialization.html for a very nice introduction to lazy initialization." This makes the book feel unfinished.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.