Why functional programming and LINQ is often better than procedural code

Functional programming is a relatively new component in the C# language. It can potentially replace for-loops in many situations with simpler code, but the question remains ‘what’s wrong with a good old for loop?’

Here are some of the reasons I think functional programming is important and in particular how LINQ can improve the readability, maintainability, and parallelizability (if there were such a word) of your code:

  1. Functional approaches are potentially easier to parallelize either manually using PLINQ or by the compiler. As CPUs move to even more cores this may become more important.
  2. Functional approaches make it easier to achieve lazy evaluation in multi-step processes because you can pass the intermediate results to the next step as a simple variable which hasn’t been evaluated fully yet rather than evaluating the first step entirely and then passing a collection to the next step (or without using a separate method and a yield statement to achieve the same procedurally).
  3. Functional approaches are often shorter and easier to read.
  4. Functional approaches often eliminate complex conditional bodies within for loops (e.g. if statements and ‘continue’ statements) because you can break the for loop down into logical steps - selecting all the elements that match, doing an operation on them, …

These days I opt for the functional syntax more often than not and fall back to for-loops when:-

A. The body of the loop contains complex logic that cannot be disentangled into a cleaner sequential application of functions and it simply easier to just write a for-loop with the complex conditional code in it.

B. The task is inherently not functional, i.e. has side effects

C. The task needs exception handling in it. Sure you can write big lambda blocks with try catch in them but at some point it becomes easier and cleaner just to use a for-loop.

Thu Apr 15 2010 18:09:54 GMT-0700 (Pacific Daylight Time)

Next page: The relationship could not be changed because one or more of the foreign-key properties is non-nullable

Previous page: Why don't you trust your build system?

Disqus goes here