Kotlin Design Patterns and Best Practices - Alexey Soshin - E-Book

Kotlin Design Patterns and Best Practices E-Book

Alexey Soshin

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book shows you how easy it can be to implement traditional design patterns in the modern multi-paradigm Kotlin programming language, and takes you through the new patterns and paradigms that have emerged.

This second edition is updated to cover the changes introduced from Kotlin 1.2 up to 1.5 and focuses more on the idiomatic usage of coroutines, which have become a stable language feature. You'll begin by learning about the practical aspects of smarter coding in Kotlin, as well as understanding basic Kotlin syntax and the impact of design patterns on your code.

The book also provides an in-depth explanation of the classical design patterns, such as Creational, Structural, and Behavioral families, before moving on to functional programming. You'll go through reactive and concurrent patterns, and finally, get to grips with coroutines and structured concurrency to write performant, extensible, and maintainable code.

By the end of this Kotlin book, you'll have explored the latest trends in architecture and design patterns for microservices. You’ll also understand the tradeoffs when choosing between different architectures and make informed decisions.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 357

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Kotlin Design Patterns and Best Practices Second Edition

Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin

Alexey Soshin

BIRMINGHAM—MUMBAI

Kotlin Design Patterns and Best Practices Second Edition

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Aaron Lazar

Publishing Product Manager: Sathyanarayanan Ellapulli

Senior Editor: Rohit Singh

Content Development Editor: Rosal Colaco

Technical Editor: Karan Solanki

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Jyoti Chauhan

Marketing Coordinator: Sonakshi Bubbar

First published: June 2018

Second edition: December 2021

Production reference: 1131221

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80181-572-7

www.packt.com

To Lula Leus, my constant source of inspiration.

To my mentor, Lior Bar On. Without you, I would have never started writing.

– Alexey Soshin

Foreword

Kotlin just turned 10 recently. It's a relatively young programming language. However, Kotlin stands on the shoulders of giants: many features and best practices have been borrowed from other programming languages. Thanks to this, we can reuse the knowledge that we have learned elsewhere when developing Kotlin programs.

Design patterns are part of the best practices that will help developers to use Kotlin efficiently. It is great to see the effort in describing the patterns that comes from the passionate people in the Kotlin community. Alexey Soshin has put a lot of effort into sharing his knowledge, not only in this book but also in interactive courses and other media.

Kotlin Design Patterns and Best Practices provides a gentle introduction to the Kotlin programming language. It guides you through the vocabulary of design patterns chapter by chapter. If you are a Java developer and have used design patterns previously, the book will show you how to do the same with Kotlin.

Design patterns appeared in the era of object-oriented languages such as C++ and Java. Kotlin, however, provides language features that allow developers to program in a functional style. This book captures the benefits of the functional approach and explains how to apply it with Kotlin.

A sizable part of this book covers asynchronous programming with Kotlin coroutines. Today, it's essential to understand how to write concurrent programs and use the asynchronous programming approach to implement concurrency in your programs. This understanding is also critical for designing these programs correctly. Concurrency design patterns will help you understand how to develop concurrent programs better.

This book will give you a solid grounding for becoming familiar with Kotlin and best practices for building programs with this modern programming language. I salute the author for his effort and enthusiasm!

Anton Arhipov

Kotlin Developer Advocate at JetBrains

Contributors

About the author

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.

About the reviewers

Aditya Kumar is an Android developer with around 4 years of experience in this domain. In his journey so far, he has worked with companies such as Microsoft and Uber. He has helped in developing a few key components of many projects and is always known for his contribution to the Kotlin community. Besides Android development, he is also interested in other technologies such as engineering systems and backend engineering and is very keen on exploring those aspects in the future.

Nicola Corti is a Google Developer Expert for Kotlin. He has been working with the language since before version 1.0 and he is the maintainer of several open source libraries and tools for mobile developers (Detekt, Chucker, AppIntro, and so on). He's currently working in the React Native team at Meta in London, UK, helping to build and ship one of the most popular cross-platform frameworks for mobile. Furthermore, he is an active member of the developer community. His involvement ranges from speaking at international conferences to being a member of CFP committees and supporting developer communities across Europe.

Joost Heijkoop is an independent consultant, a seasoned JVM and frontend developer working to make things better and tackle hard problems, and an organizer at Kotlin.amsterdam and Amsterdam.scala, and is always happy to help.

Table of Contents

Preface

Section 1: Classical Patterns

Chapter 1: Getting Started with Kotlin

Technical requirements

Basic language syntax and features

Multi-paradigm language

Understanding Kotlin code structure

Naming conventions

Packages

Comments

Hello Kotlin

Understanding types

Basic types

Type inference

Values

Comparison and equality

Declaring functions

Null safety

Reviewing Kotlin data structures

Lists

Sets

Maps

Mutability

Alternative implementations for collections

Arrays

Control flow

The if expression

The when expression

Working with text

String interpolation

Multiline strings

Loops

for-each loop

The for loop

The while loop

Classes and inheritance

Classes

Interfaces

Abstract classes

Visibility modifiers

Inheritance

Data classes

Extension functions

Introduction to design patterns

What are design patterns?

Why use design patterns in Kotlin?

Summary

Questions

Chapter 2: Working with Creational Patterns

Technical requirements

Singleton

Factory Method

Static Factory Method

Abstract Factory

Casts

Subclassing

Smart casts

Variable shadowing

Collection of Factory Methods

Builder

Fluent setters

Default arguments

Prototype

Starting from a prototype

Summary

Questions

Chapter 3: Understanding Structural Patterns

Technical requirements

Decorator

Enhancing a class

The Elvis operator

The inheritance problem

Operator overloading

Caveats of the Decorator design pattern

Adapter

Adapting existing code

Adapters in the real world

Caveats of using adapters

Bridge

Bridging changes

Type aliasing

Constants

Composite

Secondary constructors

The varargs keyword

Nesting composites

Facade

Flyweight

Being conservative

Saving memory

Caveats of the Flyweight design pattern

Proxy

Lazy delegation

Summary

Questions

Chapter 4: Getting Familiar with Behavioral Patterns

Technical requirements

Strategy

Fruit arsenal

Citizen functions

Iterator

State

Fifty shades of State

State of the nation

Command

Undoing commands

Chain of Responsibility

Interpreter

We need to go deeper

A language of your own

Call suffix

Mediator

The middleman

Mediator flavors

Mediator caveats

Memento

Visitor

Writing a crawler

Template method

Observer

Animal choir example

Summary

Questions

Section 2: Reactive and Concurrent Patterns

Chapter 5: Introducing Functional Programming

Technical requirements

Reasoning behind the functional approach

Immutability

Immutable collections

The problem with shared mutable state

Tuples

Functions as values

Learning about higher-order functions

Higher-order functions in a standard library

The it notation

Closures

Pure functions

Currying

Memoization

Using expressions instead of statements

Pattern matching

Recursion

Summary

Questions

Chapter 6: Threads and Coroutines

Technical requirements

Looking deeper into threads

Thread safety

Why are threads expensive?

Introducing coroutines

Starting coroutines

Jobs

Coroutines under the hood

Setting timeouts

Dispatchers

Structured concurrency

Summary

Questions

Chapter 7: Controlling the Data Flow

Technical requirements

Reactive principles

Responsive principle

Resilient principle

Elastic principle

Message-driven principle

Higher-order functions on collections

Mapping elements

Filtering elements

Finding elements

Executing code for each element

Summing up elements

Getting rid of nesting

Exploring concurrent data structures

Sequences

Channels

Flows

Summary

Questions

Chapter 8: Designing for Concurrency

Technical requirements

Deferred Value

Barrier

Using data classes as barriers

Scheduler

Creating your own schedulers

Pipeline

Composing a pipeline

Fan Out

Fan In

Racing

Unbiased select

Mutex

Sidekick channel

Summary

Questions

Section 3: Practical Application of Design Patterns

Chapter 9: Idioms and Anti-Patterns

Technical requirements

Using the scope functions

Let function

Apply function

Also function

Run function

With function

Type checks and casts

An alternative to the try-with-resources statement

Inline functions

Implementing Algebraic Data Types

Reified generics

Using constants efficiently

Constructor overload

Dealing with nulls

Making asynchronicity explicit

Validating input

Preferring sealed classes over enums

Summary

Questions

Chapter 10: Concurrent Microservices with Ktor

Technical requirements

Getting started with Ktor

Routing requests

Testing the service

Modularizing the application

Connecting to a database

Creating new entities

Making the tests consistent

Fetching entities

Organizing routes in Ktor

Achieving concurrency in Ktor

Summary

Questions

Chapter 11: Reactive Microservices with Vert.x

Technical requirements

Getting started with Vert.x

Routing in Vert.x

Verticles

Handling requests

Subrouting the requests

Testing Vert.x applications

Working with databases

Managing configuration

Understanding Event Loop

Communicating with Event Bus

Sending JSON over Event Bus

Summary

Questions

Assessments

Other Books You May Enjoy

Section 1: Classical Patterns

In this section, we will cover the basic syntax of the Kotlin programming language and the implementation of all the classical design patterns in Kotlin.

The classical design patterns deal with three major problems in system design: how to create objects efficiently, how to encapsulate object hierarchies, and how to make object behavior more dynamic.

We'll discuss which design patterns come as part of the language, and how to implement those that don't.

This section comprises the following chapters:

Chapter 1, Getting Started with Kotlin Chapter 2, Working with Creational PatternsChapter 3, Understanding Structural PatternsChapter 4, Getting Familiar with Behavioral Patterns