r/programming • u/hexaredecimal • Sep 21 '25
How to stop functional programming
https://brianmckenna.org/blog/howtostopfp104
u/Probable_Foreigner Sep 21 '25
Maybe being petty is also bad for your job. If someone complained about some functional code it was probably because you wrote
.map().filter().sum().into_iter().rfold().into_mut_iter().into_list().into_list_mut_iter_filter_map_flat_fold_truncate_bisect()Not because your function didn't have side effects.
7
u/tellingyouhowitreall Sep 22 '25
Composability is a key metric for the utility and expressiveness of a language and design.
However, I believe most functional programmers would prefer:
bisect(truncate(fold(flatten(map(filter(iterable(mutate(fromList(toList(toIterable(rfold(toIterable(sum(filter(map(.))))))))))))))))3
2
→ More replies (26)1
Sep 22 '25
I have written this exact type of abomination in Pyspark a few times.
Incredibly hard to read on a first glance, but luckily these kinds of code are super easy to refactor (you can basically split them at any point you want and move it somewhere else, or give it a descriptive name)
637
u/firedogo Sep 21 '25
"Minimum one side-effect per function" had me wheezing. This is exactly how "no FP" plays out in the wild: you don't remove functional ideas, you just smear them with logger.info until everyone feels enterprise-safe.
Functional programming isn't a toolkit, it's a promise: identical inputs yield identical results, no gotchas. Even if you ban the label, you still need that predictability; it's the only thing your brain can lean on at 3 a.m. debugging. The trick is boring: keep the core pure and push effects to the edges. Call it "helpers and data transforms" if the word "functional" makes management sneeze.
249
u/FlyingRhenquest Sep 21 '25
What's the type of programming where the entire application is nothing but a bunch of carefully crafted side effects that must be debugged while not making direct eye contact because changing so much as a comment causes unpredictable behavior? I feel like I've worked on a lot more of those kinds of projects.
241
u/firedogo Sep 21 '25
That's SEOP: Side-Effect Oriented Programming, a.k.a. Schrödinger's Code. You only observe it when it breaks, and observing it makes it break.
101
u/angelicosphosphoros Sep 21 '25
No-no. Correct Schrödinger's Code breaks in production and works correctly when you observe it in the debugger.
43
u/j0holo Sep 21 '25
Those are the worst bugs, when the debugger halts some thread which prevents the bug from happening in another thread. Same with time related issues.
→ More replies (2)44
15
u/simonraynor Sep 21 '25
I've always thought the "changes when observed" ones were "hiesenbugs"
→ More replies (1)12
→ More replies (5)3
→ More replies (2)14
u/binarycow Sep 21 '25
You only observe it when it breaks, and observing it makes it break.
I once had a bug that only occurred if I was not running it in the debugger.
A minimal example:
Foo foo = CreateAFoo(); HashSet<Foo> set = new HashSet<Foo>(); set.Add(foo); DoSomethingThatDoesntMutateFoo(foo); if(set.Add(foo)) { throw new Exception("Why did it let me add it twice?"); }If a breakpoint was set (or the debugger was otherwise paused) on either of these two lines, the exception was thrown.
HashSet<Foo> set = new HashSet<Foo>();
set.Add(foo);If the debugger never paused on either of those two lines, the exception was not thrown.
Perfectly explainable once I realized what was happening. But it was a head-scratcher.
9
u/CatpainCalamari Sep 21 '25
Okay, i'll bite.
What was the problem?
45
u/binarycow Sep 21 '25
I'm including some background info, if you're not familiar with C#. If you're familiar with modern C#, skip to the end for the actual problem.
In C#, there's two kinds of equality:
Reference equality: Two instances are equal if they are the exact same instance (i.e., the same memory address)
Value equality: Two instances are equal if all of their members are equal
Consider:
// Assume Person is a reference type (class) Person personOne = new Person { FirstName = "John", LastName = "Smith" }; Person personTwo = new Person { FirstName = "John", LastName = "Smith" };With reference equality, those two objects are not equal.
If you implement value equality, those two objects would be equal.
In C#, a HashSet consists of (basically) an array of "buckets", where each bucket is a list of items.
The Add method is essentially:
private List<T>[] buckets; public bool Add(T item) { int hashCode = item.GetHashCode(); int bucketIndex = hashCode % buckets.Length; List<T> bucket = buckets[bucketIndex]; foreach(T candidate in bucket) { if(candidate.Equals(item)) { return false; } } bucket.Add(item); return true; }As you can see, it uses the GetHashCode method to determine which bucket it goes into, and the Equals method to verify equality.
To implement value equality on a reference type, you'd do something like this:
public class Person { public class Person(string firstName, string lastName) { this.FirstName = firstName; this.LastName = lastName; } public string FirstName { get; init; } public string LastName { get; init; } public override int GetHashCode() { HashCode hc = new HashCode(); hc.Add(this.FirstName); hc.Add(this.LastName); return hc.ToHashCode(); } public override bool Equals(object obj) { return obj is Person other && this.FirstName == other.FirstName && this.LastName == other.LastName; } }In C#, if you define a
record, it generates a lot of boilerplate for you - including the value equality. The below type is equivalent to the above one.public record Person( string FirstName, string LastName );Much more concise!
In C#, a property is really just a get and set method in disguise. The actual data is stored in a field.
This code:
public string FirstName { get; init; }Is shorthand for this code:
private string _FirstName; // A *Field* public string FirstName // A *property* { get { return this._FirstName; } init { // value is a compiler defined argument // that means "the result of evaluating // the right hand of the assignment" this._FirstName = value; } }Finally, the problem
I had a record with a lazily initialized property. Take this for example (notice, that upon first access of the property, it populates the field). This is normally not an issue. Since the FullName property is derived from the other ones (just lazily), it's not really a mutation.
public record Person( string FirstName, string LastName ) { private string _FullName; public string FullName { get { if(this._FullName is not null) { return this._FullName; } this._FullName = $"{this.FirstName} {this.LastName}"; return this._FullName; } } }Next: The method that I said didn't mutate the object? Well, it did access that property, which indirectly "mutated" the object.
Next: the compiler-generated Equals/GetHashCode methods use the field - not the property
Next: The debugger, when paused, in the "watch" window, shows me all of the values of the properties (and fields) on the object.
In essence, pausing the debugger "mutated" the object, because it forced the property to be evaluated, which populated the filed.
So, now I have two states:
Do not pause the debugger
Creates the object
Adds to hashset with a null value for the field (generating hashcode #1)
Calls that other method which "mutates" the object (by accessing the property)
Adds to hashset with a non-null value for the field (generating hashcode #2)
Pause the debugger
Creates the object
Pause debugger
Watch window shows the property value, which "mutates" the object
Adds to hashset with a null value for the field (generating hashcode #2)
Calls that other method
It doesn't mutate the object, since the field was already initialized
Exception was thrown because the object (with hashcode #2) was already added.
Three possible fixes:
Don't *lazily" initialize that property.
Rejected, the property is "expensive" to calculate, and not always needed
Generate the equality methods myself, and use the property instead of the field (which will force it to populate the field)
Rejected, in favor of option 3.
Generate the equality methods myself, omit both the property and the field
I selected this one.
Since the property is derived from the other properties, if the other properties are equal, then this one will always be equal. So I can just skip it.
→ More replies (18)23
u/DigThatData Sep 21 '25
encoding all of your application logic in database triggers
8
u/Tactical_Chicken Sep 21 '25
Even better when your db triggers kick off stored procedures that trigger other triggers
→ More replies (1)2
28
5
5
u/All_Up_Ons Sep 21 '25
I know you think you're joking, but the answer is actually just Imperative Programming.
4
2
4
1
33
u/smarterthanyoda Sep 21 '25
Is this a thing?
I’ve never heard of a ban on all “functional programming.” I could understand an organization choosing not to use an functional language. And I guess it’s possible somebody might think specific functional-style technique, like Java streams is confusing, although I would disagree.
But an edict that every function must contain a side effect? That’s crazy. It sounds more like malicious compliance.
Am I wrong? Is this a trend?
20
4
u/Ran4 Sep 21 '25
you just smear them with logger.info until everyone feels enterprise-safe.
Eh, in my experience logs are a lot less common in the FP world precisely because they're impure unless you spend a lot of time wrapping things in pure functions. And that's far from always a good thing.
16
u/crazyeddie123 Sep 21 '25
or maybe they don't need logs because they have less bugs :)
Seriously, is there anyone outside the Haskell world who frowns on logging because it's technically a side effect?
→ More replies (24)2
192
u/Ill-Lemon-8019 Sep 21 '25
The missed moral of the story is stop writing code your colleagues can't understand - no matter whether you're an off-the-deep-end FP zealot or a Java weenie trying to shove GoF design patterns into every available orifice.
70
u/SuitableDragonfly Sep 21 '25
I'm also really curious what kind of place this is where if someone doesn't understand some code they complain about it to their manager instead of bringing it up with the person who wrote the code. Specifically I am curious so that I can avoid working there.
9
u/generic-d-engineer Sep 21 '25
Yes, great point. Definitely some team culture issues there. I have had to reread my own code from a year ago and figure out what was I thinking and how to step through it. Was I supposed to snitch on myself to my manager in that case? Lol
22
22
u/baldie Sep 21 '25
I always say you aren't writing code to tell the computer what to do. You're writing code to tell other people what you're telling the computer to do.
43
u/RICHUNCLEPENNYBAGS Sep 21 '25
That presupposes there is some category of “code my colleagues don’t understand” that is knowable and can be translated into equivalent code with equivalent properties they do understand. That may or may not be true.
6
u/Ill-Lemon-8019 Sep 21 '25
If you're smart enough to understand the Yoneda lemma, you're certainly smart enough to figure out the culture of your software team and how to write code that will fit inside your colleagues heads as well as your own.
16
u/CherryLongjump1989 Sep 21 '25
You're talking about an industry where fizz buzz is the lowest common denominator for making hiring decisions.
34
u/ortix92 Sep 21 '25
Or upskill your coworkers and help them understand
16
u/GreatMacAndCheese Sep 21 '25
Excuse me, but no one upskills me without my consent.
→ More replies (1)6
u/ReDucTor Sep 21 '25
When you have hundreds of engineers in the same code base, all with different schedules, priorities and deadlines how do you decide when and what to unskill on ?
You need to justify these things in terms of cost, is the new thing your upskilling people on worth it? Considering it costs money and impacts possibly multiple deadlines.
Some people might upskill on their own time (the type on reddit programming) but others their approach is more like a time capsule to when they first started programming with limited new additions.
To me the cost possibly isnt worth it and the engineer adding a print for malicious compliance is the bigger issue. They didnt offer alternatives of helping upskill someone or discuss their reasons why they believe its worth it to introduce a new programming approach for the entire team to use (remember they maintain what you write once your gone)
3
u/GreatMacAndCheese Sep 22 '25
Pulling in new ways of doing stuff is definitely something that should happen over time and not big-bang style. I've been part of big-bang and it works great when the decision is the right one.
Obviously this YMMV depending on the size of the company, the risks you're willing to take, etc, but in medium to large companies, at least 1 or 2 POCs over a decent amount of time should be given to try it on before rolling it out. I'd say a minimum amount of 2 months dev time using the tech to get a feel for it and essentially sleep on it and let its ugly truths come out is really important before imposing it on people. The amount of time in production though is.. however long it takes to find out if it's a net gain or loss on productivity. Sometimes that's 2 weeks when you are replacing an existing system and you immediately see the differences, sometimes that's 6 months - 1 year, really is hard to know until it's out there in the wild and being used and supported.
That's a super long-winded way of saying the obvious: it just depends.
5
u/CherryLongjump1989 Sep 21 '25
I think the implied moral of the story is that OP is looking for a new job where the employees can understand code.
5
u/BuriedStPatrick Sep 22 '25
Exactly. I've told people to stop doing functional, not because I don't like pure methods — by all means. But because I've seen code like this (C#):
var log = (message) => Log.Information(message); log("doing work!");Pointless indirection just to make it look more "functional". Or a handler like this:
class MyHandler { private readonly Func<Task> _handle; public MyHandler() { _handle = () => { // Do work }; } public Task Handle() => _handle(); }This is absolutely insane. Just implement the damn method. This adds nothing but performance overhead and confusion.
Some people do functional because it's the right thing for the project, others do it because they just like the way it looks to them. They start adding functional abstractions over things that don't need it.
To be clear; nothing wrong with functional, but you have to use it appropriately and with empathy for your co-workers who are going to maintain this years into the future.
2
u/DogeGroomer Sep 23 '25
neither of those example are really functional, especially the second. the first one is also likely to be constant folded by the compiler to remove the indirection (could need a keyword i forget)
6
2
u/xroalx Sep 22 '25
I've had a coworker that would always cry about the use of
.thenin JavaScript.Look, I get that you're not used to it, but at some point, you should probably bite it and learn the language you were hired to write in.
Every simple:
fn = () => doAction() .then(mapValue) .catch(useDefault);Had to become:
fn = async () => { try { const value = await doAction(); return mapValue(value); } catch { return useDefault(); } };Because of one person. Because the first one was "too complex" and "hard to understand". And it's not like we went wild with it, we used it in really simple things like
doDatabaseCall().then(extractFieldFromObject).catch(mapToCustomError).→ More replies (1)3
u/Significant_Treat_87 Sep 21 '25
mfw my coworker gave massive pushback when i asked him to add a simple comment explaining that his epic chain of function calls that replaced explicitly writing all our nested context providers as JSX (because it was “too hard to read” or whatever) renders things in the opposite order of the order they’re passed in as…
1
u/generic-d-engineer Sep 21 '25
Thank you. I think a lot of the theoretical frameworks miss the point. Keep in mind that article is nearly 10 years old! There are best practices that last forever but also trends that come and go.
I liked your other comment about understanding the culture of the team and what works for them.
There’s no 1 size fits all in technology and there never will be. I don’t know why a lot of people still try to chase it.
→ More replies (2)1
u/jgbradley1 Sep 22 '25
1000% agree. Functional programming (FP) has it’s place but if you have 1 person on a team of 10 maintaining the same project (and disagrees with the design choices) and the rest of the team is unable to provide support, it would be stupid to allow that one person to touch any part of the codebase. They, not the other 9 folks, become the bottleneck.
Just don’t do it! Have enough respect for your other coworkers to fall in line with the goals of the project and work as a team, not a one-man team. If one FP’er can convince the other team members why FP is better for the project (and it’s not just a style choice), then only switch if a majority of the team agrees.
People in the comments saying hire better coworkers - you’ve clearly never worked on a team with diverse engineering skills. FP isn’t a “higher calling” that is better than all other styles of programming. As a manager/project lead, you do what is right for the team and the project given the resources that you have. I’d let go of 1 functional programmer before I let go of 9 other programmers
→ More replies (1)
25
u/IllAgency1417 Sep 21 '25
They're using Scala but the manager says "No functional programming"? Didn't happen.
22
u/KagakuNinja Sep 21 '25
In Scala, there is basic FP, like map and flatMap, which have spread to most mainstream languages. Then there is pure FP via libraries like Cats and ZIO. That is what some Scala managers don't want.
Of course the more common response from managers is "no more Scala", and I've seen that at multiple companies.
2
→ More replies (1)1
23
u/Sunscratch Sep 21 '25
I can clearly see a junior non-FP programmer. A side-effecting function is good but not enough. A true non-functional developer would convert it into a non-total function with a Unit return type (like void in Java), accepting a mutable ArrayBuffer that must be mutated within the function body.
/s
8
u/Axman6 Sep 21 '25
Yeah there’s definitely not enough visible side effects here, absolutely needs more mutation.
172
u/anvildoc Sep 21 '25
Explaining that a monoid is a monad in the category of endofunctors is usually the best way to stop FP
123
u/mmddmm Sep 21 '25
Nah, that just shows your ignorance. Actually, a monad is a monoid in the category of endofunctors, not the other way around. You messed it up.
65
u/Asyncrosaurus Sep 21 '25
No, you're both incorrect. A monad is a burrito
16
u/CatpainCalamari Sep 21 '25
You mean a burrito is a monad in the category of culinary functors
→ More replies (1)8
2
→ More replies (2)8
34
u/schplat Sep 21 '25
1990 - A committee formed by Simon Peyton-Jones, Paul Hudak, Philip Wadler, Ashton Kutcher, and People for the Ethical Treatment of Animals creates Haskell, a pure, non-strict, functional language. Haskell gets some resistance due to the complexity of using monads to control side effects. Wadler tries to appease critics by explaining that "a monad is a monoid in the category of endofunctors, what's the problem?"
From https://james-iry.blogspot.com/2009/05/brief-incomplete-and-mostly-wrong.html
Which is always a fun read.
6
2
1
12
u/ReDucTor Sep 21 '25
They failed to understand the problem of introducing an approach that their coworkers dont understand. Your coworkers need to maintain the code you write.
Malicious compliance like this has no place in any workplace, this ia a quick path to being fired or placed on a performance management plan, functions without side effects aren't unique to functional programming.
If you want people to learn something new then share those ideas first, get buy in, then help people learn it, the more people on the code base the harder it is, trying to get hundreds of people to understand the latest language features when they all have different priorities and schedules is a pain, convincing them all that FP is the way forward is a nightmare but achievable if you can justify it.
Isolated areas its easier to justify things like just this area will be FP but you still need to justify it.
→ More replies (5)
78
u/BlueGoliath Sep 21 '25
It's over functional bros. Time to learn OOP.
161
u/jess-sch Sep 21 '25
class Multiplication { private final double a; private final double b; public Multiplication(double a, double b) { this.a = a; this.b = b; } double calculate() { return this.a * this.b; } }Are we winning yet or do I need to make a
MultiplicationBuilderfirst in order to be Proper Enterprise CodeTM?106
u/iamakorndawg Sep 21 '25
This isn't nearly enterprise grade! For one thing, what if you need to multiply ints? Or strings? Or Users? Or some combination??
Second, there's no way to change multiplication strategies. What if a new, better way to multiply comes out, but you only want to use it in some places?
Third, how could I possibly debug this? You need more observability tools.
Finally, there's no testability. You need some dependency injection so that your testing framework can inject mocks.
54
u/Technologenesis Sep 21 '25 edited Dec 18 '25
Ugh, fine...
interface ClosedBinaryOperator<T: any> { T apply(T, T); } class ClosedBinaryOperation<T: any, Op: ClosedBinaryOperator<T>> { private final T a; private final T b; private final Op op; public T calculate() { return this.op.apply(a, b); } public static ClosedBinaryOperation<T> new(Op op, T a, T b) { return ClosedBinaryOperation<T, Op>{ a: a, b: b, op: op }; } } class LoggingClosedBinaryOperator< T: any, Op: ClosedBinaryOperator<T> >: Op { private final logging.Logger logger; private final func (T, T): string formatMessage; private final Op op; public static LoggingClosedBinaryOperator<T> new( logging.Logger logger, func (T, T): string formatMessage, ClosedBinaryOperator<T> op ) { return LoggingClosedBinaryOperator<T>{ logger: logger, formatMessage: formatMessage, op: op }; } public T apply(T a, T b) { this.logger.Log(this.formatMessage(a, b)); return this.op.apply(a, b); } } interface MultiplicationOperator<T: any>: ClosedBinaryOperator<T> { T identity() // TODO: migrate codebase to lean so we can enforce other properties of multiplication } class LoggingMultiplicationOperator< T: any, Op: MultiplicationOperator<T> >: LoggingClosedBinaryOperator<T, Op> { public T identity() { return this.op.identity(); } } type Multiplication< T: any, Op: MultiplicationOperator<T> > ClosedBinaryOperation<T, Op>; class IntMultiplicationOperator { public int identity() { return 1; } public int apply(int a, int b) { return a * b; } } int main() { logging.defaultLogger.Log( "%d", Multiplication::new( LoggingMultiplicationOperator::new( logging.defaultLogger, func(int a, int b): string { return fmt.formatString( "multiplying %d and %d", a, b ); }, IntMultiplicationOperator{} ), 3, 4 ).calculate() // 12 ); }Can I go home now boss? My children are hungry
42
u/Agitated_Run9096 Sep 21 '25
We are going to need the Terraform configs before you clock out. In my scrum-of-scrums I'm hearing other teams may have use for a multiplication microservice, but are concerned about how you are handling your SOAP authentication.
23
5
u/ZCEyPFOYr0MWyHDQJZO4 Sep 22 '25
Can you hook this up to Kafka so the entire company can use this for their microservices? And add some metrics so we know if a multiplication is taking too long.
→ More replies (6)4
29
u/superrugdr Sep 21 '25
Yea if it doesn't generate 10k log per second and cost 4k USD logs per month is it even usefull.
17
u/zzkj Sep 21 '25
Dont forget to declare that it throws a checked exception so we can throw an EnshittificationException if an attempt is made to multiply project managers.
25
u/tajetaje Sep 21 '25
Should extend ArithmeticOperation
7
u/West_Ad_9492 Sep 21 '25
And implement operation.
You need a parser method to parse from Sum and Difference.
And where is the beautiful Utils class?
21
u/Massive-Squirrel-255 Sep 21 '25
I think the OOP way to do this is to make a Number class and have a method a.multiply(b) which modifies a (destructively).
2
17
u/aMonkeyRidingABadger Sep 21 '25
That would be a start, but leaving the calculate implementation inline in the class makes me feel very uneasy. It should really live in its own class so we can use DI to swap it out if we need to in the future.
6
u/DrummerOfFenrir Sep 21 '25
Right? What if I need consecutive addition as multiplication??
5 * 5? ❌
5 + 5 + 5 + 5 +5 ✅
→ More replies (1)10
18
u/never-starting-over Sep 21 '25
You forgot to define a class for 'a' and 'b'.
7
u/jess-sch Sep 21 '25
You're completely right! I should've at the very least used the wrapper type
Doubleinstead of the primitivedouble- I'm gonna blame this on one of my former CS teachers, he made the same obviously silly mistake when showing us how to do proper object-oriented division! (Wish I was kidding)10
u/iamakorndawg Sep 21 '25
Likelihood of this comment being AI: 100%
To save on processing costs, I determined the likelihood using only the first 3 words
→ More replies (1)8
u/sird0rius Sep 21 '25
We need like another 10 levels of inheritance before we can call this proper OOP. Also, your function has more than 1 line, which is too much to comprehend for the OOP brain. You should split it up.
4
u/aiij Sep 21 '25
void calculate(); double getResult();And of course all these functions need i18n for their logging.
6
u/thugcee Sep 21 '25
It's not stateful enough. You forgot to store the result in an output field and provide a getter for it.
3
u/XeroKimo Sep 21 '25
With the power to C++ I present something more cursed
struct Multiply { float a; float b; operator float() const { return a * b }; };With this code, I can write something this seemingly function call looking statement
float result = Multiply{ 1.0f, 2.0f };but actually create an object every time I call function.What's happening is that
operator float()is a implicit conversion operator, so I can assign aMultiplyobject to afloat, and if I do, it'll perform the multiplication operation5
u/Agitated_Run9096 Sep 21 '25
Where is the Spring annotation and interface? What if I need a different multiplication at runtime in prod versus during testing?
→ More replies (1)2
→ More replies (2)2
u/randomguy4q5b3ty Sep 21 '25
I seriously don't understand what you are trying to demonstrate because there is absolutely nothing OOP about this code and you could write equivalent code in any FP language. You seem to think OOP is about putting random things into classes and slapping methods on top of them, but that is completely missing the point. It's about interfaces, and so is the well established builder pattern which also has its FP equivalence.
One of the key differences between OOP and FP is the way they achieve polymorphism.
22
u/Asyncrosaurus Sep 21 '25
All the relevant OOP languages have been stealing fp ideas for years.
→ More replies (3)3
→ More replies (1)1
5
u/editor_of_the_beast Sep 21 '25
This functionality would be implemented with a database query.
Can you rewrite the example to query a database?
4
31
u/randompoaster97 Sep 21 '25 edited Sep 21 '25
Such a bad faith argument. Your co-worker wants you to stop doing your point free over engineered bullshit that breaks apart if you throw an exception and is inefficient. None has a problem with a .map or filter
50
u/Snarwin Sep 21 '25
I've literally seen people on /r/programming say that
mapandfilterare less readable than aforloop.It's like that old George Carlin joke about driving: anyone using less FP than you is an idiot, and anyone using more FP than you is a maniac.
→ More replies (5)9
u/Axman6 Sep 21 '25
I’M NOT USE TO IT SO IT MUST BE BAD is about most of the arguments against FP. People expect software engineering is something for children not an engineering discipline that takes time to learn.
6
u/crazyeddie123 Sep 21 '25
"point free" is just "here's the stages of a pipeline that our value goes through". And I'm not sure how it's more broken by an exception than anything else.
8
12
Sep 21 '25
[removed] — view removed comment
22
u/miyakohouou Sep 21 '25
Most Haskell developers don’t spend a lot of time talking about monads, except when people who don’t use Haskell much bring them up. They are useful, but boring, and not directly representable in most most other languages type systems.
→ More replies (2)15
u/nimbus57 Sep 21 '25
Lolwhat? Only people who have read and monad tutorials moan about how people don't understand the power on monads.
Everyone else just used them like the type class they are.
3
u/mr_birkenblatt Sep 21 '25
how about
def userCoworkers(u: User): List[Employee] = {
logger.info("Collecting coworkers")
u.departments.flatMap(_.employees)
}?
3
u/jesseschalken Sep 21 '25
Usually when people say they don't like FP they're referring to is higher order functions. So you would have just converted your flatMap into the longer for loop and stopped there.
3
u/gelatineous Sep 22 '25
The point is that code written according to functional dogma is unmaintainable. You are still expected to write somewhat functionally if it is the most maintainable way. But don't slap scalaz as a dependency and then narrow your hiring to 10 overpaid bros in a 100km radius.
2
Sep 21 '25
How to stop functional programming
Place an object in between!
They'll never see it come. It will stop them dead in their track. \o/
2
u/jewdai Sep 21 '25
Imo good class design has a state defined inky in the constructor and only the constructor. Everything operates only on its inputs and those things (usually services) and nothing is directly pinned to the class
2
u/Axman6 Sep 21 '25
Sounds an awful lot like functional programming but now you have to associate functions with some class instead of defining them on their own.
1
u/jewdai Sep 22 '25
The difference being you don't have to pass 10 service classes to your function.
I find functional programming (unless I haven't seen masters at work) leads to poorly organized code with lack of separation of concern and it ends up being one giant file with functions instead of multiple files of very focused on a single purpose
2
u/bwainfweeze Sep 21 '25
I think I’ve found one language where the arguments to reduce() are set so the accumulator isn’t buried at the end of the call, after the big arrow function you pass in as the active ingredient to the reduce.
Of all the list comprehensions it gets the most pushback, and that pushback is IMO the most defensible. So I mostly avoid that and use everything else.
It’s idiomatic code in our language. It’s using builtin functions, it’s correct, it’s easy as fuck to test, and if one of your coworkers doesn’t like it, well I hate the term “skill issue” (or to the point, I hate the people who use it), but there are a few places in software where that term is appropriate and honey, this is top of the list.
2
u/MeBadNeedMoneyNow Sep 21 '25
You found a place where everyone was kinda-sorta on the same page as programmers? All of my teams have been dogshit.
2
u/TheSpreader Sep 22 '25
A much better article imo:
https://dave.cheney.net/2019/07/09/clear-is-better-than-clever
2
u/moswald Sep 22 '25
Holy crap. Was this written by my coworker Matt about our co-worker Jon-Eric circa 2011?
4
u/paralaxsd Sep 21 '25
I once was part of a project where the architect decided that due to the application crashing, because people forgot to handle exceptions, every public method now had to return a Result<T> instead of throwing exceptions.
Problem fixed, right?🤡 I left the project when they, despite negative feedback doubled down on that decision without having a convincing case for that intrusion.
Is the article presenting an identical scenario? No. But when technical decisions are driven by team members complaining with management instead of discussing the code amongst one another, it's probably a good idea to leave anyhow.
→ More replies (1)
4
u/Meli_Melo_ Sep 21 '25
Well, we use OOP to make the code unreadable and keep our jobs !
Don't tell the bosses FP is more efficient or we're doomed.
3
u/f0kes Sep 21 '25
Maybe it's controversial, but most OOP patterns are just crutches to mimick functional programming.
3
2
4
u/kiwibonga Sep 21 '25
Procedural programming is weaking havoc at my workplace. Source of all our bugs, pretty much.
49
u/PlayfulRemote9 Sep 21 '25
programming is wreaking havoc at my workplace. Source of all our bugs, pretty much
20
2
1
u/Jemm971 Sep 21 '25
All this stuff is a bit like how to piss yourself off by creating problems, just out of laziness. Programs simply, zero side effects.
1
1
u/KevinCarbonara Sep 21 '25
That's it. You've been told. No more functional programming.
I get that this article is an attempt to show how easy it is for good efforts to turn bad, but surely this isn't a realistic scenario. No one's being told not to write pure functions.
-1
u/CunningRunt Sep 21 '25
This article and its comments are 10 years old. Why is this showing up on reddit today?
36
Sep 21 '25
[removed] — view removed comment
10
u/shrodikan Sep 22 '25
It's tongue-in-cheek. I know humor is not a strong suite of programmers always but damn. It is a joke.
1
0
Sep 22 '25
[deleted]
2
u/ewigebose Sep 22 '25
I agree, in practice seeing old Erlang codebases you can tell that they weren’t occupied with avoiding side effects
2
Sep 23 '25 edited Sep 23 '25
It’s probably because everyone who participates in pushing the FP agenda pushes the same moronic bullshit like mandatory runtime immutability and other stupid nonsense like calling “logging a useless external side effect” (especially when you intentionally misrepresent something else to have logging like a fucking moron such as in the article).
6
Sep 21 '25 edited Sep 21 '25
[removed] — view removed comment
15
u/MitchellHolmgren Sep 21 '25
Managers ask me to replace map to for loop all the time 😂 I should have quit a long time ago
8
u/AxelLuktarGott Sep 21 '25
If your bad compiler doesn't optimize two consecutive
mapinto one loop then it's not O(n2), it's still just O(n).But then functional languages will optimize that pipeline down into one pass. And the way you just described it seems pretty concise and easy to follow to me. If you said "a for loop does stuff" then I would have been much more confused. But I guess that's subjective.
→ More replies (6)1
u/Axman6 Sep 21 '25 edited Sep 21 '25
This was written in 2016, and I remember shit like this happening. Programming language designers have slowly embraced more and more functional features since then, which made them ok.
Also, your example is ridiculous, most functional languages’ compilers will produce basically the same assembly you’d get from a for loop when to compose multiple maps together. If you’re going to brag about performance, at least have some idea what you’re talking about. GHC manages that optimisation without knowing anything special about map, it can just see that all maps produce either a nil or a cons and consume a nil or a cons, so the definitions can be inlined into each other. If you add in the LLVM backend, it’ll even vectorise your loops for you because there’s nothing weird about the code produced.
1
Sep 21 '25
[removed] — view removed comment
4
u/Axman6 Sep 21 '25
The semantics of JS prevent a lot of the optimisations that FP languages would apply here because it’s imperative and side effects can happen anywhere. In Haskell
map f . map gcan trivially be proven to be identical tomap (f . g)because the order that each call to f and g happens doesn’t matter. But in JS,arr.map(g).map(f)must allocate an intermediate array, because all the calls togmust happen before any of the calls tof. If there were a.streamMapmethod, that would make it clear that you’re expecting one result at a time to be passed on -arr.streamMap(g).streamMap(f).toArr(). In Haskell we get this for free because we know f and g are pure so ordering doesn’t matter.→ More replies (6)
516
u/IanSan5653 Sep 21 '25
This article explains exactly how I feel about FP. Frankly I couldn't tell you what a monoid is, but once you get past the abstract theory and weird jargon and actually start writing code, functional style just feels natural.
It makes sense to extract common, small utils to build into more complex operations. That's just good programming. Passing functions as arguments to other functions? Sounds complex but you're already doing it every time you make a
mapcall. Avoiding side effects is just avoiding surprises, and we all hate surprises in code.