39,59 €
Functional programming makes your application faster, improves performance, and increases your productivity. C# code is written at a higher level of abstraction, so that code will be closer to business requirements, abstracting away many low-level implementation details.
This book bridges the language gap for C# developers by showing you how to create and consume functional constructs in C#. We also bridge the domain gap by showing how functional constructs can be applied in business scenarios. We’ll take you through lambda expressions and extension methods, and help you develop a deep understanding of the concepts and practices of LINQ and recursion in C#.
By the end of the book, you will be able to write code using the best approach and will be able to perform unit testing in functional programming, changing how you write your applications and revolutionizing your projects.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 380
Veröffentlichungsjahr: 2016
Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: January 2017
Production reference: 1281216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78528-222-5
www.packtpub.com
Author
Wisnu Anggoro
Copy Editor
Stuti Srivastava
Reviewer
Haridas Nair
Project Coordinator
Izzat Contractor
Commissioning Editor
Kunal Parikh
Proofreader
Safis Editing
Acquisition Editor
Denim Pinto
Indexer
Rekha Nair
Content Development Editor
Priyanka Mehta
Production Coordinator
Shraddha Falebhai
Technical Editors
Bhavin Savalia
Dhiraj Chandanshive
Wisnu Anggoro is a Microsoft Certified Professional in C# programming and an experienced C/C++ developer. He has also authored Boost.Asio C++ Network Programming - Second Edition, published by Packt. He has been programming since he was in junior high school (about 20 years ago) and started developing computer applications using the BASIC programming language in the MS-DOS environment. He has a solid experience of smart card programming as well as desktop and web application programming, such as designing, developing, and supporting live use applications for SIM Card Operating System Porting, personalization, PC/SC communication, and other smart card applications that require the use of C# and C/C++. He is currently a senior smart card software engineer at CIPTA, an Indonesian company that specializes in the innovation and technology of smart cards. You can write to him at [email protected].
First and above all, I praise God, the almighty, for providing me with this opportunity and granting me the capability to proceed successfully. To my wife, dear Vivin, without whose support and encouragements I could not have finished this book. Thank you for reminding me of the deadline of each chapter, so I could always stay on the writing process schedule. To my beloved sons, the source of my joy: Olav, who makes my life worth living by giving me much happiness, and Oliver, who was born just after I submitted the draft of chapter 5. His first cry boosted my spirit to finish this book. And a thank you to my parents and family for their inspiration.
Also, I would like to express my gratitude to the following individuals who supported me in writing this book:
The team at Packt, especially Denim Pinto, my acquisition editor, who invited me to author this book; Priyanka Mehta, my content development editor, for her constant effort in encouraging me to supply the best content for this book; and to all reviewers who have given input and suggestions to make the content of this book much better.
My best mentor, teacher, and superior at CIPTA (www.cipta.com), Benediktus Dwi Desiyanto, who never let me stop learning new things and always encourages me to catch my dream. Hope this book can be the way to make all my dreams come true.
Chief Executive Officer of CIPTA, Steven Chandra, for providing me with a new Amazon Kindle. Since then, the number of books I have read has increased. The insight from the books I have read was helpful while I wrote this book.
Chief Human Capital Officer of CIPTA, Budi Setiawan, for appreciating my work in authoring my previous book and inviting me to join the C-MAG (CIPTA Magazine) press team. It helped me a lot in enhancing my writing skills.
All my friends and colleagues at CIPTA, especially Muhammad Abdurochman Sanjaya and Seno Budi Utomo, for the insight of C# programming in developing a smart card application. It helped me develop the application I presented in this book. And Andre Tampubolon, for the insight of functional programming in Haskell.
Dave Fancher, the author of The Book of F#, thank you for your amazing site, https://davefancher.com/, my one-stop place to learn functional programming. His website inspired my authoring of this book.
Haridas Nair works as a software architect within the Architecture Practice, providing both technical and solution architecture. He is responsibile for defining, documenting, and articulating functional and nonfunctional scope.
He manages various project teams varying in size and location in USA, UK, and offshore (India). The day-to-day duties range from assisting in technical presales activities, responding to RFPs, through to high-level and detailed design phases to actual implementation on enterprise-scale projects.
I would like to thank Praseed Pai for introducing me to this publisher. I would also like to thank the publisher for giving me this opportunity.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously--that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].
Some of us may be used to developing an application using the object orientation programming technique and don’t care about the functional programming technique. However, there are benefits to using functional programming. One of the benefits is that we will get a new perspective on our programming code since the function in functional programming is identical to a mathematical function. Because it's identical to a mathematical function, the function in functional programming contains no side-effects, which means that the function invocation will have no effect on other functions in the class. We will discuss more details about the benefits and other things related to functional programming in this book.
Chapter 1, Tasting Functional Style in C#, introduces the functional programming approach by discussing its concepts and the comparison between functional and imperative programming. We also try to refactor a simple imperative code into a functional approach.
Chapter 2, Walkthrough Delegates, covers the definition, syntax, and use of delegates. We also discuss the variance of delegates and the built-in delegate.
Chapter 3, Expressing Anonymous Methods with Lambda Expressions, walks us through the concept of delegates and uses it to create and use an anonymous method. After we dig through the anonymous method, we can transform it into a lambda expression and then apply it to functional programming.
Chapter 4, Extending Object Functionality with Extension Methods, elaborates the benefits of using the extension method in functional programming. Before that, we discuss the use of the extension method and also discuss how to get this new method in IntelliSense. Also, we try to invoke the extension method from other assemblies.
Chapter 5, Querying Any Collection Easily with LINQ, enumerates the LINQ operator provided by C# and compares the two LINQ syntaxes: Fluent Syntax and Query Expression Syntax. We also discuss deferred execution in the LINQ process.
Chapter 6, Enhancing the Responsiveness of the Functional Program with Asynchronous Programming, covers asynchronous programming for the functional approach. It will explain the Asynchronous Programming Model and the Task-based Asynchronous pattern.
Chapter 7, Learning Recursion, explains the advantages of recursion over the loop sequence. We also discuss direct and indirect recursion in this chapter.
Chapter 8, Optimizing the Code Using Laziness and Caching Techniques, covers the technique used to optimize the code in the functional approach. We talk about laziness thinking and the caching technique in order to optimize our code.
Chapter 9, Working with Pattern, covers the advantages of using patterns compared to conventional switch-case operations. We discuss pattern matching and monad in this chapter. We use the pattern matching feature, which is the new feature provided by C# 7.
Chapter 10, Taking an Action in C# Functional Programming, walks us through developing functional code based on given imperative code. We use our learning in the previous chapter to create an application using the functional approach.
Chapter 11, Coding Best Practice and Testing the Functional Code, explains the best practice in the functional approach, including the creation of an honest signature and dealing with the side-effects. We also separate the code into domain logic and mutable shell and then test it using unit testing.
To walk through this book and successfully compile all the source code, we require a personal computer that runs Microsoft Windows 10 (or higher) with Visual Studio Community 2015 Update 3 installed for the running of code in chapters 1-8, 10, 11 and Visual Studio Community 2017 RC (Release Candidate) installed for the running of code in chapter 9. We also need the .NET Framework 4.6.2 unless you need to recode all the source code to run in your current version of .NET Framework. You also need .NET Core 1.0 if you want to compile all code in another platform since all code are compatible with .NET Core 1.0.
This book is suitable for C# developers with basic prior knowledge of C# and with no functional programming experience at all.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
namespace ActionFuncDelegates { public partial class Program { static void Main(string[] args) { //ActionDelegateInvoke(); FuncDelegateInvoke(); } }When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Console.WriteLine("Prime Number from 0 - 49 are:"); foreach (int i in extractedData)Console.Write("{0} \t", i); Console.WriteLine();Any command-line input or output is written as follows:
C:\>dir | moreNew terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "We have a Body property containing {(a * b)}, NodeType containing Lambda, Type containing the Func delegate with three templates."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Functional-CSharp. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
The main difference between functional and imperative programming is that imperative programming produces side effects while functional programming doesn't. In imperative programming, the expressions are evaluated and its resulting value is assigned to variables. So, when we group series of expressions into a function, the resulting value depends upon the state of variables at that point in time. This is called side effects. Because of the continuous changes in state, the order of evaluation matters. In functional programming world, destructive assignment is forbidden and each time an assignment happens a new variable is induced.
For the rest of the discussion in this chapter, we are going to create some code in C#. In order we have the same environment, let's define what we will use in configuration settings. We will use Visual Studio 2015 Community Edition and .NET Framework 4.6.2 in all of the source code we discuss in this book. We will also choose the console application project in order to ease the development of our code since it doesn't need many changes to the settings.
Here is the screenshot of the setting in creating Visual Studio projects we will use:
When we are discussing a source code that has a csproj filename-for instance, FuncObject.csproj-we can find it in one of solution files provided in the sample code. It will be in the Program.cs file. The following is a screenshot of the structure of the project in Visual Studio:
However, sometimes, we have more than one .cs file inside the project file. In this case, we can find the code we are discussing in one of the .cs files inside the project file. For instance, we have a project file named FunctionalCode.csproj. So, when we discuss any source code related to this project file, we can find it from the .cs files inside the project file. The structure of a project file consisting of more than one .cs files is as follows:
As we can see, inside the FunctionalCode.csproj file, not only do we have the Program.cs file, but also Disposable.cs, FunctionalExtension.cs, StringBuilderExtension.cs, and Utility.cs.
We will also find the partial keyword to the classes name in most of our code even though we write the classes in the same file. The purpose is to make the code snippet in this book easy to find in the sample code. By knowing the class name, it will be easier to find the source code in the file.
We also need to install Visual Studio Community 2017 RC since we will use a new feature of C# 7 in Chapter 9, Working with Pattern.