Hacker News new | past | comments | ask | show | jobs | submit login

Since you don't control the code that manufactures instances of MyClass.new, you don't have an opportunity to manipulate the metaclass/singleton class of instances of MyClass. So this technique doesn't work.



Dunno about Ruby, but in Perl and Common Lisp you just rebless the instance into a subclass that you do control.

http://www.lispworks.com/documentation/HyperSpec/Body/f_chg_...

http://transfixedbutnotdead.com/2009/07/07/moose-singleton-m...


Since you don't control the code that manufactures instances of MyClass.new

At least I didn't until I monkeypatched MyClass#initialize at runtime. cackles

Seriously, don't do that. But it is fun to contemplate.


The basic idea is adding methods to single instances. It _does_ work. What you're talking about is sugar. You could easily create a factory which manipulates instances as they are created.


Yes but you still need to inject the Factory. My point is not that Java is better than Ruby but that this style, which is commonly associated with Java, is better in any language.


Parameterizing behavior is usually a good thing in any language, yes...

The part that Python/Ruby got right is that their culture says don't parameterize until you have to. While Java culture tends to build in generality for the sake of generality, whether or not the actual system needs it. Many systems don't, but if you use typical Java libraries, you need to pay the costs for it regardless.

There was a red-flag in one of your comments above: "since you don't control the code, this technique doesn't work". If you don't control the code enough to make necessary modifications, you have a cultural problem, not a technical problem. Fix the culture, not the code. You should be building the simplest system that possibly works, not hacking around code ownership restrictions.

Parameterization is useful when you have one piece of code that you know needs to work in multiple contexts, not when you're trying to make sure a piece of code will work in all possible contexts a priori.


Isn't that the exact opposite of what the original quote was decrying?

And you can always open the eigenclass of any object in ruby for the ultimate surgical operation (THIS INSTANCE, RIGHT HERE!). It's pretty much the ultima ratio regum of special casing in any object oriented language.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: