Design Patterns and Best Practices in Java
eBook - ePub

Design Patterns and Best Practices in Java

A comprehensive guide to building smart and reusable code in Java

Kamalmeet Singh, Adrian Ianculescu, LUCIAN-PAUL TORJE

Share book
  1. 280 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Design Patterns and Best Practices in Java

A comprehensive guide to building smart and reusable code in Java

Kamalmeet Singh, Adrian Ianculescu, LUCIAN-PAUL TORJE

Book details
Book preview
Table of contents
Citations

About This Book

Create various design patterns to master the art of solving problems using Java

Key Features

  • This book demonstrates the shift from OOP to functional programming and covers reactive and functional patterns in a clear and step-by-step manner
  • All the design patterns come with a practical use case as part of the explanation, which will improve your productivity
  • Tackle all kinds of performance-related issues and streamline your development

Book Description

Having a knowledge of design patterns enables you, as a developer, to improve your code base, promote code reuse, and make the architecture more robust. As languages evolve, new features take time to fully understand before they are adopted en masse. The mission of this book is to ease the adoption of the latest trends and provide good practices for programmers.

We focus on showing you the practical aspects of smarter coding in Java. We'll start off by going over object-oriented (OOP) and functional programming (FP) paradigms, moving on to describe the most frequently used design patterns in their classical format and explain how Java's functional programming features are changing them.

You will learn to enhance implementations by mixing OOP and FP, and finally get to know about the reactive programming model, where FP and OOP are used in conjunction with a view to writing better code. Gradually, the book will show you the latest trends in architecture, moving from MVC to microservices and serverless architecture. We will finish off by highlighting the new Java features and best practices. By the end of the book, you will be able to efficiently address common problems faced while developing applications and be comfortable working on scalable and maintainable projects of any size.

What you will learn

  • Understand the OOP and FP paradigms
  • Explore the traditional Java design patterns
  • Get to know the new functional features of Java
  • See how design patterns are changed and affected by the new features
  • Discover what reactive programming is and why is it the natural augmentation of FP
  • Work with reactive design patterns and find the best ways to solve common problems using them
  • See the latest trends in architecture and the shift from MVC to serverless applications
  • Use best practices when working with the new features

Who this book is for

This book is for those who are familiar with Java development and want to be in the driver's seat when it comes to modern development techniques. Basic OOP Java programming experience and elementary familiarity with Java is expected.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Design Patterns and Best Practices in Java an online PDF/ePUB?
Yes, you can access Design Patterns and Best Practices in Java by Kamalmeet Singh, Adrian Ianculescu, LUCIAN-PAUL TORJE in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781786469014
Edition
1

Functional Patterns

The objective of this chapter is to learn about functional patterns and the changes to the traditional patterns added by the introduction of a functional style of programming that is now possible in the most important programming languages. Java 8 brought in functional features that added a new level of abstraction, affecting the way we write some of the object-oriented design patterns, even making some of them irrelevant. In this chapter, we will see how design patterns are changed, or even replaced, by the new language features. In his paper, Design Patterns in Dynamic Languages, Peter Norvig noticed that 16 out of the 23 design patterns are simpler or replaced by existing language features in dynamic languages, such as Dylan. The full paper is available at http://norvig.com/design-patterns/. In this chapter, we are going to see what can be replaced, and how and what the new emerged patterns are. As Peter Norvig said in his paper, Long ago, subroutine call was just a pattern, as languages evolve, expect the patterns to change or be replaced.
To run the code from this chapter, we used the jshell REPL utility available in Java and accessible from $JAVA_HOME/bin/jshell on Linux or %JAVA_HOME%/bin/jshell.exe in Windows.

Introducing functional programming

During the 1930s, the mathematician Alonzo Church developed lambda calculus. This was the starting point for the functional programming paradigm, since it provided the theoretical grounds. The next step was the design of LISP (short for List Programming) in 1958, by John McCarthy. LISP is the first functional programming language, and some of its flavors, such as Common LISP, are still used today.
In functional programming (often abbreviated to FP), functions are first-class citizens; this means that software is built by composing functions, rather than objects, as OOP. This is done in a declarative way, Tell don't ask, by composing functions, promoting immutability, and avoiding the side effects and shared data. This leads to a more concise code that is resilient to changes, predictable, and easier to maintain and read by business people.
Functional code has a higher signal-to-noise ratio; we have to write less code to achieve the same thing as in OOP. By avoiding side effects and data mutations, and relying on data transformation, the system becomes much simpler, and easier to debug and fix. Another benefit is the predictability. We know that the same function for the same input will always give the same output; therefore, it can also be used in parallel computation, called before or after any other function (the CPU/compiler does not need to make assumptions on the call order) and its return value can be cached once calculated, thus improving performance.
Being a declarative type of programming, it focuses more on what needs to be done, in contrast to the imperative style, where the focus is on how it should be done. A sample flow can be seen in the following diagram:
The functional programming paradigm uses the following concepts and principles:
  • Lambda expressions
  • Pure functions
  • Referential transparency
  • First-class functions
  • Higher-order functions
  • Function composition
  • Currying
  • Closure
  • Immutability
  • Functors
  • Applicatives
  • Monads

Lambda expressions

The name comes from lambda calculus, where the Greek letter lambda (λ) is used to bind a term to a function. The lambda terms are either variables (x, for example), abstractions—such as λ.x.M, where M is the function—or applications, where two terms, M and N, are applied one to another. With the constructed (composed) terms, it is now possible to do expression reduction and/or conversion. Lambda-expression reduction can be tested online by using interpreters, such as the one available at Berkeley: https://people.eecs.berkeley.edu/~gongliang13/lambda/.
The following is an example of a lambda-calculus lambda expression for calculating the circle radius square when the x, y coordinates are known:
It is mathematically defined an n-ary function:
The application is as follows:
Here is the curried version (notice the extra reduction step):
The main benefit of using lambda expressions over statements is that lambda expressions can be composed and reduced to simpler forms.
Java 8 introduced lambda expressions (made available before by using anonymous classes) and the implementation makes use of the invoke dynamic introduced in Java 7, instead of anonymous classes for performance (too many generated classes that need to be loaded) and customization (future changes) reasons.

Pure functions

A pure function is a function that has no side effects and its output is the same for the same input (predictable and cacheable). A side effect is an action that modifies the outside context of the function. Examples of this include to the following:
  • Writing to a file/console/network/screen
  • Modifying an outside variable/state
  • Calling a non-pure function
  • Starting a process
Side effects are sometimes unavoidable or even desirable—I/O or low-level operations are examples of code with side effects (von Neumann machines work because of side effects). As a rule of thumb, try to isolate the functions with side effects from the rest of the code. Haskell and other functional programming languages use monads for the task. We will have an introductory section on monads later.
Since the output of a pure function is predictable, it can also be replaced with the cached output; this is why pure functions are said to provide referential transparency. Pure functions are easier to read and understand—in his book, Clean Code, Robert Martin writes:
"Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. ...[Therefore,] making it easy to read makes it easier to write."
Favoring pure functions in the code enhances productivity and allows newcomers to spend less time reading the new code and more time using and fixing it.

Referential transparency

Referential transparency is the property of a function to be replaceable with its return value for the input. The benefits are tremendous, since this favors memorization (caching of the return value) and parallelization of the call to the specific function. Testing such a function is also easy.

First-class functions

First-class functions are functions that can be treated much like the objects from the object-oriented programming—created, stored, used as parameters, and returned as values.

Higher-order functions

Higher-order functions are functions that can take other functions as parameters, create, and return them. They promote code reuse by making use of existing and already-tested small functions. For example, in the following code, we calculate the average in Celsius for the given temperatures in Fahrenheit:
jshell> IntStream.of(70, 75, 80, 90).map(x -> (x - 32)*5/9).average();
$4 ==> OptionalDouble[25.5]
Notice the use of the lambda expression inside the higher-order map function. The s...

Table of contents