A practical example – a book publishing system
Let’s examine an example that demonstrates functional programming concepts using a book publishing system scenario:
public record Book(string Title, string Author, int Year, string Content); // Pure function to validate a book private static bool IsValid(Book book) => !string.IsNullOrEmpty(book.Title) && !string.IsNullOrEmpty(book.Author) && book.Year > 1900 && !string.IsNullOrEmpty(book.Content); // Pure function to format a book private static string FormatBook(Book book) => $"{book.Title} by {book.Author} ({book.Year})"; // Higher-order function for processing books private static IEnumerable<T> ProcessBooks<R>( IEnumerable<Book> books, Func<Book, bool> validator, Func<Book, T> formatter) => books.Where(validator).Select(formatter); public static void Main() { var books = new List<Book> { new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925, "In my younger and more vulnerable years..."), new Book("To Kill a Mockingbird", "Harper Lee", 1960, "When he was nearly thirteen, my brother Jem..."), new Book("Invalid Book", "", 1800, ""), new Book("1984", "George Orwell", 1949, "It was a bright cold day in April, and the clocks were striking thirteen.") }; // Using our higher-order function to process books var formattedBooks = ProcessBooks(books, IsValid, FormatBook); Console.WriteLine("Processed books:"); foreach (var book in formattedBooks) { Console.WriteLine(book); } }
This example demonstrates several key functional programming concepts:
- Immutability: We use
record
for theBook
type, which is immutable by default. - Pure functions:
IsValid
andFormatBook
are pure functions. They always return the same output for the same input and have no side effects. - Higher-order function:
ProcessBooks
is a higher-order function that takes two functions as parameters (a validator and a formatter). - Composability: We compose the validation and formatting operations in the
ProcessBooks
function. - Declarative style: We describe what we want (valid, formatted books) rather than how to do it step by step.
- LINQ: We use LINQ methods (
Where
andSelect
) that align well with functional programming principles.
This example shows how functional programming can be applied to a real-world scenario such as a book publishing system.