by gizmo · 4y ago · 0 comments
BAD: copying data needlessly and turning trivial stuff into a functional pipeline that is impossible to debug. You want your code to read top to bottom like the problem you're trying to solve, if at all possible. If your call stack looks like map, fold, reduce you've introduced a ton of complexity, and why exactly?
Every programmer should understand functional programming. Higher order functions can be super useful. Immutable objects are invaluable for preventing subtle bugs. But if you feel the need to transform simple linear code into a map of higher order functions because of some abstract benefits you're probably doing stuff that's too easy for you and you should get your mental challenge from solving a more difficult problem instead.
I stand a better chance understanding the sequential code than a complicated recursive (edit: nested) monad. Depending how it was written.
I can probably understand Kafka pipeline's or a functional map, reduce pipeline.
My parser for my programming language which I'm building is a recursive Pratt parser but it's written in Java.
I want to understand functional programming better. I am interested in software transactional memory and parallelism. I am aware Erlang and Go use message passing but only Erlang is functional.
In theory functional code can be parallelised due to immutability but you need some kind of communication to indicate transference of values. Imagine a pipeline where you need to share a value to a few other threads. I'm aware Haskell has software transactional memory
Isn't that simply because you're a Java developer (as I understand from the rest of your post)?
> I would rather inherit someone's stateful JavaScript or Java than a complicated codebase by a seasoned Clojure, Haskell, Scala developer. I stand a better chance understanding the sequential code than a complicated recursive monad. Depending how it was written.
True, but you add here the "complicated" attribute deliberately .. usually it is the other way round. The functional approach code is simpler to read and reason ( and usually not with much recursive monoids), while the believed sequential program has so many "concurrent" paths (even if there is no real concurrency, but just in the many hidden ways how the super distributed statefulness is manipulated).. not?
It spurned a chain of events that you might find interesting.
I am interested in parallel software and multithreading, so that's the kind of software I enjoy writing.
The branches of a single threaded software can think of potential future interleavings.
Your post inspired me to think of programs as "circular" or not. That is, they return to a steady state and can function properly no matter how many times they run and whether or not the execution is interrupted at any point.
A program that is interrupted can leave the program state in an invalid state that cannot be recovered.
So I started writing a parser to parse an assignment language. I plan to track object identities membership over time and see if objects get stuck in processing - they stop moving.
program {
available = {};
assigned = {};
main {
program = programs {
current_available = program.available {
available += (current_available, 1);
assigned - current_available;
}
item = program.requests {
available (=) item {
program.answers += item;
available - item;
assigned + (item, 1);
}
}
}
}
}
program {
requests = [];
requests += (add, 1);
main {
item = answers {
new_requests = [(add, 1)];
available += (item, 1);
new_request = new_requests {
requests += new_request;
}
}
answers -= answers;
}
}I'd rather inherit a complicated Java program than a complicated Scala program. But I'd take a well written Scala program over a well written Java program any day of the week.
Since I quit, the entire new engineering team quit and it looks like the company is going under. Functional programming is a big mistake for some real-world code.
Generalizing much? I write C# for a living, Elixir in my free time, I would take Elixir codebase any day of the week. If you try to write C# in a strictly functional fashion it's going to be shitshow as well. Moderation is the key, using immutable data structures, getting rid of side effects if possible etc.
You had a bad experience because you and/or people you worked with simply tried to fit a square peg into a round hole, you didn't get it in, threw a tantrum and now you're blaming all the squares for being bad.
I on the other hand, after learning functional language, have trouble looking at most code written by pure 'OOP developers', most of it is a spaghetti shitshow of hierarchy classes, dependencies and jumping across 20 different files of factories and providers because DUHH sOlId and ClEaN. That doesn't mean that OOP is a 'mistake for real-world code'.
I honestly think these are the important bits of this story. The startup outsourced their backend to an agency, then tried to replace the agency with a brand new internal dev team.
There's no way that story ends well, regardless of the paradigm the agency chose or how skilled they might have been (probably not very). Every codebase is unmaintainable when the team that built it is suddenly replaced.
Peter Naur had a lot to say about this in Programming as Theory Building [0]:
> The extended life of a program according to these notions depends on the taking over by new generations of programmers of the theory of the program. For a new programmer to come to possess an existing theory of a program it is insufficient that he or she has the opportunity to become familiar with the program text and other documentation. What is required is that the new programmer has the opportunity to work in close contact with the programmers who already possess the theory, so as to be able to become familiar with the place of the program in the wider context of the relevant real world situations and so as to acquire the knowledge of how the program works and how unusual program reactions and program modifications are handled within the program theory.
[0] https://gist.github.com/onlurking/fc5c81d18cfce9ff81bc968a7f...
Not OP but imho, it’s because FP is "sold" as the perfect solution for readability and code maintainability. Just use FP and nothing can go wrong. That’s at least the impression I get when I read about FP.
The fact that one can write abysmal OOP code is nothing new.
To be fair that was the kind of nonsense that was being talked about OOP in the late 90's and early 2000's.
There are no silver bullets, and anyone who claims otherwise is flat wrong.
However most techniques have their advantages, when used well - and I'd say FP has more to offer than OOP in this context.
What I don't agree with the GP is specifically the claims on other languages:
""" Python with immense amounts of spaghetti, C with its hard to control safety, abysmal imperative or OOP code in Typescript ""
These are not sold as advantages for the respective languages. Python doesn't say it's easier for the programmer to write spaghetti. C's unsafe constructs are a known side effect of being closer to the metal (and optimizing for speed at expense of safety). Typescript's selling point is type checking, which is orthogonal to abysmal code.
But FP is just sold as making it easier to make abstractions all the way down. And for many of us FP-skeptics, that's not a selling point, that's a turn off. (And to reiterate my original point - this is the same for Java, OOP and OOP-skeptics)
That’s because it is. FP is not immune to incorrect implementation. Both statements are true.
Only twenty? That'd be a reduction.
If your stack trace doesn't have at least 30 calls of "thingHandler.invoke()", you're not abstract enough.
The emphasis on "some" should be stronger in your comment, otherwise it reads, on a quick pass, as a broad dismissal of functional programming.
Functional programming concepts and ideas have been steadily incorporated in most mainstream languages in the last 10+ years. However, when people move past the language's functional programming primitives, it's when the project enters potentially dangerous territory. Your, and the article's, example of pipes, for one.
Personally, I'd like more languages to incorporate ADTs (algebraic datatypes) for me to be able to "de"layer programs back to a mostly procedural + functional programming. And based on the current adoption rate of FP concepts, I'm not sure we're that far away from having proper ADTs and pattern matching in the most popular imperative programming languages of today.
It feels egregious to implicate "the entire surface area of functional programming" here, when there are other obvious issues at play.
Hard to follow code is mostly a consequence of point-free style in Haskell which is an heresy to be avoided at all cost.
ML typically uses a piping operator to compose code instead and that leads to top to bottom code which is extremely easy to read.
There is zero difference then between a map and a loop. Loops are not read top down anyway nor are function calls. It seems to me you are just more used to these indirections than other ones and are therefor blind to them. This leads to an argument which I consider a straw man personally.
This phenomenon seems to happen more frequently with FP or related tools and languages (RxJs abstraction soup comes to mind).
> RxJs abstraction soup comes to mind
Merely a side effect of being implemented in a language that wasn’t really designed for it.
But their scope can be limited.
Do you have a link to a good one?
[1] https://elixirschool.com/en/lessons/basics/pipe_operator
https://cs3110.github.io/textbook/chapters/hop/pipelining.ht...
If you're talking about a sequence of statements, I've rarely come across such a thing.
Firstly, the mere existence of statements in a language is an incredible complication:
- It forks the grammar into two distinct sub-languages (expressions and statements)
- Expressions compose with each other, and with statements; but statements don't compose with expressions.
- It introduces a notion of (logical) time into the semantics ('before' a statement is executed, and 'after' a statement is executed)
- The times of each statement need to be coordinated. Chaining one-after-another is easy (usually with ';'), but concurrency gives an exponential explosion of possible interleavings.
- The computer often cannot help us spot mistakes, and compilers have very little ability to optimise statements.
This is especially silly in Python, where many common tasks require statements, which often requires rewrites (e.g. we can't put statements in lambdas; hence we often need separate function defs (which themselves are statements); pulling those out may lose access to required lexically-scoped variables, requiring even more plumbing and wrapping; urgh.)
Compare this to functional code, where there's only a single language (expressions) where everything is composable; where there is no control flow (only data dependencies); there is no notion of time; mistakes are more obvious (e.g. 'no such variable' errors at compile time); compilers have lots of scope to optimise; and code is trivial to parallelise.
“Logical time” actually matters when you have side-effects. Of course we can agree code without side effects is simpler to reason about. Unfortunately you need side effects to do anything useful.
"Time" doesn't matter; causality/dependency is what matters. That is modelled quite well by passing around values. For example:
let hostname = lookup("hostname")
username = lookup("username")
password = lookup("password")
connection = connect(hostname, username, password)
in query(connection, "SELECT foo FROM myTable")
The 'query' call depends on the result of the 'connect' call, so it must "happen afterwards". The 'connect' call depends on the result of the three 'lookup' calls, so it must "happen afterwards". The 'lookup' calls don't depend on each other, so they're concurrent (note that concurrent does not necessarily imply parallel).This form of data dependency is no different than, say, arithmetic: to calculate '3 × (2 + 4)', the multiplication depends on the result of the addition, so it must "happen afterwards". (The imperative equivalent would be 'push 2; push 4; +; push 3; ×;')
> Worth noting Haskell ended up reinventing the statement/expression distincion in the do-notation
Yes, do-notation "desugars" into plugging return values into arguments, like above. This gets a little tedious for things like 'IO', where we pass around a unit/null value to represent "the real world".
Still, a nice lesson from Haskell is that there's value in making things opt-in; e.g. many languages have Maybe/Option, but it's less useful in languages which allow 'null' anywhere; many languages have IO/Effect/Task/etc. but it's less useful in languages which allow I/O anywhere; etc.
What if instead we said
let connection = connect(hostname, username, password)
_ = query(connection, "INSERT INTO t1 VALUES ('abc')")
data = query(connection, "SELECT * FROM t1")
in print data
What is the order of the two calls to `query` actually matters, but how could the language know?The order of execution of code is actually important every time you have such a side effect, and languages that don't strictly define it make this type of thing very error prone.
Use "from" and "to", which talks about data dependencies rather than temporal dependencies. Most people assume dependency order implies temporal order, and then you introduce them to lazy evaluation to decouple even that.
For example, if 'foo = g(x)' is defined in one module, and another module does 'f(foo)', then the data flow is preserved. If we try to force things to be the wrong way round, we'll get compiler errors like 'No such variable foo'.
Compare that to temporal ordering of statements; if one module executes 'g(x)' and another executes 'f()', how do we ensure the latter occurs after the former? How could the compiler tell us if they're the wrong way around? Very difficult.
The only situation for this that I can think of is inside a list comprehension / generator expression. You are aware that you can define functions at any scope in python?
>>> lambda myVar: (def foo(): return myVar + 1, foo)[-1]
File "<stdin>", line 1
lambda myVar: (def foo(): return myVar + 1, foo)[-1]
^
SyntaxError: invalid syntax def f(myVar):
def foo():
return myVar + 1
return fooProblem is that is not a programming language supported by anybody else than you. It is not part of the standard library. If it was it would probably be of high quality, highly tested-in-practice code.
But if you constructed your pipeline-framework (as in the article) by yourself you now need to understand not only the solution in terms of your created framework, but also how the framework itself exactly works. If this is a one-off problem-solution what looks like simpler code in the end hides its complexity inside its framework-code. And as you keep programming your framework is a moving target. You will improve it from time to time. Understanding it becomes a moving target too. It is a real problem for maintenance for you or anybody else who wants to use and adapt your existing code in the future.
Think about having the problem and a solution and being able to describe both in English. But then you say hey if I invent this new language Klingon and express the problem and solution in Klingon, then both the problem and solution become simpler. Cool. But now you must also program the Klingon interpreter for yourself. And be aware of which version of Klingon your code is assuming is used.
This is the tendency and cost of over-engineering. It is fun and natural to look for the "ideal solution", but it comes with a cost.
The idea to handle validation (we get HTML instead of expected JSON) by passing some Nothing object down the flow is horrible, if we expect JSON and get something unparsable, well, the best strategy is to fail fast and let know client side that we have a wrong data. Instead we show off with some fancy code structure with zero value for the user of the software.
I think where functional programming really shines is in combination with a good type system, that can enforce those restrictions. In languages like js I find it not so useful (even if using map, filter, etc.) because I have no guarantees that there is a hack somewhere in the function that I did not see.
When there are a lot of pure functions the cognitive load is reduced so much I can use the "extra capacity" to focus on the task.
- No side-effects makes reasoning about logic easier, code more deterministic, and tests more reliable. However, certain problems become harder to solve (e.g. simple caching or memoization).
- Async-style interfaces allow for waiting on slow operations in a non-blocking fashion, meaning those don't occupy threads, thus a more economic use of resources. However, async-style code can be harder to read, write, and debug, though this varies heavily between languages and frameworks.
You can still write pure functions and avoid state in imperative code. Use consts, immutable objects, etc. You get some of the benefits of functional programming while still writing readable code.
let foo = MakeMeAnObject();
let bar = MakeSomethingElse(foo);
DoSomethingForSideEffects(foo, JoinThings(bar, baz));
return foo;
With immutable objects, you can be certain that neither foo nor bar were modified by any of this code. So, when e.g. debugging a problem with that DoSomethingForSideEffects() call, you don't have to worry about values of foo and bar having been changed somewhere, by someone, between their introduction and the point you're debugging.Neither of them can be modified by it in the future - e.g. someone else can't change MakeSomethingElse() to also modify its inputs, thereby accidentally breaking your code that's using this function.
Another way of looking at it: a lot of problems with reasoning about code, or parallelism, can be drastically simplified by assuming the data being passed around is only copied, and not modified in-place. "Immutable objects" as a language feature is just making this assumption the default, and enforcing it at the language/compiler level.
In terms of use, it isn't that much more inconvenient over mutable objects. You can always do something like:
foo = DoSomeTransformation(foo);
It's just that DoSomeTransformation() is not modifying the object, but instead returning a new instance of the same objects, with relevant fields having different values. The obvious drawback here is, for large data structures, there will be lot of copying involved - but that's where the languages with immutable objects are usually "cheating", e.g. by using sophisticated data structures masquerading as simple ones, as to only ever copy things that have actually changed (i.e. "distinct" objects end up sharing a lot of their data under the hood).I can't think of anything where I'd want that. Don't you end up needing infinite amounts of memory? Isn't it absolutely slow as balls copying all that stuff around?
Is it as fast mutable everything? No, some copy must happen, but is a mutable-standard languages as fast as raw hand tuned asm? Also (probably) no, but the trade offs are worth it. It likely matters a lot less than you think unless you're writing actually performance critical tight loop code vs just thinking about performance.
This way:
- passing an object around can always be by reference, since no one can change it
- depending on structures used, for changed bits you don't need to copy the entire structure, but simply shift pointers to old data or new data
- garbage collection can become trivial, and granular, since you know exactly what's new and old, and shifting data around becomes just moving pointers around (again, depends on implementation and optimisations)
There are downsides if you are not careful, of course:
- creating a bunch of new data that references old data will run out of memory, but this doesn't happen as often as you would think.
- sending data between processes/threads may result in copying that data (depends on implementation)
However, the upside is quite good: your data never changes under you. That is a call to func(data) doesn't sneakily change data. And all data becomes trivially thread-safe without mutexes or race conditions.
for example (pseudocode)
var newUser = Person(name: "some guy", age: 0)
// newUser is replaced with a new object that is
// initialized with field.name and previous age (0)
// the old object is discarded
newUser.name = field.name
// object is passed as copy-on-write, assuming a 1 sec delay
// it will print the objects values at this point in time
// (age: 0) even if altered later
async(after:1) { print(newUser.age) } // prints 0
// age was changed to 32 a nanosecond later,
// but now a new object again is initialized
// instead of mutated
newUser.age = 32
print(newUser.age) // prints 32
----------
output:
32
0
[0] https://en.wikipedia.org/wiki/Value_semantics[1] https://stackoverflow.com/questions/27084007/what-is-value-a...
would appreciate a correction!
I like being able to trust that something is what I think it is because it cannot be something else. Meaning: if I know that something can’t change, I don’t have to check for eventual accidental change.
This is "safer" for any code still operating on the original object, as it will not be changed unexpectedly.
extern result fubar(struct foo *);
extern result snafu(struct foo const *);
Just by looking at the function prototype, I know that calling snafu() won't change the struct foo I pass it. I don't know what fubar() will do to it. Maybe it won't change, maybe it will. I'd have to check the implementation of fubar() to find out.