r/functionalprogramming • • Mar 31 '19

Question Are there "clean code" guidelines on FP?

One thing I am wondering - are there any general guidelines in the style of "clean code" for the paradigm of functional programming?

To give some information on my background, I am familiar with Clojure and Scheme, and I am aware of some Clojure coding style guidelines. What I am looking for is for good practices one level up, like:

  • how many parameters should functions have?

  • when should flags be used, when methods which match the same signature?

  • when should data be combined in records / objects ?

  • what is the best way to arrange I/O and database access?

  • what helps to organize larger programs?

I am looking especially for guidelines which are generally applicable, regards of the programming language.

To describe the task at hand, I am currently writing an application in Python which does both a lot of hardware control, data gathering, and a lot of data transformation and presentation. While some of the hardware control seems to be a more naturally fit to OOP with some imperative parts (this is where the changing state of the hardware matters), some seems more suited to OOP with a functional paradigm (similar to Scala's immutable objects), and the data transformation part looks like a very clear match to "pure" FP (which is not all that unusual in code which uses Numerical Python, for example). I have been checking this code using pylint. It uses some complexity evaluations like number of branches, number of parameters, lines of code in methods. These checks tend more frequently to fail in the hardware control parts - especially, it tags some functions as "too complex". Obviously, the checks in pylint draw some criterions from Robert Martin's "Clean Code" guidlines, for example methods and functions with too many branches, too many parameters, or too many lines of code are marked with warnings.

It might be that there, I am simply trying to use too much a "pure functional" style where some sort of OOP approach (with or without side effects) would be better suited. But I am also wondering whether good functional-styled code might simply need somewhat different guidelines. For example, in "Clean Code", Bob Martin says that no function should have more than three parameters. It seems to me that this makes sense for an OOP style, where a lot of additional information is in object member variables, bit might be too little in a pure FP style.

Finally, I want to formulate something which is, let's call it, a bit of a suspicion, it is not a theory, and it corresponds somewhat to the matter of preferred OOP styles and differences to FP styles. The suspicion is that OOP has (often) advantages when used in a single code base. An example for that would be a Unix kernel. However, much of the appeal of OOP in the last three decades seemed to come from the idea that software can be made into independent, reusable parts, which can be fabricated, stored, sold, and used, just like parts of a machine, and independent of the code base in which it is employed. So, this view of OOP sees OOP as a means for re-using code as components. An example for this would be Delphi or GUI toolkits, or Java libraries. A consequence of that approach is that the resulting libraries are often very heavily geared toward general usefulness and maximum flexibility, which leads sometimes to a very high stack of abstractions, and a high complexity - I think the Java libraries are a good example of that. Probably, some clean code guidelines reflect that.

There seems to be a different school of thought which sees abstraction as not necessarily helpful, and thinks that abstraction needs to be justified within each single program - that it is better to re-write some code, than to tug around a huge baggage of unused abstractions. I think for this school of thought, FORTH is a good example.

Now, to formulate my suspicion, it appears to me that in functional programming languages, abstractions tend to be seen more in the way of an intermediate, middle-ground school of thought - they are useful if they help to express the code more clearly, but the primary goal of abstractions is not to get complex, re-usable components, rather it is to organize the code into layers which can be reasoned about independently. It seems to me that languages like Lisp and Clojure are much more centered around sharing and re-using of source code, than of binary software components. And this preference for code-sharing over component-sharing might be one of the reasons why FP is (or was) less popular in the parts of the commercial software industry which sell licensed software, than in those parts which, for example, provide software as a service.

30 Upvotes

9 comments sorted by

View all comments

3

u/watsreddit Mar 31 '19

We have a few in the Haskell world that could probably be applied to other functional (and indeed, non-functional) languages, such as "push side-effects to the edges of your application" and relatedly, the "functional core, imperative shell". The basic idea is that we can define interfaces that describe effectful actions and write functions parameterized on those interfaces, and only use the concrete implementations at the entry/exit points of your app. The core of the application doesn't use these interfaces at all, and just does pure data transformations.

Though I suppose maybe this idea is less useful without the Monad abstraction, I dunno.

3

u/Alexander_Selkirk Mar 31 '19

We have a few in the Haskell world that could probably be applied to other functional (and indeed, non-functional) languages, such as "push side-effects to the edges of your application" and relatedly, the "functional core, imperative shell".

That is interesting - are there descriptions on that?

Though I suppose maybe this idea is less useful without the Monad abstraction, I dunno.

I have to confess that I still don't understand Monads. Is there any programming pattern which is similar or even equivalent in OOP languages?

Also, I am wondering whether there is a deeper or a more general concept to the way in which syscalls and especially I/O is handled in Unix operating systems. Basically, when a C program does an fscanf(), the program is halted, the operating system does the needed I/O, which can be a lot of complex operations, and when this is finished, the syscall returns with a result. For the C program, a file which is only read is only a data source (unless it is reading and writing the same file), which means that all temporal dependencies and almost all error handling is resolved by the OS. So, basically:

#include <stdoi.h>
#include <math.h>
double get_num()
{
  double val;
  fscanf("%f", &val);
  return val;
}

void put_num(double val)
{
   fprintf("%f\n", val);
}

double process(double val)
{
  return sin(val);
}

int main()
{
  put_num(process(get_num()));
}

looks almost like a side-effect free program, even if the OS device driver surely has a lot of state.

3

u/lgastako Mar 31 '19

I have to confess that I still don't understand Monads. Is there any programming pattern which is similar or even equivalent in OOP languages?

Given the nature of your original question I suspect this post might help shed some light on things for you: https://philipnilsson.github.io/Badness10k/escaping-hell-with-monads/

2

u/Krackor Mar 31 '19

This post doesn't seem to describe monads in any more detail than saying they are hand-wavy magic.

2

u/lgastako Mar 31 '19

Well, you're right -- it's not so good for explaining monads, but when I was somewhere in the neighborhood that OP is in terms of understanding I found it helpful in motivating them and in clearing up the nature of the "pattern" -- ie that the pattern is something that appears all over the place in programming, but it's never obvious until you already have monads in hand.

3

u/watsreddit Apr 01 '19

https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell

This video describes the idea of the "functional core, imperative shell", and notably it's done in Ruby. In Haskell, we generally add a third layer between the two, which are the "interfaces" I was referring to earlier. Another term you might see used to describe this is the "Three Layer Haskell Cake", described in this article: https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html.

The article that /u/Igastako linked should give you some idea of what kind of things Monads can abstract over, even if it doesn't explain them in depth. There's no equivalent in OOP languages, because either they simply lack the capability of providing a general interface for them (in the case of statically-typed OOP languages), or they don't really get much benefit from them (in the case of dynamically-typed OOP languages).

There are dozens of articles on Monads already, but basically it's just a way of describing a pattern that pops up a lot in programming, especially when you are programming functionally. Since we are constantly passing values around, you often want to pass values with some kind of context. Monads are a way of providing a unified interface for talking about values with a context, and how chaining functions that produce contextual values can change this context. Monads have a couple of operations: you can wrap a value (the function is usually called return or pure), and you can unwrap a value, do something with it, and then wrap it back up again (this function is usually called bind or flatMap). If you call bind again on the newly wrapped value, you can reference previously unwrapped values. You can kind of think of the unwrapped values as local variable bindings like in imperative languages. The difference is that you can't arbitrarily create bindings. Instead, the bindings come from unwrapping a value from a Monad, and what it means to "wrap" and "unwrap" values depends on the particular Monad. In the IO monad, the context is the side effects being produced, and creating new bindings produces side effects. In the Maybe/Option monad, the context is whether or not you've seen an empty/null value, and creating new bindings will produce an empty value if an empty value was bound before, or a new value.

In practice, each Monad is like a specialized API for some related set of operations, but we can also have a unified syntax for working with these APIs (like do-notation in Haskell), and we can write functions that work with arbitrary Monads thanks to this unified syntax.

Really, the best way to understand Monads is to use them in a language that supports them, imo. Haskell is the most well-known, but you also have some other functional languages like Scala, Ocaml, and Purescript. Any language with support for higher-kinded types (like if you could write generics of the form F<A> in Java, for example) can implement Monads.

Regarding your C example, I wouldn't really call that side-effect free. It's certainly delimiting side-effects (pushing them to the edge even, like I mentioned before), but the reason we care about side-effects is that so we can look at a function from the outside and know exactly how it will behave for all inputs. From an outside perspective, all I know about getNum is that it gives me a double. I have no way of knowing if that function can cause the program to crash or not. Likewise for the put_num function. I have to inspect their implementations to understand how they will behave, or rely on documentation. For a large codebase, it's incredibly useful to be able to call a function and know with absolute certainty that it cannot fail.

2

u/bedobi Apr 01 '19

Keeping as much of the codebase as possible free of state, side effects etc is a good practice in any language. Even Java codebases can be tolerable when written like that.

2

u/watsreddit Apr 01 '19

Definitely true, though this is more common practice in functional languages, particularly ones like Haskell, I think. I teach Haskell/Purescript to new developers at work and in my experience they are not used to thinking in terms of limiting side-effects.

There's also the issue that without Monads (or some other abstraction for encoding effects), you really have no way of writing functions that can guarantee that they are side-effect free or limited to very specific set of effects. In the codebase I am working on, I know for a fact that there are exactly 4 modules that can perform side-effects, and they are small modules that are easy to reason about. I would have no way of knowing that with a large Java codebase, even if it was architected well and limited side-effects in the same fashion. Perhaps you can if you know your team has been very hygenic with respect to the architecture and you have a vigilant code review process, I suppose.