front matter

preface

Functional programming (FP) has become an important and exciting part of mainstream programming. The majority of new languages and frameworks created in the 2010s are functional, leading some to predict that the future of programming is functional. Meanwhile, popular object-oriented (OO) languages like C# and Java have seen the introduction of more functional features with every new release, enabling a multiparadigm programming style. And yet, adoption in the C# community has been slow. Why is this so? One reason, I believe, is the lack of good literature:

  • Most FP literature is written in and for functional languages, especially Haskell. For developers with a background in OOP, this poses a programming-language barrier to learning FP concepts. Even though many of the concepts apply to a multiparadigm language like C#, learning a new paradigm and a new language at once is a tall order.

  • Even more importantly, most of the books in the literature tend to illustrate functional techniques and concepts with examples from the domains of mathematics or computer science. For the majority of programmers who work on Line of Business (LOB) applications day in and day out, this creates a domain gap and leaves them wondering how relevant these techniques may be for real-world applications.

These shortcomings posed major stumbling blocks in my own path to learning FP. After tossing aside the n-th book that explained something known as currying by showing how the add function can be curried with the number 3, creating a function that can add 3 to any number (can you think of any application where this would be even remotely useful?), I decided to pursue my own research path. This involved learning half a dozen functional languages and experimenting to find out which concepts from FP could be effectively applied in C# and in the kind of applications most developers are paid to write. My research culminated in the writing of this book.

This book bridges the language gap for C# developers by showing how you can leverage functional techniques in this language. It also bridges the domain gap by showing how functional techniques can be applied to typical business scenarios. I take a pragmatic approach and cover functional techniques to the extent that they’re useful in a typical LOB application scenario and dispense with most of the theory behind FP. Ultimately, you should care about FP because it gives you the following:

  • Power—This simply means that you can get more done with less code. FP raises the level of abstraction, allowing you to write high-level code while freeing you from low-level technicalities that add complexity but no value.

  • Safety—FP is adverse to state mutation. This means that a program written in the functional style is unlikely to go into an invalid state. Furthermore, a conservative approach to state mutation is extremely beneficial when dealing with concurrency. A program written in the imperative style may work well in a single-threaded implementation but cause all sorts of bugs when concurrency comes in. Functional code offers much better guarantees in concurrent scenarios, so it’s only natural that we’re seeing a surge of interest in FP in the era of multicore processors.

  • Clarity—We spend more time maintaining and consuming existing code than writing new code, so it’s important that our code be clear and intention-revealing. As you learn to think functionally, achieving this clarity becomes more natural.

If you’ve programmed in an OO style for some time, it may take a bit of effort and willingness to experiment before the concepts in this book come to fruition. To make sure learning FP is an enjoyable and rewarding process, I have two recommendations:

  • Be patient. You may have to read some sections more than once. You may put the book down for a few weeks and find that when you pick it up again, something that seemed obscure suddenly starts to make sense.

  • Experiment in code. You won’t learn unless you get your hands dirty. The book provides many examples and exercises, and many of the code snippets can be tested in the REPL.

Your colleagues may be less eager to explore than you. Expect them to protest at your adoption of this new style and to look perplexedly at your code and say things like, “Why not just do x?” (where x is boring, obsolete, and usually harmful). Don’t discuss. Just sit back and watch them eventually turn around and use your techniques to solve issues they run into again and again.

acknowledgments

I’d like to thank Paul Louth, who not only provided inspiration through his language-ext library (from which I borrowed many good ideas) but also graciously reviewed the book at various stages.

Manning’s thorough editorial process ensured that the quality of this book is infinitely better than if I had been left to my own means. For this, I’d like to thank the team that collaborated on the book, including Mike Stephens, development editor Marina Michaels, technical editor René van den Berg, project manager Deirdre Hiam, and proofer Melody Dolab.

Special thanks to Daniel Marbach and Tamir Dresher for their technical insights, as well as to all those who took part in the peer reviews, including David Paccoud, Foster Haines, George Onofrei, Goetz Heller, Oliver Forral, Jeremy Caney, Kent Spillner, Matt Van Winkle, Jedidja Bourgeois, Mark Elston, Najeeb Arif, Oliver Korten, and Robert Wilk.

Thanks to Scott Wlaschin for sharing his articles at http://fsharpforfunandprofit.com and to the many other members of the FP community, who share their knowledge and enthusiasm through articles, blogs, and open source.

about this book

This book aims to show how you can leverage functional techniques in C# to write code that is concise, elegant, robust, and maintainable.

Who should read this book?

This book is for an ambitious breed of developer. You know .NET and C# or a similar language like Java, Swift, or Kotlin. You have experience developing real-world applications and are familiar with OOP concepts, patterns, and best practices. But, you’re looking to expand your arsenal by learning functional techniques so that you can make the most out of C# as a multiparadigm language.

If you’re trying or planning to learn a functional language, this book will also be hugely valuable because you’ll learn how to think functionally in a language you’re familiar with. Changing the way you think is the hard part; once that’s achieved, learning the syntax of any particular language is relatively easy.

How this book is organized: A road map

The book consists of 19 chapters divided into 4 parts:

  • Part 1 covers the basic principles of functional programming. We’ll start by looking at what functional programming is and how C# supports programming in a functional style. We’ll then look at the power of higher-order functions and the importance of pure functions. By the end of part 1, you’ll have both the conceptual and practical tools to start learning more specific functional techniques.

  • Part 2 shows some practical applications of functional techniques: how to design types and function signatures and how simple functions can be composed into complex programs. By the end of part 2, you’ll have a good feel for what a program written in a functional style looks like and for the benefits that this style has to offer.

  • With these basic concepts covered, we’ll pick up some speed in part 3 and move on to wider-reaching concerns such as functional error handling, modularizing and composing an application, and the functional approach to understanding state and representing change. By the end of part 3, you’ll have acquired a set of tools enabling you to effectively tackle many programming tasks using a functional approach.

  • Part 4 tackles more advanced topics including lazy evaluation, stateful computations, asynchrony, data streams, and concurrency. Each chapter in part 4 introduces important techniques that have the potential to completely change the way you write and think about software.

You’ll find a more detailed breakdown of the topics in each chapter and a representation of what chapters are required before reading any particular chapter inside the front cover.

Coding for real-world applications

The book aims to stay true to real-world scenarios. To do this, many examples deal with practical tasks such as reading configuration, connecting to a database, validating HTTP requests, and so on—things you may already know how to do, but that you’ll see with the fresh perspective of functional thinking.

Throughout the book, I use a long-running example to illustrate how FP can help when writing LOB applications. For this, I’ve chosen an online banking application for the fictitious Bank of Codeland (BOC)—naff, I know, but at least it has the obligatory three-letter acronym. Because most people have access to an online banking facility, it should be easy to imagine the required functionality and see how the problems discussed are relevant to real-world applications.

I use several other scenarios to illustrate how to solve typical programming problems in a functional style. The constant back and forth between practical examples and FP concepts will, hopefully, help bridge the gap between theory and practice, something I found wanting in the existing literature.

Leveraging functional libraries

A language like C# may have functional features, but to fully leverage these, you’ll often use libraries that facilitate common tasks. In this book, you’ll learn about

  • System.Linq—Yes, in case you didn’t know, it’s a functional library! I assume you’re familiar with it, given that it’s such an important part of .NET.

  • System.Collections.Immutable—This is a library of immutable collections, which we’ll start using in chapter 11.

  • System.Interactive and System.Reactive—These libraries (you may know them as the interactive extensions and reactive extensions for .NET) allow you to work with data streams, which we’ll discuss in chapters 16 and 18.

This leaves out plenty of other important types and functions that are staples of FP. As a result, several independent developers have written libraries to fill those gaps. To date, the most complete of these is language-ext, a library written by Paul Louth to improve the C# developer’s experience when coding functionally.1

In the book, I don’t use language-ext directly; instead, I’ll show you how I developed my own library of functional utilities, called LaYumba.Functional, even though it largely overlaps with language-ext. This is pedagogically more useful for several reasons:

  • The code will remain stable after the book is published.

  • You get to look under the hood and see that powerful functional constructs are deceptively simple to define.

  • You can concentrate on the essentials. I’ll show you the constructs in their purest form so that you won’t be distracted by the details and edge cases that a full-fledged library addresses.

About the code

This second edition of Functional Programming in C# uses C# 10 and .NET 6.2 Many, if not all, of the techniques can be applied in previous versions of the language, although doing so usually involves some extra typing. The appendix shows specifically how to work with immutable data and pattern matching if you’re working with earlier versions of C# that don’t include these as language features.

You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/functional-programming-in-c-sharp-second-edition. You can execute many of the shorter snippets in a REPL, thereby gaining hands-on practice with immediate feedback. The more extended examples are available for download at https://github.com/la-yumba/functional-csharp-code-2, along with the exercises’ setup and solutions. You can also download the book’s source code from www.manning.com/books/functional-programming-in-c-sharp-second-edition.

Code listings in the book focus on the topic being discussed and therefore may omit using statements, namespace declarations, trivial constructors, or sections of code that appeared in a previous listing and remain unchanged. If you’d like to see the full, compiling version of a listing, you’ll find it in the code repository.

liveBook discussion forum

Purchase of Functional Programming in C#, Second Edition includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/functional-programming-in-c-sharp-second-edition/welcome/v-7/. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/#!/discussion.

Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.

about the author

Enrico Buonanno obtained an MS in Computer Science from Columbia University in 2001 and has been working as a software developer and architect ever since. He’s worked on mission-critical projects for prestigious companies in FinTech (including the Bank for International Settlements, Barclays, and UBS) and other technology-driven businesses.


1 language-ext is open source and available on GitHub and NuGet: https://github.com/louthy/language-ext.

2 C# 10 and .NET 6 are still in preview at the time of writing, so some discrepancies are possible. These will be pointed out where relevant in the book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.42.163