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

  1. 280 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e 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

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Design Patterns and Best Practices in Java è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Design Patterns and Best Practices in Java di Kamalmeet Singh, Adrian Ianculescu, LUCIAN-PAUL TORJE in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Ciencia de la computación e Programación en Java. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781786469014

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 programmingcreated, 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...

Indice dei contenuti