11 ms·
So like, I guess the thing I don't understand is this: why do people think writing: some_array.has_my_thing() is better than has_my_thing(some_array). ? The f
by overgard 5y ago
So like, I guess the thing I don't understand is this: why do people think writing:
some_array.has_my_thing() is better than has_my_thing(some_array). ?
The former, the extension has so many issues, it messes up namespacing, it's unclear where it came from, etc. etc. The latter is just a function. It's not longer, or complex, it's just more straightforward. I really think things where you extend or override built in types is almost always just a bad idea, because the alternative is almost always just as concise and doesn't confuse everyone.
- fernandotakai 5y ago>some_array.has_my_thing() is better than has_my_thing(some_array). ? one of the reasons i prefer python to ruby. sorted(my_thing) will sort anything that can be sorted. no need for monkey patching -- you just call it and, if it can be sorted, it will be sorted.
- matheusmoreira 5y agoIn Ruby, anything that can be sorted will respond to sort. So thing.sort will also sort anything that can be sorted. Python does the exact same thing, it just hides it from you using ugly __methods__ that the language itself will call by convention. What determines sortability? "Anything that can be sorted" just means anything that implements the __lt__ method. In Ruby, this method is called <=> and the Comparable module builds upon it.
- remram 5y agoNothing like sort is hidden in class methods in Python.
- radlad 5y agoThat's not true - Python implements sorted by calling `__lt__` on the object: https://docs.python.org/3/library/functions.html#sorted https://docs.python.org/3/library/functions.html#sorted
- int_19h 5y ago__lt__ is just the way to overload the comparison operator, which of course is going to be called by the sort. What OP is saying is that there's no __sort__ or anything like that.
- radlad 5y agoBut that's not really true either - there's __len__ which len() calls: https://docs.python.org/3/reference/datamodel.html#object.__len__ https://docs.python.org/3/reference/datamodel.html#object.__... You can add iterators with __iter__, reversed() calls __reversed__, etc.
- dwaite 5y agoSorted mandates the type you give it implements __iter__, aka that it is iterable. Ruby defines sort as a method on Enumerable. The difference is that most likely that CPython and CRuby started with different capabilities to map native implementations into the language. The biggest difference between the two is python adds more functions into the global namespace, while Ruby pushes pretty hard to encapsulate logic within types.
- remram 5y agoThe discussion is about how to provide additional functionality. To be sortable, you collection has to be a collection, and it has to have comparable elements. That has to be provided by the type itself. The difference between Python and Ruby is how to add more functions. If you make a library to sort collections (or format phone numbers), the Ruby way is to monkey-patch collections (or numbers). Whereas the Python way is to offer a free function that takes an iterable (or number). This is what we are discussing. Of course Python classes have methods.
- matheusmoreira 5y agoNo, pretty much everything in the language is hidden from you behind methods. This hidden magic is in many cases literally baked into the language's syntax. Iterables use functions like __len__ and __next__. The with keyword is just a thing that implicitly calls __enter__ and __exit__ on a context management object.
- remram 5y agoYes, sorted() will use methods like __iter__ and __lt__ provided by the object. But sorting is not provided by the object and is therefore not (quoting GP) "the exact same thing, just hidden from you in an ugly __method__".
- dragonwriter 5y ago> Nothing like sort is hidden in class methods in Python. The discussion has mostly been about instance methods defined in classes, and how do you define “like sort” in this claim? list.sort() is a method in Python; it's the equivalent of Array#sort! in Ruby.
- remram 5y agoThere is nothing that sorts hidden in dunder methods on objects, even if they can be sorted. `sorted()` will use intrinsic methods like `__iter__` and `__lt__` to sort a collection, but the op is claiming that even though the syntax is different (`sorted(obj)` rather than `obj.sort!`), it's "the exact same thing, it just hides it from you using ugly __methods__". To that I reply that no, there is no method to sort hidden in __methods__. This is not how functionality is added to classes in Python. If you want to add something that works on all iterables, you don't insert new methods in iterable classes, like you do in Ruby. That free-standing sorted() function really is a free-standing function, it is not actually a method "hidden in ugly __methods__".
- dragonwriter 5y ago> If you want to add something that works on all iterables, you don't insert new methods in iterable classes, like you do in Ruby. You don't in Ruby, either. If you want something that works on all Enumerables, you normally write an (instance or class/module) method on some other class or module that takes an argument that supports the methods provided by the Enumerable API. (In Python, you might do this or write a bare function, but Ruby doesn't have bare functions; it's possible to make proc objects in a library which is the nearest equivalent, but you’d almost never do that, because module methods are much more convenient.) In either Python or Ruby you might also monkey-patch existing classes to add functionality to the., and this is slightly more common in Ruby than Python, but because Python iterable, unlike Ruby Enumerables, don't have a common superclass that isn't shared with non-iterables, you couldn't easily do a “for all iterables” thing in Python [0] by monkey-patching because you don't have a good target to monkey-patch, whereas in Ruby you might do something for (nearly, because duck typing is a thing and it's possible someone could build an enumerable by implementing the whole API without mixing in the module) all enumerables, not by adding methods directly to individual enumerable classes, but by monkey-patching the Enumerable module itself. The main difference here is that Python (despite having support for mixins because it uses multiple inheritance) tends in it's core to use a mix of OO public APIs and procedural public APIs built on top of OO protocols using (often dunder) methods, rather than either consistently-OO or consistently procedural APIs, whereas Ruby is consistently OO and uses mixins to provide shared functionality building on a narrower protocol where Python would use a suite of functions. (Python tends to be more OO in its stdlib and third party libs than in its core, except specifically when supporting protocols defined in the core and consumed through built-in functions.) [0] except by monkey-patching object with code that tries to use the dunder methods that underlie the iteration protocol and fails if they don't exist, but while theoretically possible I don't think anyone would do that.
- runevault 5y agoDid they ever fix the arbitrary nature of monkey patching where last in wins? I've not touched ruby in years (and never seriously after I read up on how prevalent MP was).
- RangerScience 5y agoSort of. They introduced "refinements" as the thing you're supposed to do instead of monkeypatching, but AFAIK it doesn't get wide-spread usage. IME you don't usually do monkey-patching, although there are circumstances where it makes A LOT of sense (usually test suites). It's one of those sharp knives - safe if you plan out using it, dangerous if you don't.
- jacobsenscott 5y agoYes, they added refinements several years ago. That said I've been programming rails for probably 10 years, and I never see anyone use refinements, and I can count on one hand the number of times monkey patching has actually been a problem for me personally. I'm sure there are cases where it bit someone hard, but this is one of those things that a theoretically bad, but never seem to really have any impact in practice.
- lamontcg 5y agoI have to maintain code that was written by a developer who has long since left the space. He monkeypatched in stuff like Hash#dig years before it landed in ruby with a slightly different API and blew up the codebase. Since he was a pretty clever developer and had some wide experience in other languages he would monkeypatch in useful stuff from other languages -- but by doing that collisions with the core language are actually pretty frequent. Many people have the same clever idea when its really just copying some pattern that was successful in some other language. Awhile back I gutted the code and ripped out 60% of it, including all the monkeypatching and the maintanence burden on every ruby release dropped sharply. (And I'm assuming we're talking about the more polite kind of Monkeypatching where you're adding methods to global classes that are net-new, not the practice of opening up a class and scribbling over methods that you didn't write and replacing behavior, where should you should always mental picture your SemVer contract being lit on fire)
- int_19h 5y agosorted() will return a new collection. You still need to do foo.sort() in Python if you want to sort in-place.
- drusepth 5y agoDon't mind me, just adding the equivalent ruby code for readers to compare: array.sort # returns a new collection array.sort! # sorts in place (Ruby convention is to add a ! when methods directly modify the object they're called on.)
- dragonwriter 5y ago> Ruby convention is to add a ! when methods directly modify the object they're called on No, Ruby convention is to add a “!” when there is a “less safe” version of an operation, for which a “more safe” version exists without a “!”. Mutating versions of methods where a nonmutating version also exists are one common example, but not the only one, and mutating methods without a nonmutating counterpart don't get “!”.
- dwaite 5y ago> one of the reasons i prefer python to ruby. sorted(my_thing) will sort anything that can be sorted. no need for monkey patching sort() in ruby is declared on Enumerable. Sorted() in python is declared to take an iterable first parameter. They are pretty much equivalent, except python has built-in functionality to reverse the order of the output array, while ruby you would have to negate your sort function. Ruby however allows types to override sort, such as when the underlying type is a red black tree which is already sorted. For duck typing, you can also declare a compatible sort method on types which do not implement Enumerable - doing so in python would require a separate method.
- Mikeb85 5y ago> So like, I guess the thing I don't understand is this: why do people think writing: > some_array.has_my_thing() is better than has_my_thing(some_array). ? The latter is in the global namespace (or you have to create a module/namespace for it). The former is encapsulated in a class. Encapsulation is nice.
- zer0-c00l 5y agoExcept here the encapsulation comes at the cost of extending a core library at runtime, which has all the tradeoffs mentioned in the article.
- jshen 5y agoOne benefit is discoverability. I coded a ton of Ruby/rails back in the day and it was nice to be able to jump into a repl and see what methods were on an object. Also, you could often find the source of the method through the repl. I think a lot of these debates come down to repl development versus ide development. I’ve done a lot of both, but many complaints come down to people on one side not understanding the way the other side works.
- matsemann 5y agoIn other languages (like Kotlin), that extension is actually not done on the object, but is a statically imported function and it's only syntactic sugar. This avoids all the pit falls (no collision, knows where the function comes from etc)
- dragonwriter 5y ago> Except here the encapsulation comes at the cost of extending a core library at runtime No, it doesn't. Pervasive OO style and monkey-patching core classes are orthogonal. Ruby favors the former strongly, and supports the latter, and Rails rather heavily leverages the latter (to the extent that it has been harshly criticized for it by much of the non-Rails Ruby community), but there is no necessary relationship between them.
- 5y ago
- manquer 5y agoThe first style is more aligned to how some people reason the statement in their mind and that is why they like it better.
- sparker72678 5y agoPersonally, I just find `some_array.has_my_thing?(thing)` to be more readable, and I spend way more time reading code than writing it.
- ajmurmann 5y agoI think this might be hosting complexity which reminds me a little of Rich Hickey's Simple Made Easy talk. The Rails way seems more readable because it's hiding complexity. The other approach reveals the complexity, but actually has less complexity than the Rails style solution. This might only become apparent when something goes wrong.
- ajmurmann 5y agoI think you are right that the solution where you pass the array in is clearer and probably more maintainable. It doesn't seem object-oriented at all though. It also leads to a totally different look and feel between built-in and extensions. It's not idiomatic at all. So, I think it's fair to say that the advantages you are lay out are more tangible than the other side of the trade-off. Having written too much Ruby code I'd still cringe every time I have to pass the array. Edit: To make it actually clean it should be 'MyArrayLib.has_my_things(array)'. Still really dislike it despite all the logical arguments for it.
- TomVDB 5y agoI’m switching back from Ruby to Python out of necessity, and I loath things like len(my_list) vs my_list.len(). I just don’t understand why Python thinks it necessary to define global functions for something that naturally should exist as a method. And, of course, there’s no way to know up front when to use a global function vs when to use a method.
- dfinninger 5y agolen(my_list) is just sugar for my_list.__len__() if you feel strongly about the convention: https://docs.python.org/3/reference/datamodel.html#object.__len__ https://docs.python.org/3/reference/datamodel.html#object.__...
- int_19h 5y agoIt's not just sugar; it also does things like ensuring that the value is actually a nonnegative integer. And for other unary "magic methods", the disconnect can be even bigger. E.g. iter(x) is not just a synonym for x.__iter__() - it can also produce an iterator for something that only provides __len__ and __getitem__.
- dragonwriter 5y agoThis is, I think, largely a result of Python not idiomatically using mixins as much as Ruby (since it has multiple inheritance, it supports them, and they are sometimes used, but Ruby leans into them hard in the core.) In the Ruby way, with otherwise similar setup, you would have a mixin that provided __iter__() given __len__() and __getitem__(), and classes that had the last two but wanted the behavior of the first would just include that mixin class as a parent, rather than having a separate branch in iter() to handle the different cases. (Ironically, its one way that Ruby is less TMTOWTDI than Python is.)
- progval 5y ago> In the Ruby way, with otherwise similar setup, you would have a mixin that provided __iter__() given __len__() and __getitem__(), Python does have such a mixing, it's collections.abc.Sequence https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes https://docs.python.org/3/library/collections.abc.html#colle...
- mmahemoff 5y agoComposability. some_array.do_thing().do_another_thing().do_something_else() versus do_something_else(do_another_thing(do_thing(some_array))) Note the first example could be an example of chaining - where each function returns "self" and we progressively transform the object. Or it could be simply each function returning different values which are operated on. Either way, the pattern is usually cleaner and easier to debug than the nested equivalent.
- choward 5y agoSo it's a purely a syntax issue? Other languages like elm have a cleaner syntax for that.
- empthought 5y agoIt's super ironic that you used the term "composability" and didn't actually use functional composition for the second example. (do_thing . do_another_thing . do_something_else) some_array
- funklute 5y agoBut this kind of functional composition often doesn't have first-class support in the language syntax. That is, it often requires you to rely on helper functions or libraries. As a result, it's not nearly as readable or intuitively obvious as the chaining example (and this is in contrast to mathematical notation, where functional composition is very clear, in my opinion).
- servytor 5y agoBecause intellisense can help.
- geysersam 5y agoThat makes sense. This is the most convincing reason I've come across in this thread. How do code completion work in languages where the predicate goes before the subject?
- samatman 5y agoEasily, for typed languages: the values which can be parameters are constrained to values which are in scope and of the appropriate type.
- MadcapJake 5y agoBoth styles can utilize that kind of intellisense on parameters. What about code completions before you've specified the parameters? Not really possible in the functional style unless your functions are namespaced and then you're still limited to what was in that module. Only with object-verb method passing can you get code completions related to the data before you've started specifying (the rest of) the parameters. When declaring a variable, in a typed language you could use the variable type to filter down the possible function completions based on return type; in practice, I don't think any LSPs do that.
- RangerScience 5y agoIn your example, `has_my_thing` then has to be able to handle any possible input (even if it's just to say "I can't handle this input). Example: length of objects/hashes, and length of arrays. And, sure, I guess you could `Array.has_my_thing(some_array)`... but that's just re-arranging the mixin structure behind `Array`. It only looks different until you start peaking under the hood. IMHO, sometimes you want a function because in your problem domain there's a universal (or universal enough) act/question/etc, and sometimes you want a member function because in your problem domain the act/question/etc only makes sense given some particular context.
- sobellian 5y agoSubjectively, the chief advantage is readability for long chains of function composition. Compare list.fft.map(square).sum.sqrt to sqrt(sum(map(fft(list), square))). This is all a matter of taste, but IMO the former reads more easily. It's a pretty trivial matter, so I wouldn't go breaking encapsulation everywhere just to support it. D has a feature called Universal Function Call Syntax where a.f(b, c) is sugar for f(a, b, c) for any free function, rendering those issues moot. I just wish more languages would pick it up!
- toomanydoubts 5y agoWhy not this? (sqrt . sum . map square . fft) list I really don't see what chaining via methods bring that simple function composition doesn't.
- Mehdi2277 5y agoThat's not possible to write in most languages. If a language does support compose operator or custom operators then yes I think that style is good too. But there is no way to write that style in python/ruby. My ideal preference is for a language to support universal function call syntax where x.f(y) is equivalent to f(x,y) always and also include support for custom operators (or at least include common functional operators).
- dragonwriter 5y ago> That’s not possible to write in most languages. If a language does support compose operator or custom operators then yes I think that style is good too. But there is no way to write that style in python/ruby. Ruby has composition operators in both directions: given: x = 2 f = lambda {|a| a+1} g = lambda {|a| a*2} the following are all equivalent: f[g[x]] (f>>g)[x] (g<<f)[x] What’s inconvenient is that to use it with methods, even ones that can be invoked in ways that look like function calls in other languages, you have to realize a method object, since method names don’t name objects. Or, as Matz says (I don’t think of Ruby as a Lisp at all, but in this context it makes sense) Ruby is a Lisp-2, not a Lisp-1.
- dinoreic 5y agoBecause it is baked into the class itself. Ruby is global variables "fiesta", because all classes and modules (and functions that begin with first uppercase letter) and became global once loaded. Because of that, you can not have 2 parallel versions on the same lib, in the sane app, not possible. You load classes once, and they are accessible everywhere, magic! No need for loader headers as in JS, Python, Java, Go, ... That said, ruby devs like to have "sane" extensions like to_json. People proffer to write "@object.to_h.to_json" instead of "JSON.parse(@object.to_h)" and not to think about loading json lib. I agree that Rails is abusing this too much.
- jaynetics 5y ago> you can not have 2 parallel versions on the same lib, in the sane app with the very latest ruby version, you actually can: https://rubyreferences.github.io/rubychanges/3.1.html#kernelload-module-as-a-second-argument https://rubyreferences.github.io/rubychanges/3.1.html#kernel...
- lloeki 5y agoI suppose you're referencing: Kernel#load: module as a second argument (the link jumps to some random place for me) Well, you always could, it was just a bit more involved: https://github.com/lloeki/pak https://github.com/lloeki/pak
- almog 5y agoI guess it comes down to how we are used to process natural language, in which the noun comes before the verb.
- inopinatus 5y agoA better interface might be my_thing.in?(some_collection) since it affords the object agency to decide for itself.
- ratww 5y ago> The former, the extension has so many issues, it messes up namespacing, it's unclear where it came from, etc. etc That depends on the implementation. A monkey-patch is definitely problematic, but when it's properly scoped, like C# extensions, Rust Traits or Ruby Refinements, it's quite elegant.
- drusepth 5y agoThe former's inherent namespacing is exactly why I prefer it. You know exactly where each method came from (it's a method that exists in a `some_array` instance namespace); inversely, I have no idea where `has_my_thing(foo)` comes from or what all it can be used for if it's just sitting in the global namespace. Very often, when I'm learning new code, there's one line I'll write over an over in console bindings: > some_object.methods It provides a super-easy way to learn what methods are actually relevant to `some_object` without having to pour over every method available in the global namespace and figure out whether `some_object` is a valid argument to each. You can also apply set logic like `some_object.methods - {}.methods` to return only the methods available on `some_object` that AREN'T on typical objects, which is a very, very, very powerful learning/exploration tool. For example, irb(main):003:0> PaypalService.methods - Service.methods => [:create_prepay_invoice, :build_client, :capture_invoice_funds, :get_order_info, :get_plan_price] Side note: you can also call `.source_location` on any method to see exactly what file/line it's defined in (even in core ruby/rails methods). There's a lot of other inspection methods available to learn more about objects and what you can do with them, which IMO is a benefit over your latter example.
- nitrogen 5y agoAlong these lines, I recommend also trying Pry's ls command, which breaks the methods down by which module or class implements them for a given object, and the show-source command. It's this great ease of introspection that makes Ruby so fun.
- dgut 5y agoBecause not all programmers are made equal. For some method(thing a, thing b) thing { return a * b } is not better than method a * b end If you're an "artist" type that care about the aesthetics of your code you tend to prefer the second.