HNHacker News
TopNewBestAskShowJobs

leafboi

-4 karma · joined July 5, 2020

submissionscomments
leafboi··on Classes are a way of writing higher order functions
>You chose a definition among many and then dismissed the submission as "confused" because it does not meet your definition.

My definition? I quoted wikipedia. A lot of people use "my definition" Basically under "your" definition C++ and go might as well be a functional programming language.

>Considering that ML is one of the most impactful functional programming languages both in theory and practice, I think it's right to call that absurd and dogmatic. If you take it as a personal attack that I called your argument absurd, I don't know what to say. Maybe grow a little bit of skin?

Why grow skin? I literally didn't care. I just decided to call you junior because you were acting like one. It seems like you cared more. I was just explaining to the other guy why I called you a junior. I recognize the attack but I literally don't care, but that doesn't mean I won't respond or address it.

>I don't need to provide a definition to find a flaw in yours. I did not come into this submission looking to smugly dismiss the topic at hand with my obviously irrelevant preferences for terminology. You did.

My Definition doesn't have flaws. Like I said, if I expand it to encompass mutability (as you have) then you can place Go and C++ on the functional pedestal. I haven't used ML but clearly a language like ML only allows mutability as a small exception that's rarely used otherwise there's no point to classify ML as functional.

But let's get back on topic. You literally said that no PL theorist would agree with me. But look at wikipedia. Apparently many do. So you're wrong.

leafboi··on Classes are a way of writing higher order functions
>Unsolicited advice: Sophomoric pedantry isn't a good look.

Starting conflict and calling people "dogmatic" and voting people down is not a way to win people over. I can see a number of paths this road could have gone down where you can easily get another person to agree with your ideas as an alternative viewpoint despite a wikipedia article saying otherwise. You chose to take none of these roads, maybe largely because you don't know how to do this.

>I don't really care what a wiki article says.

Right because your opinion is the best opinion and only opinion that matters. The community opinion and the majority opinion has no relevance to you because you participated in "functional development for over a decade." Whoop dee doo. I chose a definition of functional programming that has huge relevance to the community at large. You on the other hand... haven't even stated your definition yet.

Unsolicited advice: Arrogance and the inability to admit your own mistakes is not a good look. A decade of experience does not earn you the right to act like an ass hole nor does it make you a good programmer.

leafboi··on Classes are a way of writing higher order functions
>You have missed the point.

Tell me what you think the point is. Typically when someone thinks a point was missed they address the point rather than devolve the conversation into a condescending description about my character and how I should act. It's a sort of tactical what you're doing here. But who cares, no one is reading.

It's curious how you don't even address my points and just say that I missed the point when I'm the one dictating the point in my original comment. Typically this isn't how you respect other people and get them to respond positively to your comments, what you're doing will draw other people to support you but anger your target because of the condescension. I'm not sure what you're objective is because people aren't really reading this thread... it's already buried.

>It’s curious you think this piece is written by a “JavaScript programmer”,

The examples in the original piece are in javascript. Why don't you RTFA before commenting on the "point."

>and the person who responded to you here is a “junior” — the implication being that you know more.

The Junior thing was more of a retort. I said it with full awareness of what it implies and how the other person would take it because his tone obviously implies that he doesn't think he's a junior. Basically the replier has his own opinion which he is entitled to say (and that I respect) but when you say things like "dogmatic" and then vote me down... that's just not respectful. Since I can't vote him down I inject a bit of subtle rudeness in my replies as a subtle retort in return. Just being a mirror. Similar in a way to the subtle game you're playing. That's all this is.

>It might help to take a step back and assume intelligence in others: what if these people are smart? What could you learn from them? If you think the idea is wrong, assume it’s coming from a peer. One way you know you are doing that, is if you form your disagreement as a question.

Maybe you should take a step back and look at your own post. Telling people to shift their thinking implies you have a sort of superiority complex. As if you're not the one that's mistaken. How do you know I'm not a peer? How do you know I'm not superior. Perhaps you should take a look at yourself. You seem like a guy who thinks he's superior to me in programming but you haven't demonstrated as much, you haven't even addressed the point.

You went on a side tangent talking about my behavior. Trust me, if you want someone to change or listen to you, talking to them like this is not the path.

You want to know what will make people respond to you and listen to you? Address them without any subtle disrespect. It's very simple.

You could've responded to me like this:

   I disagree with you. I also think there was a misunderstanding of the point. Here's why...
By proving the other person wrong without being disrespectful you can change the other person's' character. But obviously this isn't our objective here is it?

That being said take a look at this wikipedia post and tell me. Who missed the point?

https://www.wikiwand.com/en/Functional_programming

   "Functional programming is sometimes treated as synonymous with purely functional programming, a subset of functional programming which treats all functions as deterministic mathematical functions, or pure functions. When a pure function is called with some given arguments, it will always return the same result, and cannot be affected by any mutable state or other side effects. This is in contrast with impure procedures, common in imperative programming, which can have side effects (such as modifying the program's state or taking input from a user). Proponents of purely functional programming claim that by restricting side effects, programs can have fewer bugs, be easier to debug and test, and be more suited to formal verification.[1][2]"
Literally that's the definition I'm following. It's one form of the definition and certainly a popular one. That's my opinion. You disagree? You think I missed the point? Elucidate. The original poster can disagree but my opinion is far from as he puts it "absurd."

Read the article. What definition of functional programming does that class with a setter even fit under? Ok he redefined it as a higher order function... Is what he doing procedural programming or functional programming. It looks to me he's doing a bit of everything and calling it a function. Does the guy even know that the class keyword is just sugar for "function" in javascript?

Look at this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

Literally it says "classes" are just special functions. He's just reiterating the javascript spec as if it's a new fangled discovery. In fact, before ES6 all "classes" were written with the keyword "function." No dude. The article writer doesn't get it and neither does the person who responded to my post. When you do OOP with LISP you're not doing FP period. The article writer just noticed an isomorphism and is likely amazed by what all JS programmers were doing before ES6. Not to be insulting but the parent poster likely doesn't have much experience.

>I took the time to respond to you, because it looks like you have some real love for programming, but know less than you think. You can grow a lot more if you shift some of your thinking

I too took the time to respond to you. Despite your condescending attitude/game. Let's see where this goes.

leafboi··on Classes are a way of writing higher order functions
No I'm using the mathematical definition of a function. ML is not Math nor is it purely functional.

All functional languages need to bend the rules a bit in order to have side effects but in general the person is not writing functions and therefore is not getting the benefits of using functions.

FP is about reducing and restricting these functions that break the rules. Defining a class in terms of mutations and side effects is going against the philosophy of FP.

leafboi··on Classes are a way of writing higher order functions
Ok. No. There's a lot of confusion with semantics. Following the most used definition of OOP as defined by JAVA, C++ and C#:

Classes are in no way functions in the FP sense because classes mutate state.

Classes are in no way functions because calling methods requires the instantiation of unrelated state. Example:

   class A
       def __init__(self, a, b, c):
          self.a = a
          self.b = b
          self.c = c
          self.banana = create_banana(create_gorilla(create_jungle()))

       def process_a(self):
          return process(self.a)
process_a cannot be used unless a, b, c and the banana plus the gorilla holding the banana and the entire jungle the gorilla lives in is instantiated.

Let's talk about terminology. There are three that often get mixed up.

   Procedure = a set of instructions that could encompass mutating and changing state.
   Function = a box that when given input produces an output. The box cannot modify the universe. It can only produce something new when given an input. 
   Object = A grouping of a set of procedures and state that can mutate. 
The javascript programmer OP is mixing up function and procedure. He defines a procedure and says that it can be a class. A procedure can be a class as it's just a set of instructions which can encompass defining scope, state and more procedures restricted to scope and state (aka an object).

This thing right here, written by the OP:

  function setFirstName(firstName) { 
    fName = firstName
  }
Is not a function... it is a method or a procedure that mutates state.

A function can do none of the above.

That's it.

leafboi··on Read Fewer Books
The thing with reading is that the main point is often buried beneath realms of text. A movie can deliver the same concept in two hours when a book typically takes several days.

Another thing with reading is that there's no logical reason why the content you're reading is better than television. If TV can have crap so can books.

I have found that reading builds biases better than television. The reason is that reading takes much more effort than television and oftentimes the more effort you spend on something the more bias towards it you develop.

I've found that in general if you want to have a larger breadth of knowledge... youtube videos are actually awesome at distilling concepts and getting to the main point.

I'm saying this as someone who use to and still actively reads books.

leafboi··on Lee Kuan Yew's Singapore
Good point.

Additionally, complexity also scales. A dictatorship relies more on the common sense of the dictator while a democracy relies on a set of written laws that grows with complexity over time. A single party does not need a contract while at least two parties must engage in a contract called a written body of law in order to come to an agreement. This "contract" is edited and amended over time with no limit to how complex it gets.

In fact, that complexity balloons to a point where only experts can understand the law (lawyers). It also grows to the point where the law is so complex that it can become internally inconsistent and develop loop holes that do not serve the original intended purpose of the law.

This allows for entities to exploit these loop holes. Of course only entities with enough money to afford the "experts" to find the loop holes and exploit them will be able bend the laws to their advantage thereby causing only the rich and elite to become more powerful.

The above is the basic theory about the anthropological progression of your typical democracy. Growth in complexity of a body of law to the point where only the elite can afford to hire specialists to take advantage of said law.

That is the main danger of democracy. Excess Complexity to the point where only people who can afford specialists to change the law can exploit it to their advantage. Complexity of law also leads to all kinds of other phenomena that niche experts and common people can take advantage of as well. For example constructors that take advantage of property law.

The scary thing about the theory above is that there is a TON evidence of this. Almost every modern democracy in the world suffers from ALL of the problems above. Literally find me one that doesn't.

leafboi··on Lee Kuan Yew's Singapore
The problem is there's no definitive evidence that proves this yet.
leafboi··on Lee Kuan Yew's Singapore
You shouldn't be asking yourself whether the post is sarcasm. You should be asking yourself does my post fit with the logic provided by the initial post?

Then if the logic fits with the logic of the initial post you should ask yourself is the logic absurd?

If so then that means the initial post is absurd.

leafboi··on Lee Kuan Yew's Singapore
Discuss away. It's just that posts like these tend to actually completely assassinate the character and all discussions related to it. I'm just putting this here to temper the sentiment before it gets carried away. I am in no way trying to censor all criticism.
leafboi··on Lee Kuan Yew's Singapore
Some views suggest that the political structure of the United States is in many respects an oligarchy, where a small economic elite overwhelmingly determines policy and law. Some academic researchers suggest a drift toward oligarchy has been occurring by way of the influence of corporations, wealthy, and other special interest groups, leaving individual citizens with less impact than economic elites and organized interest groups in the political process.

A study by political scientists Martin Gilens (Princeton University) and Benjamin Page (Northwestern University) released in April 2014 suggested that when the preferences of a majority of citizens conflicts with elites, elites tend to prevail. While not characterizing the United States as an "oligarchy" or "plutocracy" outright, Gilens and Page do give weight to the idea of a "civil oligarchy" as used by Jeffrey A. Winters, saying, "Winters has posited a comparative theory of 'Oligarchy,' in which the wealthiest citizens – even in a 'civil oligarchy' like the United States – dominate policy concerning crucial issues of wealth- and income-protection."

In their study, Gilens and Page reached these conclusions:

   When a majority of citizens disagrees with economic elites and/or with organized interests, they generally lose. Moreover, because of the strong status quo bias built into the US political system, even when fairly large majorities of Americans favor policy change, they generally do not get it. ... The preferences of the average American appear to have only a minuscule, near-zero, statistically non-significant impact upon public policy.
   — Martin Gilens and Benjamin I. Page, 2014
E.J. Dionne Jr. described what he considers the effects of ideological and oligarchical interests on the judiciary. The journalist, columnist, and scholar interprets recent Supreme Court decisions as ones that allow wealthy elites to use economic power to influence political outcomes in their favor. "Thus," Dionne wrote, in speaking about the Supreme Court's McCutcheon et al. v. FEC and Citizens United v. FEC decisions, "has this court conferred on wealthy people the right to give vast sums of money to politicians while undercutting the rights of millions of citizens to cast a ballot."

Nobel Prize-winning economist Paul Krugman wrote:

   The stark reality is that we have a society in which money is increasingly concentrated in the hands of a few people. This threatens to make us a democracy in name only.
   — Paul Krugman, 2012

I would say, again, that the answer is complex and multifaceted. It is not exactly clear whether authoritarianism or democracy is better. One thing is clear though... both are far from perfect.
leafboi··on Lee Kuan Yew's Singapore
The hospital was built to save lives. Now that the initial wave of the pandemic is over the hospital sits empty.

Private enterprise would never spend resources to build hospitals to save lives simply because it isn't "profitable." Only a centrally planned government will pull off such a feat purely in the name of saving lives without regard to profit. I mean literally no non-profit in the united states is capable of building a hospital just to handle a temporary spike in demand.

leafboi··on Lee Kuan Yew's Singapore
>No, America had (and still has) central authority make (making) a conscious choice not only not to direct energy at that purpose but to actively interfere with subordinate authorities attempts to do so for purposes linked to maintaining institutional power by placing blame.

Right of course. You're talking about the HBB, the Hospital Building Bureau the government sponsored central entity that builds all hospitals in the United States obeying trump and not building any hospitals.

According to wikipedia:

   Health care in the United States is provided by many distinct organizations.[1] Health care facilities are largely owned and operated by private sector businesses. 58% of community hospitals in the United States are non-profit, 21% are government-owned, and 21% are for-profit.
Which is pure BS. Hospitals are centrally planned like you said by the HBB! Central authorities are stopping hospitals from being built! Nothing to do with private enterprise or the lack of central control! My friend told me it's because private enterprise isn't reacting fast enough to demand because the demand is temporary and there really is no profit for private business to build more hospitals! What a stupid answer. Obviously it's a government conspiracy.
leafboi··on Lee Kuan Yew's Singapore
:)

Roman empire failed after 1500 years.

Portuguese Empire failed after 584 years.

Khmer empire failed 630 years.

Kush Empire failed after 1420 years.

Silla Empire failed after 980 years

Holy Roman empire failed after 838 years

Kanem Empire failed after 676 years.

Chinese empire failed after 2000 years.

I asked my friend what's the connection between all these Civilizations? He told me "Empire."

What a stupid answer.

The connection is "failure." You know what hasn't failed! The United States of America that's what!

leafboi··on Lee Kuan Yew's Singapore
All the civilizations I mentioned were authoritarian. Egyptian Pharaohs, Roman Caesars, Chinese Emperors. The history of all great civilizations is by a huge majority created and maintained through authoritative rule.

In fact, modern anthropological theory states that the first step in the formation of a big civilization requires central authorities to form first.

>what we should really be looking at is whether they provide for their citizens the best -- which democracy does

America didn't have the capability to provide room for the influx of covid-19 patients. China built a hospital in a week. There's no question that for this specific instance, authoritarianism provided better for its' citizens than democracy.

Like I said. Complicated. Multifaceted.

leafboi··on Lee Kuan Yew's Singapore
I think because HN's audience is mostly US based there's a high level of bias towards democratic governments.

I think if we all take a look at it from a unbiased angle it's all really apples and oranges. A bad dictator is not so different from a democracy electing bad leaders and a good dictator is not so different from a democracy electing good leaders.

The thing with a democracy is that you have a lot of checks and balances so an elected bad leader can't do much damage... but then again an elected good leader can't do much good either.

leafboi··on Lee Kuan Yew's Singapore
Don't think that the democratic process guarantees a good hand off... it's still a crap shoot and a lucky draw. See current President Camacho of the United States.

Unlike a dictator, the aggregate will of the people never serves the self interest of a single individual. The issue with majority rule is that the aggregate intelligence/judgement of the people is likely not matched with what is required to select a good leader.

leafboi··on Lee Kuan Yew's Singapore
Let's not turn this into a character assassination. That's what they do in politics and I hope HN is above this stuff.

Henry Ford invented the modern factory by bringing the conveyor belt into the manufacturing system. He was also an anti-Semite who supported Hitler.

Do not ignore the fact he was an anti-semite, but also do not ignore the fact that he invented the modern factory.

People are complicated, contradictory and multifaceted creatures... be unbiased and do not discount one quality because you disapprove of another.

leafboi··on Lee Kuan Yew's Singapore
Obviously the world is a super simple place with super simple answers to seemingly complex questions. When I asked my friend which is better authoritarianism or democracy he told me the answer is complicated. I told him to look at the evidence:

Almost Every civilization in history: egyptians, romans, greeks, China was more or less some form of authoritarian government. They all failed.

Basically every single civilization that existed before modern civilization existed Failed! The fact that the United States of America hasn't failed means the US way (democracy) is the best and only way!

leafboi··on Why is OOP still so widely spread?
>Worked with that in .NET a bit, specifically this one: https://github.com/reactiveui/ReactiveUI Not a big fan. For example, when I wanted to fix a bug, put a breakpoint to the code that failed, and reproduced, there was no way to tell who or why sent that event, the original context was already lost. For this reason I prefer simpler ways with interfaces or lambdas. Not sure if that’s a problem of the approach or the implementation I used. But generally speaking marshalling contexts is complicated and is a common source of bugs, YMMV.

The tooling is irrelevant to the paradigm itself as tooling can improve over time. Either way it's the dominant pattern right now for UI. I'm not an expert in it but I do know that the tooling for react/redux right now is quite good.

>I can see how it can be the case on servers (one reason is economy, for many companies it makes more sense to rent more EC2 instances instead of writing better software), but I’m not sure same applies to client. In the browser, you have the same 16.6ms performance budget for optimal usability. The fact that JavaScript is generally slower than compiled languages makes things worse.

In servers it's not a priority because the database is the bottleneck. Servers need to just be faster than the database and that can easily be achieved with something slow like ruby or horizontal scalability. The pattern in web development on the backend is highly similar to functional programming. Web servers are mostly stateless and state is stored in a database, so you can basically increase the amount of servers that access the database for basically an unlimited amount of capacity for parallelism. Of course all of this is bottlenecked by the speed of your database.

For the front end it's actually less critical, believe it or not. Even the shittiest phone is already plenty powerful. Most of the slowness in this area is still in IO or data transfer. All those loading screens you're waiting on is mostly data transfer and database bottlenecks. The reason why UIs are so slow nowadays is because literally half of most UIs live on the cloud and are downloaded by your browser/mobile device. We are well past the time when UIs take 16.6ms to load. 1s is actually quite good nowadays.

>Every design pattern can be abused, and none of them is a silver bullet

Except I didn't abuse a design pattern. I used an incredibly general example. Basically a single method in a class will likely not be utilizing all members in that class yet at the same time you cannot use a method without instantiating ALL members. it's a pointless restriction that is solved by changing the method into a function that operates only on its input parameters.

When something is wrong with the most trivial of all examples... then something is wrong with the entire paradigm.

>If you want to reuse that code, make it a global function, all OO languages have them or equivalents (static classes in C#).

Which is another of saying "use functions in namespaces instead of objects." I recommend that if you're doing C# or JAVA you should write all your functions this way. There is no reason why you shouldn't have this level of re-usability on ALL your code. There's no point in making things methods tied to random state.

>See the example linked in my previous comment (I hope C# is readable enough even for non-users), the iReadStream object returned from setupConnection can potentially hold quite a lot of referenced things, GZIP compressor, AES implementation, yet for the user of that object it’s just a trivially simple interface with a single read() method.

I looked at it, the use of static keyword makes it basically plain old functions rather then methods. I wouldn't call it OOP. But whatever it's just words. Basically I'm saying: "shared mutable state in classes offers no benefits and makes your program less modular" You can still call it OOP if you want but if you agree with my statement then overall we're in agreement.

>Due to polymorphism, OOP allows to write functions operating on data types unknown to either compiler or the programmer writing that code, as long as the types implement the expected functionality.

This is just a type class or an interface or whatever you want to call it. It exists in other languages as differently named concepts. I would say it's not an OOP thing. An untyped language like python basically every single variable type in that language is Polymorphic to each other.

>Microsoft replaces both data types and code of their IOutputStream.WriteAsync method with windows updates. Their changes don’t break my code, they don’t even require me to recompile it.

That's because you already bent your code to fit their interface. They maintain that interface and you don't have to change anything. This is universal to all types of programming paradigms FP included.

>These things are orthogonal. No one forces you to return half-initialized objects, you can throw an exception instead.

In an FP language you are forced to never even be allowed to have half-initialized objects exist. The concept doesn't exist in FP. This eliminates a whole class of potential errors from your program.

In procedural languages a common pattern I see is this:

   var x = A();
   x.a = 1
   x.b = 2
   ....
Basically if the procedures are written out like that it leaves room for a potential error/mistake/bug to occur. What if you miss instantiating something?

In a functional language it must be done only like this:

   var x = A{1, 2, ...}
And most FP languages do not allow nulls or future modification. Meaning you have to figure out the true value of every variable and shove it into the object during instantiation. These are essentially procedural or temporal errors that functional programming gets rid of by eliminating the concept of time. It asks you to define the correct piece of data rather than treat it like a container that you fill with data over time.

The language Elm that I recommended earlier is an FP language that takes concepts to the extreme. In ELM you can absolutely never have a runtime error (other then blowing up memory). It is impossible because the language doesn't allow you to do stupid things that would otherwise trigger runtime errors in other languages like C# or C++. It eliminates a whole class of errors you find in C, C++ or C#. The only thing you have to deal with is logic errors.

>1. Why not? We have objects, they have methods which mutate their internal state. Looks OOP enough in my book?

You referring to your example? I dunno it looks to me like they're static meaning they don't mutate internal state. Do those functions in your example modify variables that aren't part of the parameters? I think I'm being liberal with my use of "mutate internal state." In this case I mean a member variable of the class. You labeled it static and therefore the function is basically just a procedural function. I wouldn't call it OOP anymore then I would call a function in C OOP.

>2. If I would have actually implemented these objects instead of writing // TODO comments, these implementations all would have a fair bit of internal mutable vars, due to buffering, AES blocks, and other shenanigans.

Well they aren't mutating global vars are they? If it's just mutating scoped variables within the function then it's still not OOP in my book. It has to modify a variable outside of it's scope that's part of the instantiated class. I wouldn't call this function FP either. It's definitely procedural programming similar to C or golang.

To make it clear I'm saying Procedural programming > OOP and FP > OOP and it's still up in the air for procedural programming vs. FP.

Also the in the banana gorrila example I compared a class to a function.

   def addOneFunc(x):
       x += 1
Just so you know the above example is not an example of FP. That is a procedural function that mutates state. I was using it to show you how even Procedural programming is better than OOP.
leafboi··on Why is OOP still so widely spread?
>Have very little idea, I don’t do web development.

Then I would say you are a bit behind the curve when it comes to what the majority of people are doing in UI development. The majority of UI development happens on the web. Current practices involve using a functional paradigm to deal with mutable state. The pattern is called Functional Reactive Programming. FRP for short.

>I think the majority of programmers nowadays, and have been for decades, working on internal line of business applications. No reason to generalize their experience over the rest of the software development.

I'm generalizing over a vast majority. The vast majority of SW development is web stuff and basically in web development performance is not the priority. Useability is. Basically people choose languages and frameworks like ruby, php and python over C++ for ease of use. Software development bootcamps emphasize javascript not C++.

These languages are so slow that it doesn't matter if you follow the functional style or not.

>JS is merely passing data to WebGL APIs. These APIs are implemented in web browsers, and underneath browsers in GPU drivers. Both modern browsers and GPU drivers have millions of lines of code written in C or C++, and JS is not performant enough to replace these, not even close.

Yeah I know. Don't write your OS or OS drivers in javascript. In general the platform is implemented by one guy and everyone else operates in his universe. Most web developers and even game developers won't get into the internals of OpenGL.

>Yes, and that’s usually a good thing. Here’s a method: https://docs.microsoft.com/en-us/uwp/api/windows.storage.str.... You can’t write bytes to a stream without the stream. From API design perspective that’s a feature, not a bug.

You missed the point. Object.write is worse than write(stream) because Object can hold more things than just a stream. If you implemented Object.write instead of write(stream) then your write method is forever tied to irrelevant context. Again see the banana gorilla jungle example.... literally the addOne method cannot be reused without creating a banana, a gorilla, and a jungle.

If you want to restrict your function to operate on certain data types you do this by restricting the input parameters. That's it. There is no need to attach it to irrelevant context when it doesn't even really touch other parts of the state.

>Visibility of that state. Usability of the API. Composability of the overall thing.

In FP you hide private state in functions. It is hidden anyway. "C" below.

   A -> function(A){return B(A, C)} -> B  (C is hidden state)
If you think about your programs this way where hidden state is ephemeral you never will have objects that are in a state of half correctness. The object only has two states: Existence or non-existence, never a state where only half of it's properties are initialized. The hidden state is forever stored within the function expression, ephemeral and inaccessible as it should be.

This is 100x better than the explicit use of "private." Hidden state in this case is truly hidden by structure rather than by syntactic tags.

Useability is equal. As you yourself as said object.verb() is semantically equivalent to verb(object).

Objects are not more composable than functions. The only way to compose objects are through inheritance, (which is bad) and object composition which requires the parent object to be aware of the child Object.

Example:

    class B():
        ....

    class A()
       def __init__(self, B)
           self.b = B


    A is aware of B, therefore A is not modular. You have to customize A to be aware of B to compose it with B. 




    universal function composition:

    def compose(f: A->B, g: B -> C): A -> C {
          return function(x: A){return g(f(x)); }
    } 

    def addOne(x: int){
       return x + 1;
    }

    def timesTwo(x: int){
       return x * 2;
    }

    addOneThenTimesTwo = compose(addOne, timesTwo)

    addOne is not aware of timesTwo, timesTwo is not aware of addOne, compose is universal meaning it works on any function of type A -> B. 

In terms of composition. Combining functions to form other functions hands down beats combining objects to form other objects. Literally no contest. It's one of the defining features of FP. All your FP primitives are literally tiny modular bricks that your compose into data pipelines that pump data from Input to Output. It is at the two ends of this pipeline where the functional style breaks down and you have to either start breaking rules or using complex abstractions to deal with IO and mutable state.

>The internal state of the object returned from setupConnection method can be just the TCP socket, or it can be a socket + AES decryption + a decompressor.

These are all static and stateless IO functions. You're not really doing OOP without an internal mutable var. You could literally rename that class to namespace. (I'm not too familiar with C# but I'm assuming the use of the word static means that the function is not tied to instantiated state meaning all state arrives in as a parameter negating the need for using the word "class" over "namespace")

leafboi··on Why is OOP still so widely spread?
>What about React? They say right on their front page: “Build encapsulated components that manage their own state, then compose them to make complex UIs.” That’s a textbook definition of OOP.

I made a mistake here. Not react. Redux. Basically the DOM update loop that's popularly associated with languages like elm and frameworks like react. That world changes so fast I'm not even sure if Redux is relevant anymore.

>My primary focus is meeting requirements and budget. All technical decisions about reusability, modularity, performance, and the rest of them, are driven by these two.

Then do what you need just know that OOP doesn't contribute to reusability. I actually don't see any benefit to is over just procedural programming.

>Almost everything has a performance budget. For a web app difference between 1ns and 1ms doesn’t matter at all, but difference between 100ms and 1 seconds still matters, users will complain, search engines will downrank. Desktop apps ideally need to respond within 17ms because mainstream displays render at 60Hz. Performance cost of immutability is huge, can be 1-2 orders of magnitude, for 2 reasons. (1) memory allocations are relatively expensive (2) CPUs have cache hierarchy, main memory is like 20-40 times slower than L1D cache, each time you allocating a new immutable object it’s pretty much guaranteed to be out of caches.

Nah most CPU stuff is so fast none of this matters anymore. For web development, (I'm a web developer) They use languages like python with garbage collectors to handle stuff. The reason is because the bottlneck lies in IO. Python is slow but the database is slower and that's where they use a procedural language like C. For browser stuff they use javascript now and the DOM and the redux pattern so pure performance is no longer as critical because stuff is so fast anyway. I mean really when the browser is loading you're waiting on IO, not on rendering or javascript.

>Also CAD/CAM/CAE, realtime multimedia, some projects in embedded esp. real-time stuff. By the way, these areas are what I mostly do for a living.

That's similar to gaming right? Graphics. So essentially yes you do work in an area where FP is probably not the best choice. However the majority of programming nowadays is Web sites. Even so JS and functional programming is powerful enough to drive 3D graphics on web browsers.

>However, the real value of OOP is when you have to deal with complex mutable state. Every single time mutable state is essential to the problem (rich GUI is just one area where it’s the case, there’re others), OOP has no good alternatives.

What's the difference between a function that modifies state and a method that modifies it's own internal state? Almost none except the method is tied to context. The method cannot be used outside of that context.

You have to instantiate state and irrelevant context to use a method and that is the problem. The alternative to OOP is to just use procedural programming because literally there is only one single difference that separates the two paradigms:

Methods are tied to context, functions are not.

In knowing this you will know that basically with OOP you're tying your hands together for no good reason. You can write those exact same methods as separate procedural functions to get the same functionality without the downsides.

> I disagree that OOP promotes mutable state for cases when it’s not needed, it all depend on the language. JavaScript or Python don’t support immutable properties of their objects, but C# and (to lesser extent, but still) C++ do.

It promotes it by virtue of being the only feature that separates a class from a namespace. If you're not using a mutable variable in your class you're not doing OOP because what you're doing is isomorphic to writing a namespace with functions. (You can have private functions in namespaces for certain languages to btw.)

As I side note to easily about the FRP pattern you should just checkout ELM. https://elm-lang.org/examples/first-person. It's a batteries included functional programming framework that you can program right in the browser. In the example I gave you the first person 3D program is written by a user without the user ever writing a procedure or a method that modifies state. All the functions minus the shader stuff are strictly pure and therefore reusable.

leafboi··on Why is OOP still so widely spread?
>When the mutable state is essential (like in my example for a file stream object) that’s not a problem at all, quite the opposite, it allows to expose idiomatic API from a library/module, while hiding implementation details from consumers.

Yes, When mutable state is essential pure FP cannot help you. However much of FP styled languages / frameworks are designed to segregate mutable state away from your awareness as much as possible. See React or Haskell.

Even so, like I illustrated in the Jungle banana gorilla example. When you have mutable state, it is better to deal with it without using OOP. Take a look at that example again, see how the procedural function is better than the OOP method.

>Your method is bad if the code is performance critical, your call stack is twice deeper than 1 or 2. Even ignoring performance, deep stacks complicate debugging, all debuggers show call stacks, they may also be visible in other places like crash dumps, exception traces, or logs

We can talk about the qualitative benefits of each but I'm sure you'll agree from a language/API perspective... My method is the best method in terms of reusability. If the focus of your code is reusability and modularity FP is the best way to go. However you are right that there is inevitably a performance cost. Computers are essentially machines that rely on mutability and have memory boundaries. Any functional abstraction implementation on top of such a machine will not be a zero cost abstraction. We're in agreement here. However you will note that for most modern programming the performance cost is no longer a factor that matters. Either computers are way too fast and make the performance cost negligible or there are bottlenecks in other parts of the system that make the performance gain negligible.

Games and Databases are two examples where FP may not be the most appropriate paradigm due to the performance critical nature of the areas.

>I don’t particularly want to, but for 99% of real-world software dealing with mutable state is essential part of the problem.

Yeah A lot of FP languages have abstractions that help you get around this. See Haskell or React, look up FRP and the IO Monad. Not trivial research subjects.

Look think about it this way. OOP promotes shared state and mutable state in places where it isn't necessary. FP forces you to use a minimum amount of shared as possible and segregates that away from your program. There are essentially two types of functions:

     functionThatGetsDataFromIOOrChangesState()

     functionThatTakesInputANdHasAnOutput()
FP has abstractions that highly segregates these two types of functions. OOP has facilities that integrates all these functions together into arbitrary groups called objects. The purpose of a class is to hold mutable state and integrate side effects with logic. If your class does not hold mutable state then essentially it's just a class repurposed as a namespace with syntactic sugar around the object_verb(object) semantics.

If you are writing a low level program that deals with a lot of mutable state or IO, FP can still operate in this arena via the abstractions but if performance is super critical then probably don't use FP for this stuff. Still, better than OOP for mutable stuff is just a straight up procedural paradigm as I showed you in the banana jungle gorilla example.

IO and mutable state needs to be separate from Logic in order to promote reusability. This is the key area where OOP fails. Procedural programming can achieve this separation while Functional Programming Forces you to achieve this separation.

FP has its downsides and upsides, it is however the most reusable and modular paradigm that currently exists. If modularity and elegance is your objective nothing I know of beats it.

As for OOP, when you bring in procedural programming into the picture, OOP no longer has any upsides. Again, see the banana example.

leafboi··on Why is OOP still so widely spread?
>You were the one stating that only FP has a perfect calculus representation, and have dismissed all the posts from everyone that that proved otherwise.

That's my opinion. That's not called trolling. Disagreeing with people respectfully is not called trolling. Saying the shit you said above: that you're out of food to continue trolling me IS trolling.

I'd flag you already but you need a certain rep to do that. I'm quite new.. but let's see if Dang actually does his job.

leafboi··on Why is OOP still so widely spread?
>Conceptually, procedural languages like C are doing that too for files, they’re just writing object.Verb as object_verb(Handle instance).

The main problem with OOP is the promotion of mute-able state, this is what ties everything together and makes everything less modular. Though semantically equivalent object_verb(object) is actually better than object.verb when you consider mutations and side effects.

Seriously I want you to consider this: Two classes A and B.

  class A:
    def __init__(self, x):
        self.x = x
        heavy_computation()

    def addOne(self):
        self.x += 1

  class B:
    def __init__(self, x):
        self.x = x

    def addTwo(self):
        self.x += 2
Let's say I want to write an addOne method for B. How do I reuse the code for addOne in A inside of B?

   1. Inheritance. Make a base class have A and B inherit from it. 
   2. Duplicate code by writing a duplicate method. 
   3. Dependency injection, modify B so that it takes A and Does some crazy stuff: 

  class B:
     def __init__(self, x, a):
        self.a = a(x)
        self.x = x

     def addOne(self):
        self.a.addOne()
        self.x = self.a.x

     def addTwo(self):
        self.x += 2
        self.a.x = self.x
All three options are bad for various reasons. There is no option where I can just add a method to B without modifying any other part of the program or duplicating code.

AddOne is not reuse-able because it's tied to mutable state and the constructor and all the methods that share that state. This happens regardless of whether or not it's A.addOne() or addOne(A).

The only universe where addOne can be reused is if it started off as a stateless function (addOneFunc)

  def addOneFunc(x):
     return x + 1

  class B:
     ...
     def addOne(self):
        self.x = addOneFunc(self.x)
By making addOne a functional concept I am able to impliment B.addOne without modifying anything else and reusing code to maximum effect. You cannot do this easily with OOP and this is why OOP is bad.

If I want to deal with mutable state, it's actually not technically FP anymore. Inevitably I will have to and that's why many FP paradigms segregate IO with FRP patterns or the IO monad. Even still straight up procedural programming with mutability is still better than OOP because addOneFunc:

   def addOneFunc(int& x):
       x += 1
is more reusable than addOne:

  class Jungle:
    def __init__(self, x, gorilla, banana):
        self.x = x
        heavy_computation()
        self.jungle = create_jungle(create_gorilla(banana))
        


    def addOne(self):
        self.x += 1
“… Because the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle. “ —Joe Armstrong

Many people will say don't design your programs this way. Well nobody has the foresight to know exactly how their primitives will compose for the design they have now and in the future. With OOP you will inevitably design your program into a wall because when it comes time to reconfigure the bricks in the wall you realize that OOP has super glued everything together. What happens IRL is that people eventually hit more complex versions of the example problem I gave you above.

leafboi··on Why is OOP still so widely spread?
Things can be both a library and a framework. You can use react like a utility and react itself can take have code injected in it.
leafboi··on Why is OOP still so widely spread?
>The great thing about repurposing a class as a namespace is I can pass that repurposed namespace package anywhere.

namespaces can be passed anywhere anyway.

>The number + 1 or x 1 doesn't require an object or oop. It doesn't require a function either and would be better to just inline.

+ 1 and x 1 are just examples. If you take the examples and make it more complex the problem still remains.

An inlined expression is still a function. It's just not named.

  y = function(x){return x+1;

  b1 = 1 + y(2)

  x = 2
  b2 = 1 + (x + 1)
In the above code y(2) and x = 2; x+1; are equivalent.

>You never need to change their code either inject those objects into a new class or extend one and inject the other.

You rarely ever need to do this in FP, but you need to do this all the time in OOP.

leafboi··on Why is OOP still so widely spread?
>Well, your answers regarding OO calculus appear to be otherwise.

I'm obviously not trolling. You literally admitted you are. I can't flag you, so I'm going to plant a word here that will hopefully attract attention and get some admin to stop you. Stop trolling or fuck off.

leafboi··on Why is OOP still so widely spread?
Let me come at it from another angle. I'm a bit too blunt. I'm not saying people discredit his work. It could be beautiful and elegant. I'm saying his work isn't accepted in the mainstream meaning generally people don't know about it, nor do people study it and contribute to the theory.
leafboi··on Why is OOP still so widely spread?
https://news.ycombinator.com/item?id=24366735
← PreviousPage 2 of 7Next →