141 points · by jamis · 11y ago · 86 comments
http://jamesgolick.com/2013/4/14/mris-method-caches.html
The late, great James Golick had a patch to add one once, but it never got merged upstream.
If you care about performance even the tiniest bit at all whatsoever, please don't use the techniques discussed in the OP in production code or in your gems. It may make your memos 30% faster on a microbenchmark... while causing the rest of your program to run considerably slower.
It remains an open issue: https://bugs.ruby-lang.org/issues/9262
This stuff feels really dangerous and unnecessary. I spend a lot of time on code reviews pointing out bad features of Ruby (and Rails) that we shouldn't be using because they break application flow and make it significantly harder to reason about the code for the small benefit of decreasing a few lines. But it's certainly fun to talk about :)
However, the language itself is great. The trick is to remember the usual advice that just because you can doesn't mean you should. Too many gems add "clever" metaprogramming (such as the def tricks in this article), when it isn't actually making the program simpler.
The beauty of ruby is that while it can act almost like a LISP for the times when you want powerful metaprogramming features, while also allowing simple shell or C style imperative code when that is more appropriate.
(Of course, some people fear that type of freedom... https://vimeo.com/17420638 )
Another trap is redefining #== without also looking at #eql?, which means Hash doesn't behave like you expect. It's just another bit of mental trivia you've got to Just Know...
For example BigDecimal. With operator overloading, I can easily compare a BigDecimal object to an integer or float, the same way I can already compare them to each other:
BigDecimal.new("10.0") == 10.0
10 == 10.0
Without operator overloading, this would become needlessly messy (and require explicit handling of nils): d = BigDecimal.new("10.0")
!d.nil? && d.value_equal_to(10.0)
Ruby has always been about readability of the code, and avoiding unnecessary repetition, and I think operator overloading (when used correctly) is a great example of this.The default `==` from Object compare identity, so unless you define it `Money.new(20, 'USD') != Money.new(20, 'USD')`.
Is this just a complaint about the ability to overload operators in general?
Instead of overloading, I've always wanted to define new operators e.g. <DotProduct> used as 'int x = v1 <DotProduct> v2;'
If you're going to do something with operators, at least let me make descriptive ones.
But still, this is a really cool trick that I didn't know you could pull off with Ruby, so thanks for sharing!
Honestly, I wish there were more people doing posts about recreational programming topics. WhyTheLuckyStiff was one of the last great recreational Rubyists. I miss that kind of no-holds-barred exploration.
In Ruby, no visual indication exists. Worse, things like attr_reader blend instance variables with local variables and method identifiers. Throw in a method_missing and inheritance, and you can easily lose weeks just tracking down where an identifier is even coming from. Throw in a gem or two, and all hope is lost.
It may not be depending on the context; consider:
(let ((foo 123)
(+ 'please-dont-do-that))
(print foo)
(print +))
Both `foo' and `+' are variables here - while present on a first position of an S-expression at one point - even if you're running a Lisp-1 (like Scheme), i.e. where functions and variables share a namespace - or rather, a symbol can have separate function and value bindings. In Lisp-n (like Common Lisp) you can have a variable slot bound to a function value (i.e. lambda).But one thing Lisp does have, which impacts readability significantly IMO, is simple and consistent syntax. Contrast to some Ruby-like languages which let you skip braces when working with dictionaries, making you stop and wonder how the hell a given piece of code is going to be parsed by the interpreter. Or Scala, which has so much context-dependent meaning bound to non-letter characters that I finally start to understand why people were afraid of C++ operator overloading. Both examples are, in my opinion, cases of syntactic sugar leading to cancer of semicolon.
def some_method
what_is_this
end
You don't know what what_is_this is. It could be an instance variable, a method (anywhere in the inheritance tower), or an autogenerated method from method_missing. It's impossible to tell without digging through the code. But the problem there is, you can't simply grep the code for things like this. You could end up with 100s of uses of the identifier and never find the source. Especially if you inherit a class from a gem, or method_missing has been used.> In Lisp-n (like Common Lisp) you can have a variable slot bound to a function value (i.e. lambda).
Yes, and Lisp-1 vs Lisp-n has been a hot debate for decades in both Lisp and Scheme communities. I'm not about to claim it's a completely solved problem there.
I hate this "dynamic programming[0] = hard to debug" meme. A truly hard to debug code is one that's nonlocal (you have to read 20 files to follow the execution flow (hello Scala trait abusers)) or displays random behaviour (e.g. threading, dependence on external resources). This one? Every "tricky" thing is contained in a block of 10-20 lines. Just isolate the endpoints and follow the execution until it does something you think it shouldn't.
In a way, the biggest enemy of a bug hunter is their own assumptions.
[0] - examples here aren't really metaprogramming, and even the latter isn't that hard to debug if you actually sit down and read the code.
I recently re-watched Yaron Minsky's "Effective ML" talk where (towards the end) he talks about making read-only and read-write types. That's where I thought Jamis was going with the state machine example: one could tell an object "yo, make yourself immutable!" (ie redefine your methods so that you can't change yourself). But in an OO world that seems more neatly achieved with subclassing. [To the extent of faking anything "immutable" in ruby"].
There's #freeze I suppose... and no #unfreeze. Which is perhaps sensible :) And #freeze only guards against new assignment to instance variables; it doesn't guard against an instance method mutating the content of an instance variable (def esquirify! ; @name << ' Esq.' ; end). So there's that. But I'm far from convinced...
Python has this "inner-methods" capability (with saner scoping) which is a great antidote for python's limited lambdas. But that's not a problem with ruby.
It's a neat trick (and nice to read something from Jamis again). Are there any sensible use cases?
class S
class << self
attr_accessor :singleton
end
attr_accessor :value
def initialize
@value = "xxx"
S.singleton = self
def S.new
S.singleton
end
end
end
a = S.new
# => #<S:0x007ff4a41532e0 @value="xxx">
b = S.new
#=> #<S:0x007ff4a41532e0 @value="xxx">
a.value = "zzz"
b.value # "zzz"
a.object_id == b.object_id
#=> true
That said... doing this may win you great sorrow.http://www.tclcommunityassociation.org/wub/proceedings/Proce...
Somebody now shall goeth forth and implement Zork...
Bash:
$ foo()
{
bar ()
{
echo I am bar
}
}
$ bar
bar: not found
$ foo
$ bar
I am bar
Pretty much the same thing as the Ruby example.This is simply because function defining is a kind of statement or expression with a side effect which must be evaluated. The side effect is global (a name is globally associated with a function). So if the side effect is in a function body, its evaluation is delayed until the function is called, and then its effect is still global.
Does this work in Plan 9 rc?
In Python, an inner def will lexically bind a function, creating a closure. Python is not less dynamic than Ruby.
In Common Lisp, a defun inside a defun will behave similarly to Ruby; but if you want lexically scoped local functions, you use a different operator, namely flet or labels.
Scheme has a define which is lexical: it brings a lexical identifier into the scope for forms which follow.
Lexically scoped items, even in a dynamic language, in fact can be "cast in stone when you press the compile button"; they are cast in that stone which is the entire compiled environment of the surrounding function.
Metaprogramming has a place in Ruby but for the examples in the article there are far more readable ways to implement it.
Readability > cleverness every single time.
This is hacker news, not "production code" news. Abusing things in unexpected ways is pretty much the definition of hacking.
Many people seem to be jumping on this article as if the author was suggestion a new programming pattern we should start using, rather than an interesting look at some of the lesser-known quirks of ruby. I'm pretty sure even the author would agree that triple nested method definitions are not something we should use for production code.
What I would say is that although we should have an extremely good reason to employ these techniques in production, I believe that every professional Ruby programmer should be able to understand them and/or figure them out in a few minutes.
It’s not like we’re talking about obfuscated C.
However, metaprogramming is a power that should be used wisely. When implemented unnecessarily it reduces readability (and probably performance) for no real gain.
The devise source contains some great examples of metaprogramming used properly:
https://github.com/plataformatec/devise/blob/master/lib/devi...
Readability is in the eye of the beholder. For those unfamiliar with higher-order programming, maps are just a 'too clever' form of a for loop.
A clean and understandable solution is one matching the problem being solved in a precise way. In search for simplicity one can't forget that programming is a trade, and one should be expected to actually learn some shit.
In other words - just because you don't understand something doesn't mean it's "clever code".