Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Functional Programming with C#

You're reading from   Functional Programming with C# Unlock coding brilliance with the power of functional magic

Arrow left icon
Product type Paperback
Published in Jul 2024
Publisher Packt
ISBN-13 9781805122685
Length 258 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Alex Yagur Alex Yagur
Author Profile Icon Alex Yagur
Alex Yagur
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Part 1:Foundations of Functional Programming in C#
2. Chapter 1: Getting Started with Functional Programming FREE CHAPTER 3. Chapter 2: Expressions and Statements 4. Chapter 3: Pure Functions and Side Effects 5. Chapter 4: Honest Functions, Null, and Option 6. Part 2:Advanced Functional Techniques
7. Chapter 5: Error Handling 8. Chapter 6: Higher-Order Functions and Delegates 9. Chapter 7: Functors and Monads 10. Part 3:Practical Functional Programming
11. Chapter 8: Recursion and Tail Calls 12. Chapter 9: Currying and Partial Application 13. Chapter 10: Pipelines and Composition 14. Part 4:Conclusion and Future Directions
15. Chapter 11: Reflecting and Looking Ahead 16. Index 17. Other Books You May Enjoy

How to use expressions for clear and simple code

Using short and clear code makes it easy to understand what it’s doing. It’s also easier for you and others to read later on. Using expressions in C# can help us do this. Let’s learn how to shape our code with expressions.

The power of expressions – improving readability and maintainability

Expressions support the idea of immutability, a cornerstone of functional programming. Since expressions evaluate to a value and don’t modify the state of our program, they allow us to write code that’s less prone to bugs, easier to reason about, and simple to test.

One day, Steve received a phone call from his old friend Irene, a renowned author of children’s books. She had begun to notice that books with longer titles seemed to be more popular. To test her theory, she gathered the titles of all the top-selling books and asked Steve to develop a program to calculate the average title length associated with popularity.

Initially, Steve created the program in the manner he was accustomed to:

double averageLength = 0;
foreach (string title in bookTitles)
{
    int titleLength = title.Length;
    averageLength += titleLength;
}
averageLength /= bookTitles.Length;

However, the code looked wordy, and he decided to practice a functional approach and rewrite the code. He replaced the foreach loop with a simple Average expression that computes the average character count:

var averageLength = bookTitles.Average(title => title.Length);

With what almost seemed like magic, all these computations became just a single line of code. One line of more functional and concise code using expressions instead of statements.

Techniques to convert statements to expressions

A great step toward embracing functional programming in C# is turning your statements into expressions where possible. As we just saw, LINQ (which stands for Language INtegrated Query) can be a powerful tool in this transformation.

In the previous example, we used the Average method from LINQ. These are extension methods available for any IEnumerable<T>, allowing us to perform complex operations on collections with simple, expressive code.

We can further leverage other LINQ methods, such as Where for filtering, OrderBy for sorting, and Aggregate for reducing a collection to a single value.

Also, the code can be transformed to comply with the functional approach even without LINQ methods. For example, we can convert if statements into a conditional operator:

// If-else statement
string bookStatus;
if (pageCount > 300)
{
     bookStatus = "Long read";
}
else
{
     bookStatus = "Quick read";
}
// Conditional operator
string bookStatus = pageCount > 300 ? "Long read" : "Quick read";

Moreover, all for, while, foreach, and so on loops can be replaced with recursive methods, which will be expressions when run. In addition, we can use the Result type instead of exceptions and higher-order functions, which will be discussed in later chapters.

Guided exercise – refactoring code using expressions

Emily approached Steve with a request to help her create a program that would display the view count of her YouTube videos. However, Emily’s channel comprises both private and public videos, and she was interested in counting views only for her public ones.

Steve wrote a program in which the primary method of counting views looked like this:

string GetPublicVideosViewsMessage(IEnumerable<Video> videos)
{
     int totalPublicViews = 0;
     foreach (Video video in videos)
     {
          if (video.IsPublic)
          {
               totalPublicViews += video.Views;
          }
     }
     return $"Public videos have {totalPublicViews} views";
}

Then, Steve thought he should use this chance to get better at using the functional approach and expressions instead of statements. So, he made changes to his code using expressions and LINQ methods to make the code clearer and shorter. Now the new version looks like this:

string GetPublicVideosViewsMessage(IEnumerable<Video> videos)
{
     var totalPublicViews = videos
               .Where(v => v.IsPublic)
               .Sum(v => v.Views);
     return $"Public videos have {totalPublicViews} views";
}

Here’s what we changed:

  • The if statement has been replaced with the Where method. This method filters out the elements that do not satisfy a certain condition – in this case, where v.IsPublic is false.
  • The loop that manually adds each video’s views to totalPublicViews has been replaced with the Select method. This method transforms each element – in this case, it takes each video (v) and transforms it into its view count (v.Views).
  • Finally, the Sum method adds up the views from each of the public videos to get the total.

By using LINQ methods and expressions, the resulting code is clearer, more declarative, and more concise. We can now see at a glance what the code does – calculate the total number of views for all public videos – rather than how it does it. This is the power of expressions in C# – they allow for cleaner, more human-readable code.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image