Strategy pattern and functional programming

During the first four chapters of this book, we discussed patterns and practices a lot. The strategy pattern is one of the important patterns of Gang of Four (GoF) patterns. This falls under the behavioral patterns category and is also known as a policy pattern. This is a pattern that is usually implemented with the help of classes. This is also an easier one to implement using functional programming.

Jump back to the Understanding functional programming section of this chapter and reconsider the paradigm of functional programming. Higher-order functions are one of the important paradigms of functional programming; using this, we can easily implement a strategy pattern in a functional way.

Higher-order functions (HOFs) are the functions that take parameters as functions. They can also return functions.

Consider the following code that shows the implementation of HOFs in functional programming:

public static IEnumerable<T> Where<T>
(this IEnumerable<T> source, Func<T, bool> criteria)
{
foreach (var item in source)
if (criteria(item))
yield return item;
}

The preceding code is a simple implementation of the Where clause, in which we used LINQ Query. In this, we are iterating a collection and returning an item if it meets the criteria. The preceding code can be further simplified. Consider the following code for a more simplified version of the preceding code:

public static IEnumerable<T> SimplifiedWhere<T>
(this IEnumerable<T> source, Func<T, bool> criteria) =>
Enumerable.Where(source, criteria);

As you can see, the SimplifiedWhere method produces the same result as the previously discussed Where method. This method is criteria-based and has a strategy to return results, and this criterion executes at runtime. We can easily call the preceding function in a subsequent method to take advantage of functional programming. Consider the following code:

public IEnumerable<ProductViewModel>
GetProductsAbovePrice(IEnumerable<ProductViewModel> productViewModels, decimal price) =>
productViewModels.SimplifiedWhere(p => p.ProductPrice > price);

We have a method called GetProductsAbovePrice. In this method, we are providing the price. This method is self-explanatory, and it works on a collection of ProductViewModel with a criteria to list the products that have a product price that is more than the parameter price. In our FlixOne inventory application, you can find further scope to implement functional programming.

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

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