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

Buch teilen
  1. 280 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
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

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Design Patterns and Best Practices in Java als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Design Patterns and Best Practices in Java von Kamalmeet Singh, Adrian Ianculescu, LUCIAN-PAUL TORJE im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Computer Science & Programming in Java. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
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...

Inhaltsverzeichnis