7 ms·
"DCI" in Ruby is completely broken
- lucisferre 14y agoFrom my experience the main benefit comes from the alignment of particular scenarios, with contexts, the result of which is a single place to reason about the algorithm(s) behind that scenario. I see very little reason for the dogma behind the way role injection is typically handled, yet everyone seems to be attached to doing this in Ruby. This is odd because there are DCI examples in almost every language, each one has it's awkwardness when it comes to roles, but they all manage to get it done with some workaround. I don't see why Ruby should be any different, if it wasn't possible to call #extend, we'd just do it another way. Either way, I wouldn't dismiss DCI just because the canonical approach some academics cooked up is completely senseless in practice. In fact the author seems to agree in the end so the title is a bit exaggerated.
- dasil003 14y agoI'm late to the party, but I read all the comments and I think yours is the best. DCI is a powerful design concept in any class-based language. When behavior gets complex, DCI is the cure for the "kingdom of nouns" that results from a beginner-level understanding of how to apply OOP. In short, DCI is a way to elevate business tasks to first-class citizens. The singleton method business is purely an aesthetic concern. It definitely makes for more appealing code, but at the cost of an order of magnitude performance hit. All else being equal I love elegant code as much as the next rubyist, but this is simply too high a price to pay and I'm shocked that so many people find this acceptable.
- eduardordm 14y agoRuby is a language, not an implementation. DCI in ruby seems just fine, but all implementations are not friendly to the dynamic mixin hell hole.
- latortuga 14y agoCompletely agreed, the title is a red herring and serves to dissuade people from giving DCI a try. "It's too slow" is not an argument against DCI, it's an argument for fixing a slow implementation of #extend or using a different method.
- bascule 14y agoWhy not do DCI with delegation instead of mixins?
- davnola 14y agoBecause in general, delegation tends to lead to object schizophrenia. Specifically, SimpleDelegator will leak the original delegatee object when a delegated method returns `self`. s = "foo" d = SimpleDelegator.new s s2 = d << "bar" s2.object_id == s # true I think SimpleDelegator is really neat but totally dangerous. Doesn't this ring alarm bells with you? # delegate.rb L117 # # Returns true if two objects are considered of equal value. # def ==(obj) return true if obj.equal?(self) self.__getobj__ == obj end
- bascule 14y agoWhile this is true, it currently has pathological performance on all major Ruby implementations.
- eduardordm 14y agoI just wonder if fixing this (by adding extend calls to cache) will end up making unicorn eat way too much memory.
- mst 14y agoThe perl equivalent (run-time role application) normally caches the extended class by default and re-uses it. Provided you don't have a pathological number of combinations, that seems to work out pretty well.
- perlgeek 14y agoErm what? Changing the class hierarchy invalidates all method caches? That sounds a bit brutal, and totally unnecessary. Can't you just have a method cache per metaclass (or class; I'm not very familiar with how Ruby factors this stuff)? Since mixing in a role into an instances creates a new metaclass anyway, there's no need to affect instances of the original class.
- FooBarWidget 14y agoIt's because MRI's implementation is simple. They haven't bothered caching per class because it takes more code. However JRuby caches per class.
- enebo 14y agoIf you have to go and look up the method again (even ifcached) because the callsite cache is invalid then you already lost. Constantly invalidating the callsites is the real problem with this pattern.
- moondowner 14y agoJust to note tha NetBeans RCP uses DCI as well, quite successfully. http://wiki.apidesign.org/wiki/DCI http://wiki.apidesign.org/wiki/DCI http://www.antonioshome.net/kitchen/nbdci/ http://www.antonioshome.net/kitchen/nbdci/
- minimax 14y agoI'm not a Ruby programmer, so maybe I'm misunderstanding the article -- are we talking about changing an object's class hierarchy after it's already been instantiated and then complaining that it's the performance aspect that is pathological? That sounds like a completely insane way of writing software to me.
- FooBarWidget 14y agoYes, that is what the author is talking about. I'm not sure what his point is though. This fact has been known for years and if you care about performance, you simply don't modify the class hierarchy.
- urbanautomaton 14y agoIt doesn't seem to be widely acknowledged amongst people promoting this particular style of DCI as a good way to write Rails app, so I'd say the point is valid, even if the title is overstated. There are also quite a few other very popular gems that make heavy use of #extend at runtime for non-DCI purposes, including Haml and Paperclip, so I don't think it's fair to say that this is common knowledge (at least in the Ruby community).
- lnanek2 14y agoIt isn't so odd in Ruby. Ruby has always been a duck typing land. If it quacks, it is a duck. There's even a method missing handler so you can respond to any method call whatsoever. People can and do add methods directly to even built-in classes as well, the equivalent of modifying the class prototype in Javascript. So method calls are considered more messages in Ruby and saying a class will respond differently to a message after it has more data about what it is, a certain blog for example, isn't so strange to Ruby programmers.
- cube13 14y ago>It isn't so odd in Ruby. Ruby has always been a duck typing land. If it quacks, it is a duck. There's even a method missing handler so you can respond to any method call whatsoever. What's the benefit of this kind of typing, though? I'm pretty much just a C hacker these days, so I'm pretty ignorant about Ruby, but does this apply to the object or to the class? It seems simpler, especially on a conceptual level, to just initialize the the duck with everything it could possibly need to be a duck, rather than adding things dynamically.
- tptacek 14y agoI've had similar experiences profiling Ruby code, replacing dynamic constructions with static ones, and seeing orders of magnitude bumps in performance. One thing I've learned never to do is to "customize" short-lived objects at runtime with new methods. If you create an object in response to user input, it should be born with all the methods it's going to need.
- technoweenie 14y agoI was curious what Tony's graph would look like using a SimpleDelegator as he suggested. (using ruby 1.9.3p194) Calculating ------------------------------------- without dci 68507 i/100ms with dci 24409 i/100ms with delegator 46945 i/100ms ------------------------------------------------- without dci 2240202.4 (±3.2%) i/s - 11235148 in 5.020463s with dci 412445.3 (±3.7%) i/s - 2074765 in 5.037113s with delegator 1018928.4 (±1.6%) i/s - 5117005 in 5.023310s RUBY: require 'rubygems' require 'benchmark/ips' require 'delegate' class ExampleClass def foo; 42; end end module ExampleMixin def foo; 43; end end class ExampleProvisioner < SimpleDelegator def foo; 44; end Benchmark.ips do |bm| bm.report("without dci") { ExampleClass.new.foo } bm.report("with dci") do obj = ExampleClass.new obj.extend(ExampleMixin) obj.foo end bm.report("with delegator") do ExampleProvisioner.new(ExampleClass.new).foo end end
- bascule 14y agoWhich is pretty much what you'd expect... making two objects instead of one cuts the speed approximately in half.
- urbanautomaton 14y agoI took a stab at separating out the method dispatch costs from the cost of the #extend call here https://gist.github.com/4436640 https://gist.github.com/4436640. I also tried making a call against an unmodified instance of a completely different class to demonstrate that the global method cache is indeed flushed in MRI by doing a runtime #extend on any object instance. Subtracting the results of different runs like this is pretty questionable, though (the errors accumulate), so the above is to be taken with a pinch of salt.
- zem 14y agothe example in the op was somewhat misleading in that he was extending the object within its initialize method. i think you'd more often want to do a per-object extend dynamically at runtime to simulate something like smalltalk's #become, where the object would be modifying its capabilities and 'type' based on some external input conditions.
- mrgoldenbrown 14y agoThe title of the post is unnecessarily inflammatory. It should be "Using extend to do DCI in Ruby is completely broken." The author even admits this in the article, and points out other ways of doing DCI in Ruby.
- re_todd 14y agoWhat titles are NOT unnecessarily inflammatory nowadays?
- dogas 14y agoDCI is a paradigm related to design and architecture. Computers are so fast today that does this benchmarking business really matter? If DCI helps to keep your code maintainable, readable, and less buggy, is that a better tradeoff? I would think that 95-99% of the time, the answer is yes. On a side note, if speed is mission critical, then would ruby really be the language of choice to use?
- CrLf 14y ago"Computers are so fast today that does this benchmarking business really matter?" Famous last words. Computers are much faster than they were years ago, but look at how much crap they have to deal with... So much crap in fact that we barely notice they are indeed much faster. So much crap that hardware can barely keep up. Performance is never mission critical until it becomes mission critical, and that usually happens all of a sudden. It's that moment a few days into production when the system becomes unbearably slow and the rest of the company is breathing down your neck asking "WTF is going on?! Fix it, NOW!". It's problematic enough when you are just creating to many objects and making processor caches irrelevant, but if your performance issues are baked directly into your coding style... good luck with that.
- LnxPrgr3 14y agoWe're not talking micro-optimization to squeeze an extra 0.5% performance out of a system. We're talking about an order of magnitude (or more) slowdown, in a language already not exactly known for its blazing speed. My question of the day: why isn't more time spent on building abstractions that aren't just convenient but that are also fast? Why does readable, maintainable code have to mean code so slow it effectively turns Core i7s into Pentium 90s? I don't think it has to mean that at all, but that's exactly the choice a lot of programmers seem to think they're making.
- ryeguy 14y agoYou know, I've been thinking about this kind of thing lately. All of this mixin, traits, monkey patching hoopla is completely nonexistent in functional programming languages. To add a new method to an object you just..write a function that takes that piece of data. Imagine a language where a call looked like this: user.doSomething(1, 2, 3) But it's just syntax sugar for this function application: doSomething(user, 1, 2, 3) ("user" would be just the data..like a struct type thing) That way you get the flexibility of loose functions but you get the (imo) superior aesthetics of oop languages.
- zzzeek 14y agohow is that not what Python already is: >>> class Foo(object): ... def __init__(self): ... self.x = 1 ... self.y = 2 ... def bar(self): ... return self.x + self.y ... >>> Foo().bar() 3 >>> f = Foo() >>> Foo.bar(f) 3 >>>
- Tuna-Fish 14y agoBut you cannot do it the other way, eg: def foo(bar, baz): print bar.baz + baz f = Foo() f.foo(3) # error
- zzzeek 14y agoClaiming "f.foo" should work when "foo" is a freestanding function strikes me as nonsensical, as the "." operator is a namespace operator, suggesting names that are within the namespace of "Foo". Though Postgresql supports this pattern (http://www.postgresql.org/docs/9.2/static/xfunc-sql.html#XFUNC-SQL-COMPOSITE-FUNCTIONS http://www.postgresql.org/docs/9.2/static/xfunc-sql.html#XFU...). I think it's awkward there too, and has the caveat "it's unwise to give a function that takes a single composite-type argument the same name as any of the fields of that composite type." - basically it breaks namespacing.
- swift 14y ago
- bcheung 14y agoI thought the same thing when I came across the DCI pattern. It is very useful for beautifying and simplifying use cases that span lots of objects. I do something slightly different. I create a class directly for the context and then fire an object into it. class TheContext def initialize # ... end def execute(the_object) # ... end end
- reedlaw 14y agoIn practice, we've been using DCI (with object.extend) in a production Rails app and have seen no worse performance degradation than in other apps with comparable complexity (at least subjectively--of course it's very difficult to measure objectively). Typically plenty of production apps suffer more from simple things like missing an index on a db column, N+1 queries, iterating over objects in Ruby, or poorly-thought out design. DCI in Rails is a pretty good trade off for when you need to use it.
- andrzejkrzywda 14y agoI'm "thinking in DCI" for 2 years now. At GameBoxed (http://gameboxed.com/ http://gameboxed.com/) we've got a Rails app that uses a lot of .extend on every request. It's in production for 1.5 year now. It's a backend for multiple social games (one backend app for many CoffeeScript frontends). It's not huge in terms of traffic and performance needs. We implemented it with a DCI-like architecture in mind. It was helpful at the beginning. DCI wasn't the only way to implement it, but it was the simplest way for us at that time. We've had some performance problems, but they were never related to the usage of .extend. If it was a performance problem, we would probably consider removing the .extends (not a big deal), switch to Java, do more caching, there are so many options. Again, we don't have huge performance needs, we've maybe 40 req/s at peak times. DCI is much more than .extend, it's a huge shift in thinking about the OOP architecture. If we (as Ruby community) agree that it's an architecture worth trying, then maybe it makes sense to introduce better optimisations techniques to the current Ruby implementations? Anyway, it's great to see the discussion happening. DCI may not be ready to use right now, but it's more of a change in thinking than in the implementation. I definitely wouldn't call it completely broken in Ruby. Here are some of my posts on DCI in Ruby: http://andrzejonsoftware.blogspot.com/2011/02/dci-and-rails.html http://andrzejonsoftware.blogspot.com/2011/02/dci-and-rails.... http://andrzejonsoftware.blogspot.com/2012/01/dci-and-rails-lessons-learnt.html http://andrzejonsoftware.blogspot.com/2012/01/dci-and-rails-... http://andrzejonsoftware.blogspot.com/2011/08/dci-patterns-how-to-write-dci-contexts.html http://andrzejonsoftware.blogspot.com/2011/08/dci-patterns-h...
- bascule 14y agoWhat does extend give you that delegation doesn't?
- andrzejkrzywda 14y agoAt a code level - no need to write the delegation methods/macros. At the design level - flat hierarchy At an abstract level - thinking in terms of objects, not classes.
- 14y ago
- transfire 14y agoThere's more than one way to skin a cat. Besides mixins, You don't even have to use SimpleDelegator to do delegation in Ruby. For example, here is a demonstration of another approach to DCI in Ruby (http://github.com/rubyworks/dci http://github.com/rubyworks/dci).
- htyden 14y agoExtending is expensive. Delegating is usually cheaper, just be careful how you do it. https://gist.github.com/4441557 https://gist.github.com/4441557 I guess the upside of `extend` is that you can do it at the call site, delegation has to be configured upfront.
- evan2 14y agoYou can do DCI without singleton methods in Ruby.