4 ms·
My prefered style is a class that's ideally no more than one level deep. Mix in some traits if you need them. Also, as such as possible, make every class/object
by smabie 7y ago
My prefered style is a class that's ideally no more than one level deep. Mix in some traits if you need them. Also, as such as possible, make every class/object immutable and the methods side-effect free. I find this leads to a very natural style in which functions are logically grouped together (also, helps with intellisense) but never modify any state. If there are classes/functions that modify state, make it explicit through naming (I append '_!' for Scala).
Essentially, what I'm describing, is just functional programming where f(a, x) becomes a.f(x). I find the latter easier to read and lends itself to a fluent, lightweight style.
In general, I don't really think the discussion of OOP vs FP or whatever is that meaningful. What is meaningful is mutable vs immutable. Every great developer I've met has agreed with me that mutation should be avoided as much as humanly possible: really the only valid reason to introduce mutation in your program is for performance reasons. And yet, we as an industry still are by and large writing mutation heavy code for no reason at all. Things have gotten a lot better in the last 10 years, but we still have a long way to go.
Edit: I'm mostly talking about Scala in this post, btw. I also want to note that I do think deep class hierarchies are a good solution to some problems. The two examples that immediately come to mind are UI APIs and collection libraries. Both these problems are very naturally solved by OO, the essence of which is the deep (as much as necessary) class hierarchies. Very few problems I've encountered besides the above actually require these subtyping.
An great alternative approach is row polymorphism, ala OCaml. I've not had any professional experience with OCaml or row polymorphism, so I'm not sure how well it actually works in practice.
- whlr 7y ago> I find the latter easier to read and lends itself to a fluent, lightweight style. Maybe I'm bikeshedding, but I think this is a nontrivial part of why people like OOP languages. Being able to read right to left, without nested parens, makes code comprehension easier. I think the mathematical notation for function application has held programming languages back. I realize that there's a huge benefit to uniformity of syntax across languages, and that syntax is ultimately much less important than semantics, but I wish we could settle on something better than f(x). I really appreciate languages that are willing to do something different (e.g. haskell and lisp).
- smabie 7y agoThere's the pipe operator in a lot of languages (|>) to try and solve this problem, but it has always felt clunky to me. Compare: f(g(h(x))) x.h.g.f x |> f |> g |> h I think most people prefer the second one to all the rest.