Pure Functions – VB

[Table of Contents] [Next Topic]

FP introduces the notion of pure functions.  A pure function is one that doesn’t affect the state of anything outside of it, nor depends on anything other than the arguments passed to it.  Also, given a set of arguments, a pure function will return the same result.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCAmong other things, if a method does any of the following, it is impure:

·         Altering a parameter that was passed by reference

·         Altering the members of a passed object (all objects are passed by reference)

·         Altering external objects, static members of classes, etc.

The term for these things is “side effects”.  A pure function doesn’t have any side-effects.

The benefits of writing pure functions are:

·         If we write functions that don’t have side-effects, then we can use them whenever and wherever we want to when composing our queries.  Pure functions lead to composability.

·         Testing is easy.  Once we have tested all edge conditions on the arguments to our function, we can be certain that the function works properly.

·         Concurrency is (at least theoretically) possible.  If we know that a function relies on nothing other than its parameters, then we (or the compiler) might be able to execute the function in a new thread, or even a different CPU.  This is one of the directions that the industry will take in the future to take advantage of multiple CPUs.

Any functions (utility functions, extension methods, lambda expressions, etc.) that we want to use within a query expression should be implemented in a pure fashion.  In particular, when we write new query operators (extension methods that operate on IEnumerable(Of T)), we always want to write them to be pure.

Actually, there are two types of impurity

·         The impurity is contained inside the method

·         The impurity leaks out of the method.  For purposes of threading and taking advantage of multiple core CPUs, and multiple CPU computers, impurity that is contained within a single method still may allow for queries to be parceled out to separate threads and possibly separate processors.

One of the sources of bugs in conventional-object oriented programs is something called broken invariants.  There are invariants associated with many classes – for example, if one member has some value, then another member needs to have a particular range of values.  This is a funny way to get rid of those types of bugs: just say no to state!

[Table of Contents] [Next Topic] [Blog Map]

Comments (0)