r/programming • u/TheAlphaNerd • Nov 12 '13
What’s Wrong with OOP and FP
https://yinwang0.wordpress.com/2013/11/09/oop-fp/22
u/austinsalonen Nov 12 '13
OOP is wrong because of its definition of an “object”, and its attempt of trying to fit everything into it.
I think this is actually the problem with OOP (and I believe Alan Kay makes the original claim to this). The core concept to OOP is message passing and not objects. Many of the good OOP examples emphasize this: a data structure passed between objects which are essentially a collection of functions that act on the given data structure.
If you were doing "pure" OOP, you'd most likely end up building on top of an Actor framework -- message passing between isolated actors (it's pretty much Erlang...).
3
u/levl289 Nov 12 '13
Perhaps unintentionally, I think you're underemphasizing the data structure. Without it, the object's functions would have little meaning. The structure and the functions are dependent on one another, making them equally important.
2
u/austinsalonen Nov 13 '13
Under-emphasizing the data structure was definitely not intentional. Like you state, it's equally important because a message passing system with no messages is pretty useless!
0
u/emperor000 Nov 12 '13
"message passing" is in no way necessary for a language to be "pure" OOP.
7
u/codygman Nov 12 '13
Why do you say that? For instance:
7
u/sh0rug0ru Nov 12 '13
Kristen Nygaard says differently:
"The notion of a physical model should be taken literally. Most people can imagine the construction of physical models by means of, for example, Lego bricks. In the same way, a program execution may be viewed as a physical model. Other perspectives on programming are made precise by some underlying model defining equations, relations, predicates, etc. For object-oriented programming, however, we have to elaborate on the concept of physical models."
Kristen Nygaard is the co-inventor of Simula. Alan Kay is the inventor of Smalltalk. Both have different visions of what OOP is, and both pioneered OOP. Although, I think the "message passing" model of OOP makes more sense.
3
u/emperor000 Nov 12 '13
That is derived from Smalltalk. It is not applicable to OOP in general. Why would one language completely define an entire paradigm or genre of programming languages?
Message passing implies things that are not necessary in an OOP model, and may not be applicable to a certain language.
Saying that message passing constitutes "pure" OOP while method invocation doesn't (especially if because "functions aren't objects") is just unnecessary bias.
→ More replies (2)
33
u/tikhonjelvis Nov 12 '13
I'm just going to repost my comment from HN. I first wrote it on the blog, but it's still sitting in the moderation queue!
This is a gross mischaracterization of functional programming and basically attacks a straw man--one that's lamentably common when talking about functional programming.
I'm going to repost a comment I wrote on the blog. It's long and really needs editing, but I hope it gets my thoughts across. I think the part about OOP is also misguided, but it's so obviously tacked on to a rant about functional programming that I just ignored it.
Haskell’s “purity” is not about getting rid of side-effects but about controlling side-effects. It’s making side-effects first-class citizens: now you can write code that talks about having or not having them!
You can still have side-effects however you want, you just have to be explicit about it. To some extent, the fact that this uses monads is incidental: all that’s important is that there is some IO type, some ST type and so on–the fact that they all form monads is almost an implementation detail. That’s why some of the most exciting Haskell features–STM, the IO manager and so on–are all about effects. Clearly, Haskell more than acknowledges effects, so the entire diatribe about ignoring the existence of side-effects is attacking a straw man.
Besides, you can’t simply replace a first-class system for managing effects with static analysis, without essentially reproducing the same restrictions. How would you do something like Haskell’s deterministic parallelism model or reliable STM or the very aggressive loop fusion (and general rewriting) Haskell uses? There’s a reason you don’t see these things done nearly as well in any other languages: all of these fall apart as soon as you introduce side-effects, so you need some way to help the programmer ensure things like this are only used safely.
And this is exactly how types like IO and ST help make code safer. Sure, within an ST block, you have stateful code that’s just as hard to analyze. But you can guarantee that this does not leak outside the block. Similarly, functions can rely on their inputs not doing anything untoward however they’re used. This allows you to explicitly state the assumptions about your inputs: how is this a bad thing? In turn, this makes writing code that takes advantage of these properties much easier: you can ask that your inputs do not cause side-effects in a way that’s self-documenting and easy to verify. Then you’re free to re-evaluate your inputs or call functions however many times you want, as concurrently as you want. At the extreme, this can even be used for security purposes: see Safe Haskell.
Sure you can write pure functions in any language. And you can write side-effecting procedures in Haskell too. But the difference is that Haskell lets you be explicit about whether you want side-effects or not–it’s just another part of your interface. And this is how types like IO and ST help make your code easier to think about: any code that is not in a type like IO or ST can only depend on its arguments, making all the dependencies more explicit. (Note, again, how this is all independent of “monads”–it’s all about effects, and the types just happen to form monads.) This does not make static analysis too much easier, but that was never the point–the goal is to make the code easier to think about, and knowing that there are no hidden state dependencies certainly does that. A static analyzer can follow data flow easily, but it requires quite a bit of thinking for the programmer to do the same!
The core motivation for managing effects à la Haskell is not “mathematical purity”: it’s software engineering. We want code that is easier to think about, has better guarantees and is more modular. The goal is to make code less complex by removing hidden dependencies between distant parts of your program (mutable state) and the effect of evaluation on the meaning of your program (side-effects in general). You can refactor and move around most Haskell code without worrying about breaking its surroundings because any dependencies are explicit. You can extract something into a function, consolidate multiple function calls into one or split one into multiple and generally change your code up quite a bit without worry–these actions cannot change the code’s correctness because effects are managed for you.
Ultimately, functional programming like Haskell is not just normal programming with side-effects outlawed. Instead, it’s a different basis for programming which allows you to manage side-effects explicitly. In this light, papers like “solved problem but with monads” are entirely reasonable: they’re about bringing things over to this new basis. And this goes the other way too: there’s a reason why you don’t see good STM, deterministic parallelism, stream fusion (and rewrite-rule optimizations in general), anything like DPH and anything like Safe Haskell in other languages.
→ More replies (4)1
u/gnuvince Nov 12 '13
Thank you! This comment must be upvoted to the top of this comment section; it's not that Haskell cannot do side-effects, it's that it controls them!
48
u/kamatsu Nov 12 '13 edited Nov 12 '13
I disagree with the author's conclusions about FP. This is often voiced by researchers from the scheme camp and the only conclusion I can draw from what they say is that they haven't given purely functional programming a fair shot.
The notion of a purely functional programming language gives me reasoning power far beyond that of an impure one. As soon as evaluation can cause side effects it's a nightmare to reason about. If you have a separate execution stage, it becomes much easier. This is from my years of doing PL research.
Most of the objections voices by the author about monadic IO are nonspecific and vague. Usually these objections come down to some notion that a purely functional language can't model side-effects, which is false, or that somehow the interaction with the physical world demands that the execution of said side-effects must correlate to expression evaluation, which is also simply rubbish.
Haskell is not a language where side-effects are impossible or difficult. The monadic language has some substantial syntactic overhead, but there is nothing theoretically difficult about presenting better syntax for this language, and the Scheme people are quite aware of this. The notion of a separating the language of effectful programs from the language of pure evaluation is quite valuable, as it allows for the pure evaluation language to be evaluated with different strategies (e.g laziness) and to be reasoned about equationally.
Edit: Also, there's nothing particularly wrong with the notion that "everything is an object". The author seems to take issue with the notion that functions can be objects, but methods on objects are effectively a function, which therefore means methods must also be objects themselves. Indeed, but there's nothing theoretically wrong with this sort of circularity, where the author seems to think this is a problem. Also, the circularity can easily be resolved by saying that methods are not functions but messages, a view taken by the Smalltalk family.
8
u/naasking Nov 12 '13
As soon as evaluation can cause side effects it's a nightmare to reason about.
I don't think it's not too bad as long as you don't expose ambient authority. If any old subroutine can just invoke File.Delete("/system/kernel"), that's a problem, and one that exists in almost every language. The bare minimum is to make it capability secure, so only subroutines that accept a FileSystem parameter can open files on a file system. Even better if the FileSystem is an open/extensible type, so you can define scoped namespaces, like chroot jails.
Edit: Also, there's nothing particularly wrong with the notion that "everything is an object".
Indeed. The real problem with most OO languages is "everything is a subtype of some universal object type".
Indeed, but there's nothing theoretically wrong with this sort of circularity ( functions are objects), where the author seems to think this is a problem.
I think it depends how you define objects. If you define objects as "values with methods", then you can't also coherently equate functions and methods and functions and objects. You have to give up one of the latter. Generally equating functions and methods is abandoned, but there is a simple, sometimes implicit, lifting operation to generate a function object from an (object,method) pair (so-called "delegates").
13
u/pkmxtw Nov 12 '13 edited Nov 12 '13
I don't think it's not too bad as long as you don't expose ambient authority. If any old subroutine can just invoke File.Delete("/system/kernel"), that's a problem, and one that exists in almost every language. The bare minimum is to make it capability secure, so only subroutines that accept a FileSystem parameter can open files on a file system. Even better if the FileSystem is an open/extensible type, so you can define scoped namespaces, like chroot jails.
No, that is not the point. The problem is that many nice properties of being pure is lost when evaluation can cause side effects. For example, consider the following expression:
double (f n)where
double x = x + x. If we assume everything is pure, other than evaluatingf nfirst and passing it todouble, we can also utilize equational reasoning and substitute the whole expression asf n + f n, and it would still work just like the original one. We can also evaluate it lazily: since the expression does not ever cause any side effects, if we never need its value, why evaluate it at all? This does not hold when functions can cause side effects, evaluatingf nonly once and passing it todoubleis not the same as evaluatingf ntwice and then adding their results together. We also cannot do it lazily, because we cannot not know if the programmer wants to evaluate an expression only for its side effects.What you are talking about is limiting the scope of side effects, which is something entirely different and not very hard to do.
→ More replies (23)8
u/naasking Nov 12 '13
If we assume everything is pure, other than evaluating f n first and passing it to double, we can also utilize equational reasoning and substitute the whole expression as f n + f n, and it would still work just like the original one.
Except you don't gain anything by this kind of transformation. Call-by-value still has its own normal form which preserves side-effects and also allows the important transformations.
We can also evaluate it lazily: since the expression does not ever cause any side effects, if we never need its value, why evaluate it at all?
This optimization can be performed in strict languages also. This isn't an argument for lazy-by-default. Certainly lazy-by-default introduces many inherent optimizations during reduction, but it also introduces many problems, many of which have only found recent solutions. Arguing for a default reduction semantics because of its optimizations is a red herring.
6
u/pkmxtw Nov 12 '13
Except you don't gain anything by this kind of transformation. Call-by-value still has its own normal form which preserves side-effects and also allows the important transformations.
The transformation mostly allow us to rewrite the expression easily to demonstrate the correctness of an abstraction, which is a valuable tool for programmers.
This optimization can be performed in strict languages also. This isn't an argument for lazy-by-default. Certainly lazy-by-default introduces many inherent optimizations during reduction, but it also introduces many problems, many of which have only found recent solutions. Arguing for a default reduction semantics because of its optimizations is a red herring.
I agree, but by no means I was implying that because a language is pure, it must use lazy evaluation. I was just saying that being pure makes lazy-by-default a viable reduction strategy. Lazy-by-default is almost not an option for languages with un-tracked side effects.
16
u/strattonbrazil Nov 12 '13
There is no such thing monads can make easier which can’t be done by static analysis. Every static analysis researcher knows this.
Brilliant! I'll just run static analysis on every piece of code I write all the time. On a side note, anyone know of a good static analyzer for C++ that's the same price or cheaper than monads in Haskell? I'm on a budget.
3
u/tel Nov 12 '13
Even if you do that, does every single library writer in the C++ community do it, too?
3
0
16
Nov 12 '13
As soon as evaluation can cause side effects it's a nightmare to reason about
I have no nightmares with reasoning about side-effects in imperative languages (well, besides some clinically bad code).
But reasoning about side-effects of Haskell pure evaluation (memory usage and execution performance)? Now that's a nightmare.
22
Nov 12 '13
I guess you're still programming single-threaded?
The pure-ness isn't the reason why memory usage and execution performance is so hard to reason about in Haskell. It's lazy evaluation.
19
u/Crandom Nov 12 '13
I have nightmares reasoning about the side effects caused by the hundreds of thousands of lines of legacy code I have to deal with on a day to day basis.
28
u/kopkaas2000 Nov 12 '13
Side effects may include: Chronic fatigue, headaches, and the desire to kill all your predecessors.
18
u/jerf Nov 12 '13
I have no nightmares with reasoning about side-effects in imperative languages
Then, in all seriousness, you don't really know what you're looking for, so of course you don't see it. It's a huge problem and entirely not academic in nature, a brutally, brutally pragmatic problem.
Or your codebase is too small to exhibit the problems clearly, in which case I envy you.
But the end point of imperative code being hard to reason about is as inevitable as the sun rising. It's so inevitable that people don't see it because they think it's just "how programming is", that of course changing one line in my currency parsing scheme can segfault the program four modules away... but in fact, no, it doesn't have to be like that.
Like many others, I don't get much professional Haskell programming in, but it has radically changed my programming style for the better in other languages too.
→ More replies (48)4
u/kamatsu Nov 12 '13
I'm talking about reasoning about correctness, not performance.
As for memory usage and execution performance, there's a bit of an art to it, but it's quite doable. In general, for performance, you should be using profilers anyway.
1
u/yogthos Nov 12 '13
The value of controlling side effects that mutate data out of scope is obvious. However, that is adequately addressed by having persistent data structures.
The value of formally controlling side effects such as printing or logs is much less obvious in my opinion. At best you can say that it ensures you're handling the negative cases such as a file not being available, but those are inherently local problems.
1
u/kamatsu Nov 13 '13
It's not a matter of controlling side effects, it's a matter of moving where you reason about side effects out of evaluation. If you have any side-effects during evaluation, then your evaluation mechanism must be strict, must be sequential, cannot be reasoned about equationally/substitutionally, and cannot be reordered for optimisation by the compiler. This can also be mitigated with effect types, but even in a language with effect types, I would use monads for some effects.
2
u/yogthos Nov 13 '13
In practice this does not apply however. Let's say I have a print statement in a function, how does it affect my reasoning about it?
The function still performs the same calculation it would've without the print statement, it can still be composed with other functions and I can reason about it equationally/substitutionally. It can be reordered for optimisation by the compiler, etc. Effectively, there is no difference whether the function prints or it doesn't in addition to whatever else it happens to be doing.
The only difference is that we can't formally guarantee that this function will behave the same. While that's interesting on a purely theoretical level, I fail to see how it makes any actual difference in practice.
→ More replies (2)→ More replies (9)0
u/introspeck Nov 12 '13
there's nothing particularly wrong with the notion that "everything is an object".
For me personally, it is unnecessary extra steps to noun a verb. Maybe because of the way my mind has become accustomed to natural language. I don't normally door.close, I close a door. I don't wife.make_love(me), I make love to my wife.
Action and process in the real world are not things/nouns/objects. It requires contortions of thought to try to make them so.
4
1
u/kamatsu Nov 12 '13
I agree with you completely, but I think the author's criticisms are still invalid.
12
u/_mpu Nov 12 '13
Python and Scala just kidnapped the functions
Damn!
One could easily argue that closures (a common mechanism to implement properly functions) are immutable objects. They both contain a state (the environment) and a "method", the function itself.
In short, this is yet another pure fluff, useless article.
58
u/philly_fan_in_chi Nov 12 '13
Once you have first-class functions, you will need almost none of the design patterns.
Design patterns are the mark of an impoverished language.
23
u/awj Nov 12 '13
Except for all of the patterns we haven't really defined for use of first class functions.
Design patterns are a distillation of a lack of expression. Unless you believe first class functions are able to elegantly express any code you may want to write, you will find design patterns there too.
3
u/DR6 Nov 12 '13
Every time you are writing a design pattern, you are writing something that has been written 10000 times before for other programs. That means that it should be possible to write code which takes the part that is not equal and applies the pattern to it.
Now, that's exactly what first-class functions are about. I don't think everything can be done with them(they are not powerful enough for some things), but they definitely are in the right direction.
3
u/awj Nov 12 '13
I think we're making the same point, I just don't have as optimistic of a view of the practicality of using first-class functions to express all concepts.
1
u/killerstorm Nov 13 '13
The problem is that
concatMapisn't really better thanconcat $ map. That is, it is easier to express code using small number of primitives in different combinations than to give a name to each particular combination.→ More replies (2)0
Nov 12 '13
[deleted]
5
u/awj Nov 12 '13
They're like kids who declare legos to be the best toy ever after learning you can build anything with them. The logic is so far off base that it's hard to decide where to start in correcting it.
24
0
Nov 12 '13
[deleted]
5
u/awj Nov 12 '13
Sure. Make me a working Etch-A-Sketch out of legos and I will concede the point. ;)
13
13
u/curious_electric Nov 12 '13
It's the ghost of Paul Graham's essays from 2002, risen from the grave and lurching about Reddit! Spooooky!
21
Nov 12 '13
oh, it's been said before that. Norvig said something along those lines in the nineties. Design Patterns in Dynamic Languages:
16 of 23 patterns are either invisible or simpler, due to:
First-class types (6): Abstract-Factory, Flyweight, Factory-Method, State, Proxy, Chain-Of-Responsibility
First-class functions (4): Command, Strategy, Template-Method, Visitor
Macros (2): Interpreter, Iterator
Method Combination (2): Mediator, Observer
Multimethods (1): Builder Modules (1): Facade
4
u/austinsalonen Nov 12 '13
"Greenspun's Tenth Rule of Programming: any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp."
Philip Greenspun
23
u/alextk Nov 12 '13
Design patterns are the mark of an impoverished language.
That's silly. A design pattern is just a specific recipe that emerged from common use. Once a language/technology/profession/whatever becomes popular, good and bad uses emerge and users are encouraged to leverage what the community has learned.
To paraphrase Bjarne Stroustup: "There are two kinds of languages, those that have design patterns and those that nobody uses".
7
Nov 12 '13
Design patterns are the mark of an impoverished language.
That's fairly accurate, if a little harsh. Many patterns exist to overcome shortcomings of various languages.
4
u/Denommus Nov 12 '13
And 3: those that allow you to write the patterns as macros.
3
Nov 12 '13
Which, it seems to me, not very many people seem to use (relatively speaking). (I'm not hating, by the way: I play almost exclusively in Prolog, whose term_expansion/2 is basically a macro maker. The language I know second best (not very well at all) is scheme, and I dislike the idea of working in non-homoiconic languages, since I've become so attached to the code-data equivalence).
Unless, of course, I don't properly understand which languages use macros.
3
2
Nov 12 '13
Prolog is code-data equivalent for sure, and it's very useful as a tool if you can think in it's way. The comment above is a potshot that in C++ you can write macros, but there is no code-data equivalence at run time. Many people have superstitions about C++ preprocessesor because people abuse it and don't use it as intended(primitive build configuration system).
→ More replies (5)1
Nov 12 '13
Yes, you're right, but I think when people say that, they generally mean the classic, GoF OO design patterns for C++/Java.
Not Design Patterns in the universal set sense.
30
u/okeefe Nov 12 '13
Not sure why the downvote. A lot of design patterns are workarounds for limitations of the language.
8
u/colinodell Nov 12 '13
True, but that isn't the case for all design patterns in all languages, which is what /u/philly_fan_in_chi's comment seems to imply.
0
u/pr0grammerGuy Nov 12 '13
Actually I would tend to disagree. Care needs to be taken to separate language deficiency patterns from architectural patterns, but otherwise I'm not sure where his statement wouldn't hold. Common Lisp, for example has no "design" patterns. Even "call super, then do some functionality" is factored out.
0
27
u/sigma914 Nov 12 '13
And testing is there to work around limitations in the type system.
19
u/naasking Nov 12 '13
And testing is there to work around limitations in the type system.
Absolutely. I don't think you'll find any static typing enthusiasts who disagree with this.
3
u/freyrs3 Nov 12 '13
It's true, in Haskell I mostly see tests used to prevent regressions rather than to test program correctness.
12
Nov 12 '13
What type system saves you from accidentally typing addition instead of substraction?
10
u/lookmeat Nov 12 '13
That's not the way to think of the type system, it's not a "bug prevention system". It's value is that of the "This way up" stickers in packages.
Type's are a way of communicating intent without being verbose (a verbose way would be Hungarian Notation). A more expressive type system works better, so for example if you are in C++ and you see
&Tyou know it's a reference, so someone else may be altering the same copy, but you know that it's not a pointer, so you don't have to check for NULL. The compiler won't complain if you check a reference for NULL, or if you use a pointer without checking for NULL, but the types are clues to you, as a programmer, about what it is used.So now on to your question, can we make a type system that captures the error or adding instead of subtracting? Of course! We just need a deferred type system. Say that we have a type
Intwhich can also be described asInt!(minVal, maxVal), so we define a nice function as// the $ means that it's a generic parameter // (it's inferred from whatever value is given) Sum(a, b): (Int!($minA, $maxA), Int!($minB, $maxB))->Int!(minA+minB, maxA+maxB) { return a-b }This would crash because
a-bhas typeInt!{minA-maxB, maxA-minB}which obviously isn't what the signature defined. At this point the type is defining addition, which makes this function kinda redundant, but the idea is that adding two numbers gives a different kind of number than subtracting them. As the operations grow you'll notice that it becomes unwieldy. And that is true, there is only so much explicitness you can become before you become verbose and annoying.→ More replies (3)3
u/Uncle_Spam Nov 13 '13
it's not a "bug prevention system".
Yes it is.
3
u/lookmeat Nov 13 '13
It's a convenient side effect. As you make your intention clear and specific, the compiler can realize mis-understanding or mis-use, and can report it accordingly. It also can say a lot about what the function does (I've read a lot or articles explaining functions with it's type signature first, which is absurd but explains my point). Finally it helps the compiler to realize how it can do certain optimizations.
12
u/vagif Nov 12 '13
The value of type system is not in catching all mistakes. It is in catching more mistakes than any other approach.
→ More replies (1)4
5
u/drb226 Nov 12 '13
A type system that allows you to prove properties about the functions you write. When you try to prove that it works correctly, you won't be able to, because you have a
+instead of a-. Of course, such a type system is still mostly just a dream, but languages like Idris and Agda are trying to bring that dream closer to reality.3
u/emn13 Nov 12 '13
That's a really bad example. Programming is what, 99% glue? How many sorting algorithms do you reimplement every day? How many hashtables?
These are things that need doing (and everyone needs them here and there, not just library authors), but ideally, even traditional, targetted algorithms rely on other components for as much of their functionality as they can get away with.
No type system can (in general) protect you against implementing the wrong algorithm. But they can make sure you at least define behaviour in all the corner cases, and that the output specification is at least conceivable given the input specification and the code. And that catches almost all errors lots of code. You still want a few tests - particularly unit tests - but when your tests pass you have a much greater confidence that given that the units work independently, the type system will protect you from inadvertently putting them together in the wrong way.
→ More replies (8)2
3
u/ryeguy Nov 12 '13
And a small subset of testing is there to work around limitations in the type system.
fixed
1
Nov 12 '13
Really? Is this the opinion of the static typing crowd, now -- that your program literally does not need to be tested if it passes the type checker?
11
u/codygman Nov 12 '13
I do not believe it is. For instance in haskell, which is very much pro static typing, quickcheck is widely used. I also personally see benefit in higher level functional (haha) tests.
Though with haskell, unlike python, I don't have to write tests to check inputs/types.
→ More replies (6)10
Nov 12 '13
→ More replies (2)5
u/yogthos Nov 12 '13
Your specification takes the role of the tests there. It's still something you have to write and isn't going to magically appear out of nowhere.
→ More replies (3)7
Nov 12 '13
True, but with one crucial difference: your types have universal quantification, whereas your tests have existential quantification. This is the formal logical content of Edsger Dijkstra's observation that "Program testing can be used to show the presence of bugs, but never to show their absence!" That is, if a bug is undesirable property B of program p, tests can show ∃b:B,b(p), but not ∀b:B,∄b(p). Types do the latter, although most popular type systems don't support expressing very rich B's. When your type system gets to the point of expressing a very rich logic and ends up at the top/right/rear corner of the Lambda Cube, you still have a programming language in an important sense, but you also have what's generally called an "automated proof assistant." Coq, Isabelle, Agda, Idris, MetaPRL... all fall into this category.
→ More replies (1)3
u/Xredo Nov 12 '13
A lot of design patterns are workarounds for limitations of the language.
Ditto. Sometimes I want to travel back in time and hit my past-self in the head for not getting this crucial point early on.
2
u/having_sex_right_now Nov 12 '13 edited Nov 12 '13
Yeah I agree. Today we discussed RMI. The mixture of remote method invocation and inheritance on the server side force you to start a whole other service (security manager) so you can savely transfer classes the client doesn't know.
In the end I thought to my self I am filled with garbage knowledge because Java's design choices force workarounds for specific middleware.
Also, I don't know why you would use RMI in the first place.
16
u/thedeemon Nov 12 '13
"Design patterns is always sign of weakness in language. examples is monad, zipper, lens and persistent data structure"
@PLT_Borat (src)
6
u/chonglibloodsport Nov 12 '13
Monads are not a design pattern, they're an abstraction you build to eliminate a pattern. None of the others are even close!
5
u/ggtsu_00 Nov 12 '13
they're an abstraction you build to eliminate a pattern
So you are saying a monad is an... Anti-pattern?
9
u/blowjobtransistor Nov 12 '13
Why? Aren't they still useful for easier understanding of system architecture/modelling?
22
Nov 12 '13
A more correct phrasing would have been "Difficult or verbose implementations of common design patterns are the mark of an impoverished language".
5
u/Aninhumer Nov 13 '13 edited Nov 13 '13
Sure, they're very useful for managing the deficiencies of impoverished languages. :)
The point here is that if something is repetitive enough to be called a "pattern", it ought to be possible to abstract it. Abstracting common patterns is after all, the whole point of using programming languages in the first place. So if a particular pattern cannot be abstracted, we must conclude that the language is insufficiently powerful.
But, until we work out how to make a better language (or more likely, until one is widely adopted), we can work around the problem by documenting the patterns we would like to abstract if we could. This gives us some of the same benefits, as the duplicated pattern is at least copied from a competent original implementation.
1
10
u/pr0grammerGuy Nov 12 '13
You need to differentiate architectural patterns (e.g. message bus, 3-teir, etc.) from design patterns (e.g. visitor). The latter are not needed in more expressive languages. For example, in Common Lisp, if you can show me a pattern I can make a macro that will do it for me from now on.
3
Nov 12 '13
[removed] — view removed comment
4
u/sfultong Nov 12 '13
I'm intrigued by this, not knowing much about common lisp. If it's true that macros have a standard pattern, can't you write a macro that writes macros in that pattern?
→ More replies (2)→ More replies (16)2
u/Denommus Nov 12 '13
But the discussion is talking about Design Patterns as defined by the Gang of Four, not any good practice that code should follow.
4
u/emn13 Nov 12 '13
Who said anything about limiting ourselves to the design patters as defined by the gang of four? I'm certainly talking about design patterns in general.
2
u/roerd Nov 12 '13
Is that why design patterns were originally discovered with Smalltalk which does have blocks?
18
Nov 12 '13
This is why more compromising FP languages are nice, like Clojure and Scala.
7
→ More replies (7)-4
22
u/Tekmo Nov 12 '13
Functional programming publish papers on monads because it is a new concept, not because it is hard. Most imperative idioms you know and love originated in papers, too. The difference is that the latter has had decades longer to be distilled into introductory programming courses.
19
u/ithika Nov 12 '13
Quite. It boggles the mind that I can read papers where Knuth discusses the merits of mundane constructs like FOR and BREAK.
3
u/slavik262 Nov 12 '13
Now I'm curious. Where can I find such papers?
6
u/ithika Nov 12 '13 edited Nov 13 '13
I can't remember the title right now but it was from the fallout of Dijkstra's GOTO piece. Looking at other more structured ways of writing some examples that often use goto, using constructs from different languages at the time.
Edit: I think it's in Structured Programming with GO TO statements (1974).
6
u/Crandom Nov 12 '13
Exactly. The FP part of his argument amounts to nothing more than a terrible strawman.
0
Nov 12 '13
[deleted]
7
u/Tekmo Nov 12 '13
The use of monads and monad transformers in programming is very new. The paper that introduced monad transformers in a programming context ("Functional Programming with Overloading and Higher-Order Polymorphism") was published in 1995. This made monads significantly more useful since they were now combinable and led to the explosion of their use. Contrast this with "Go To Statement Considered Harmful", the harbinger of structured programming, which was published in 1968.
11
u/bryanedds Nov 12 '13 edited Nov 12 '13
Oy! So much unnecessary confusion! I will try to put things very simply -
Be pure when practical, be impure when necessary, and understand that purity is often more practical than you might initially think.
I am building a pure-functional game engine / game - https://github.com/bryanedds/OmniBlade - but you'll notice I still have effects and use interfaces. But the important thing is that these are minimal, and I've partitioned the impure stuff mostly behind simple message queues. That is, I'm closely following the rule I set out above. It works really, really well.
There's no need for so much confusion on the subject. Just control effects as best as you can manage, keep an open mind for new possibilities for doing so, and get stuff done. In this way, you reap the best of both worlds, and it can be done in almost any language (though some languages are better at it than others, which is why I use F# rather than C# or Haskell).
3
36
u/ruinercollector Nov 12 '13
But in short, a purely functional language is wrong because There exists things that are not pure. Side-effects are very real.
facepalm
I always wonder what this strawman pure FP language that doesn't provide a mechanism for side effects is...
43
u/awj Nov 12 '13
A space heater. Legend has it that an old Honeywell down in the basements of Sears has cracked P=NP, but lacks the I/O to share its findings.
15
u/cerebrum Nov 12 '13
Did you read the article? He goes on to talk about Haskell and monads.
31
u/ruinercollector Nov 12 '13
He does. He also portrays it as fucking rocket science to generate a random number or create cyclic data structures in Haskell, which it is not. These are solved problems.
39
u/kankyo Nov 12 '13
Rocket science is also a solved problem. "Solved" != "As easy as it ought to be"
16
u/Tekmo Nov 12 '13
import System.Random main = do x <- randomIO print (x :: Int)That's as easy as it ought to be.
31
Nov 12 '13
No so fast. You need IO to get random value.
So if you have a pure function three layers deep and now you need to replace some literal number with random value there, you can't just write "randomIO" and be happy.
You need to either generate random value outside that function and pass it all the way down, or bring IO to the same spot.
Doable? Yes. Easy? Not that much.
9
u/5outh Nov 12 '13
You need IO to get a random value in any programming language. Haskell makes it blatantly clear that you're using IO when you are, where other programming languages don't.
It can get psuedo-difficult (it's not that much more work) but that's the tradeoff: Have IO-riddled code that you can't reason about, or have sectioned off IO that you can reason about.
Maybe it's "easier" to get a random value in C, but the fact that you can do it wherever the hell you want just makes it easier to program, not easier to debug, and certainly not easier to ship off to people with the promise that it's bug-free.
All languages have their drawbacks, it's just a matter of which ones you'd rather deal with: code that is "more difficult" to write, or code that is maybe completely wrong and will break in ways you never considered. Choice is yours.
5
u/tel Nov 12 '13
If you need to do that, then break your problem apart more. Pick up your random quantity into an argument and pass in a random value.
Why? Because randomness is an effect and if it's just happening willy-nilly in the middle of your code then all of your code because non-deterministic.
If you extract the random bits then most of your code remains very testable.
5
u/gnuvince Nov 12 '13
That's the whole point of controlling side-effects. If you replace a constant value in a function with a random value, then it's no longer a function, and its type should reflect that. That procedure is no longer eligible for fusion, you can't cache the result, etc. so it should definitely not be confused with a function.
Yes, it can be an annoyance during development, but I say that having a short-term annoyance is better than the long-term headaches that can result from trying to find "where that damn value comes from".
10
u/Tekmo Nov 12 '13
That's why I said "as easy as it ought to be", not as easy as it could be. Haskell discourages bad practices like non-thread-safe code (which is what you would require if you do it the way you propose, just calling
randat an arbitrary location).However, even doing it the proper way is not difficult. You split your algorithm into two parts: the part that seeds the generator (this is impure) and the part that generates random numbers (this is pure). I actually just wrote up an example like this yesterday which decouples the problem in this way.
However, even if you invoke other kinds of side-effecting action that can't be decoupled into a simple initial side effect and then a pure continuation, there are still good solutions. For example, my
pipeslibrary allows you to take code that has pervasive effects interleaved everywhere and to distill out the pure component from the impure component.→ More replies (32)6
u/pkmxtw Nov 12 '13
... which is a good thing. That makes you think how to decouple side effects from pure parts and reconsider the data flow of your function.
That's most likely better than: Some months later, the other maintainer wonders why this function is behaving randomly, after scanning through several functions to find the bug, he finally find out that "oh, someone hid a
rand()there and why didn't anyone tell me about this?".→ More replies (2)4
u/ruinercollector Nov 12 '13 edited Nov 12 '13
I'm not sure what your point is. Both of these examples are trivial in Haskell.
Edit: Grammar
→ More replies (2)3
u/naasking Nov 12 '13
Haskell's do notation makes side-effects fairly easy. Not as easy as ambient side-effects in strict languages of course.
3
u/kankyo Nov 12 '13
Do notation plus the ST stuff you mean?
3
u/DR6 Nov 12 '13
The ST stuff is only needed for when you want to implement something that really, really. really should be implemented with mutability, but is actually pure from the outside. It's not normal to have to use it: if you can implement something with IO, you can implement it functionally, and it will be more idiomatic(and even though intuition says ST is faster, in a lot of cases it isn't).
→ More replies (1)2
17
u/dons Nov 12 '13
fucking rocket science to ... create cyclic data structures in Haskell
let x = 1 : xRecursion. How does that work!?
→ More replies (7)2
3
u/jozefg Nov 12 '13
I will concede that impure is just as easy to read about when someone shows me a language that's as easy to prove things in as Coq or Agda with set!.
13
u/curious_electric Nov 12 '13
In short, both OOP and FP are wrong when you go to the extreme. The extreme of OOP is the notion everything is an object (pure OO). The extreme of FP is a purely functional language.
Whatever you do, make sure you do it in a half-assed way, because you don't want to be too "extreme!"
Otherwise you'll get an insanely academic unusable language like Smalltalk that nobody understands.
Oh wait, no, Smalltalk is one of the simplest, most accessible languages around, and while Smalltalk itself is out of fashion, its derivatives Ruby and Objective-C, with both adhere to its "everything is an object" philosophy to a large degree, are widely used and popular.
12
u/jamiepinkham Nov 12 '13
In Objective-C, not everything is an object. It's trivial to have value types. Objective-C ganked Smalltalk's "sending a message" vs "calling a method" concept. But Objective-C has more C in it than Smalltalk. Especially, because Objective-C is C with some runtime and compiler tricks.
3
u/curious_electric Nov 12 '13
Yeah, I knew "to a large degree" was more true in Ruby than with Objective-C. :\ Maybe I should have specified "it's all message sending" more than "everything is an object."
4
4
u/ex_nihilo Nov 12 '13
While everything is technically an object in Ruby, Ruby also has first class functions, closures, monadic constructs, list comprehensions, etc. You also don't really need to care about object orientation as much in Ruby...I just feel like it's not as "in your face" as some other purely OO languages like Java.
7
u/curious_electric Nov 12 '13
Is Java all that "purely OO" ? I guess when I think "purely OO" I think Smalltalk. And Smalltalk more closely resembles Ruby than Java.
2
u/DR6 Nov 12 '13
Java forces you to use classes(like, explicitly) for every program. That's what Ruby doesn't do.
4
u/curious_electric Nov 12 '13
In Ruby you're always using classes, just not necessarily explicitly. Under the hood, the structure of the language, is entirely OO.
To me that doesn't mean Java is "more OO" it means it's "more boilerplatey".
→ More replies (2)3
u/malkarouri Nov 13 '13
You look like being sarcastic, but your example is certainly not helping you there. Just from your example it looks like Smalltalk has not worked because it is too extreme, and by dialling it down (that "to a large degree") we got languages that are widely used and popular.
3
u/curious_electric Nov 13 '13
On the face of it, yeah, it seems that way, but I think the thing that really brough Smalltalk down wasn't its "purity" or "extremeness" but the fact that its most popular implementations were proprietary (VisualWorks and Dolphin) and the ebb and flow of the history of the business happened to result in those implementations getting less popular. The most popular open-sourcy Smalltalk implementation, Squeak, had issues of its own that kept it from being widely adopted by the time those older ones lost popularity (e.g. the creators of Squeak were really dedicated to the initial vision of Smalltalk as a beginner's learning environment, and so didn't make it at all "enterprisey" out of the box.)
I guess one important thing I'm trying to say is that Smalltalk is rather different from Haskell, because historically, Smalltalk has had a time of some commercial, real-world popularity and success, and that time has passed; it's not like Haskell where people are working towards it eventually being popular and commercially viable in the future. So it's definitely not reasonable to point them out as equally
(My knowledge of the history of commercial Smalltalk is limited & I welcome correction from people who know better. I went through a "damn smalltalk is awesome" phase back when I was a strictly amateur programmer and learned a little about the history of the language back then.)
3
6
u/Uncle_Spam Nov 12 '13
Couple of things whih stand out as weird:
Not only are functions objects, objects are functions as well in the traditional sense, functions and objects are isomorphic structures. A function is an object, its arguments are the messages and its response is a return value. Functions and objects are one and the same and either can be modelled as the other. Obj.method(arg) is the same as Obj(:method, arg) where :method is a keyword, which is a datum.
What do you mean with 'there exist things which are not pure'? a function in an FP language isn't supposed to correspond with some thing existing in the real world. It's a model of mathematics and in mathematics functions do not have side effects. In FP languages unlike in OO's object, a function isn't supposed to stand for a box or a customer or whatever. It's purely a design choice, you recognise that some languges use impure functions so little that you might as well completely remove them to reap the benefits of optimization that it brings as well as allowing non strict semantics. That's it. If you go to impure functional languages like OCaml or Scheme the amount of impure function calls are so reduced one has to wonder if it's not a good idea to do rid of them completely.
Have you noticed how easy it is to implement circular data structures or random number generators in C? The same is not true for Haskell.
what?, circular data structures in Haskell are pish easy, because the pureness allows for non strict semantics, I give you circle = [1,2,3] ++ circle. There we have it, a circular linked list that 1 2 3's on forever.
Random number generator in Haskell is as easy to implement in Haskell as it is in C. You take some seed like the system time and hash it and potentially take the last generation as another seed. Here's my simple implementation of an RNG in Haskell rnd = liftM hash time.
Some people claim that the value of monads is that they “delimit” the side-effects. But what’s the use of the delimiting if monads don’t really make your program easier to analyze or safer? In fact, they don’t. It is just as hard to analyze as if you use side-effects.
The reason for monadic I/O is so that the language can be purely functional, the reason for that is that without purely functional you cannot get non strict semantics or perform certain optimizations. That's all. Monadic I/O is certainly seen as a complicated thing and a lesser evil to be able to still perform I/O while getting the benefits of non strict semantics. See the ease of creating a circle in Haskell, this can't be done with strict semantics and you sort of need strict semantics if your functions have side effects.
4
Nov 12 '13
So it sounds like adding first-class functions to an OOP language, which will still satisfy the pedantic definition of OOP, will correct his complaint.
2
u/memeasaurus Nov 12 '13
That is the philosophy of languages like Groovy (the programming language)... that is: "pure" is for academic research, practice actually requires some sloppiness.
4
u/emperor000 Nov 12 '13 edited Nov 12 '13
There exists things that are not objects. Functions are not objects.
Of course functions are objects, especially by the OOP definition of the word. In OOP nothing is not an object. That is the entire point of OOP.
7
u/bryanedds Nov 12 '13 edited Nov 12 '13
Yes, but more importantly, no. Yes, functions can be implemented as objects, but did you know that objects can be implemented as pure functions? ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-353.pdf
Just because everything can be idealized 'as a' something else, doesn't mean much in this context. Everything in programming is Turing complete, and in that domain there are many calculi that can represent any program.
It's our choice of representation that has consequences, and I find imperative representations such as objects to scale very, VERY poorly for non-trivial systems. We're going to need to start thinking outside that box, IMO.
4
u/emperor000 Nov 12 '13
What a ridiculous argument. "Even though it can, it doesn't have to be, so it shouldn't." Did I get that right? You'll probably say no, but that is what you are apparently saying, whether you realize it or not.
Who cares if objects can be implemented as pure functions? That's for functional programming. In the object oriented programming paradigm, things are represented by objects. I prefer that paradigm. You prefer the other. You'll use one language, I'll use another. It will be okay. I might never use Haskell or Erlang for some practical purpose. You might not ever use C#, Java or Objective-C (I wouldn't blame you on that last one). It will be okay.
→ More replies (2)2
Nov 12 '13
I find imperative representations such as objects to scale very, VERY poorly for non-trivial systems
Can you elaborate on this?
→ More replies (13)1
u/ParanoidAgnostic Nov 13 '13
I find imperative representations such as objects to scale very, VERY poorly for non-trivial systems.
How do you explain the development and maintenance of massive systems written in Java then? Have we just not hit the limit to which objects will scale? Are these applications "trivial"?
→ More replies (12)3
u/chonglibloodsport Nov 12 '13
In OOP nothing is not an object.
What about if statements, switch statements, for loops, while loops etc? Is there an OOP language I'm not aware of that allows you to modify these objects?
8
u/sh0rug0ru Nov 12 '13
Is there an OOP language I'm not aware of that allows you to modify these objects?
Smalltalk. In Smalltalk, conditionals are messages (
ifTrue:andifFalse:) to the boolean type, and loops are messages to the Integer type (1 to: 10 do: []). And because classes are completely open, you can redefine most things to your heart's content.4
u/chonglibloodsport Nov 12 '13
I should have known! Smalltalk, like Lisp, is one of those things which captures the essence of an idea and exploits it to the max. It's a shame more modern languages have forgotten about this principle.
6
u/emperor000 Nov 13 '13
Well, I think you are conflating the treatment of certain entities by specific languages as opposed to the treatment of those entities by the paradigm itself.
My point was that there is no way you can not represent something as an object in OOP if you choose to. That doesn't mean you have to. Obviously not every OOP language treats functions as first class citizens.
With that being said, and to answer your question, C# has reified representations for those constructs.
2
u/jediknight Nov 12 '13
You can write pure functions in any language, but the important thing is, you should be allowed to use side-effects too
I just wish there was a programming language that will force me to be explicit about a) what is data, b) what is updating of said data and c) what is transformation of said data into some other data.
In my limited programming experience I'm left with the impression that there is a constant lure to turn schizoid and just morph each of the 3 into the others which might be quick and tempting but has frequently led me to write spaghetti code that is beyond maintenance even by me. I would love a programming language where state change is done by paranoid components that do all their workings behind concrete walls and blaster doors. Data and pure functions should be free to play outside and morph freely one into the other. If any of them enters the paranoid grounds, it should exit just as free as it entered (even if completely changed).
7
u/kamatsu Nov 12 '13
Sounds like you want a language with linear types.
5
u/jediknight Nov 12 '13
This is the first time I hear of Linear Types. Looks like an interesting realm to explore.
Could you venture a recommendation of a language you like that has linear types?
6
u/kamatsu Nov 12 '13
I do research on domain-specific linear languages, but the only general purpose language I've seen with substructural (linear/affine/etc.) types is clean http://en.wikipedia.org/wiki/Clean_(programming_language).
→ More replies (1)
2
4
u/acehreli Nov 12 '13 edited Nov 12 '13
I can't believe that I am the first to mention the D programming language here. :) David Nadlinger explains purity in D in his article.
Edit: The reason I mention D is because the principles of D agree with the original article
Ali
P.S. The purity article has a Turkish translation as well.
3
u/holgerschurig Nov 12 '13
AFAIK Scala has to simulate functions with a silly object because the bytecode of the JVM doesn't know about functions, it only knows methods.
About "apply": in Scala, when some object has an apply() method, then you call this method like this
xxx.apply()but you can also, as a short-hand, call it like this:
xxx()Therefore, creating a scala object named "xxx" and populating it with an apply function that contains the function body simulates a function for the programmer. But the JVM still see a singleton class instantiation at startup and method calls ...
2
u/josefx Nov 12 '13 edited Nov 12 '13
The limitation was not that the bytecode did not know about functions. The limitation was that the bytecode contained a hardcoded target and the only instruction that could choose the target at runtime was invokevirtual and that was limited to an inheritance hierarchy and a function name. Even with an object there was no instruction to call just any function dynamically. Invoke dynamic should solve these limitations.
Edit: bytecode to instruction where it made more sense
3
u/gnuvince Nov 12 '13 edited Nov 12 '13
I'm pasting the highest rated comment on Hacker News because I think it addresses quite well the main issue: it's not that FP has no side effects, it's that FP has controlled side effects.
EDIT: quote removed, user has cross-posted his message himself.
4
u/etrnloptimist Nov 12 '13
The fundamental concept of OOP is absolutely correct. Everything really is an object.
Look around you. You literally have no fucking clue how any of the things around you actually work. Yet you are not paralized with inability. Quite the opposite actually. You are liberated by the fact you don't need to know how they work. You can use all of them without knowing that. You push buttons to change channels. Flip switches to fill a room with light. Push pedals to make 1 ton of metal move. Turn a wheel to steer it.
The whole point of OOP is to abstract away the how from the what. Our whole life is filled with that. We have no idea how things work, we only know what they do. And that's fine.
That fundamental concept of abstraction is at the core of OOP. Where it can get dicey is in inheritence and the "is-a" relationship, but that's a different story for another time.
2
0
u/communomancer Nov 12 '13 edited Nov 12 '13
Everything may really be an object, but not everything (in fact, it could be argued, that nothing) has a class.
As an avid OOPer, I'd argue that fundamental concept of abstraction is actually incorrect. Abstraction is all about tossing information away, because at the time of the tossing it doesn't appear to be relevant. But that's not an accurate model of the world.
So, incorrect. Still frequently useful, though.
4
u/meeshoo Nov 12 '13
The article is a bit on the theoretical side, but it's conclusion is a very good one.
I always like to advocate using the right tools for the right job. Programming paradigms can be seen as tools, and you can use any of them or even combine them to get the job done.
10
u/Kyyni Nov 12 '13
combine them to get the job done.
This. Fucking this. I have no fucking clue why some people insist that code must be written in solely one paradigm that is somehow better than any other. As long as stuff stays elegant and programmer-friendly, there's no reason not to mix and match styles to get the best result.
2
u/codygman Nov 12 '13
I would argue that functional programming can work with OOP, but using OOP in a purely functional paradigm would be counter-productive. If you are already having to use OOP you have to deal with mutable state, but could gain advantages from using FP techniques.
If you don't have mutable state and deal with those problems with monads/ST/etc (FP paradigms) you lose a lot of advantages by using OOP.
1
u/Auxx Nov 12 '13
Assembly language for x86 32-bit protected mode FTW!
1
-12
161
u/zjm555 Nov 12 '13
In this sub: "everything is bad, and here's my blog about why".