From: Rein Henrichs Date: 2010-06-15T08:10:07+09:00 Subject: Re: Do I overuse class methods? On 2010-06-14 10:35:10 -0700, Michał Zając said: > W dniu 2010-06-14 15:33, Robert Klemme pisze: >> >> As a compromise Michael could use module Singleton and thus define >> instance methods without the overhead of creating new instances all >> the time. >> > > I think this is interesting idea. > I have spent much time in Java / C# environments with heavy use of > dependency injection pattern so maybe this is source of my aversion to > stateless classes manual instantiation - usually something else has > done it for me :D Using Singleton pattern is more similar to Service > Locator but it may be good alternative. > > Thanks Ruby's design patterns (in the Gang of Four sense) are extremely lightweight compared to their Java equivalents. Rick Olsen's Design Patterns in Ruby book shows good idiomatic Ruby implementations of the GoF patterns. That said, I don't think you want a Pattern at all. I think you want a more *object oriented* architecture. IRT Singleton: I think that Singleton is just a way to cheat and get global state that looks like instances. I didn't present it as a solution because (imo) it's really just a restatement of the problem. I try to avoid it for the same reasons that I try to avoid the classes you're asking about. Let me put it this way: replace all of your pseudo-classes (these classes that don't instantiate and are used as singleton method holders) with this: YourClass = Object.new def YourClass.some_method ... do stuff ... end ... more ... This is functionally equivalent. Does this look like good Ruby code? Is this good OO design? If not, why not? The classes you're asking about aren't (functionally) classes at all: they're just objects like this one. You should object to them for the same reasons that you (may) object to the above. Also, Ruby has far better mechanisms than dependency injection. So much so, in fact, that Rails core member and creator of two different Ruby dep. injection libraries, Jamis Buck, recently gave a great talk about why you don't need dependency injection in Ruby. Summary is here, and is a good read if you're coming from heavy, "enterprisey" languages like Java: http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming. Coming from a Java background, the best thing you can do is let go of the heavy pattern-driven architectures that are common in enterprise-land (the ServiceLocator, CachedTemplateFactoryProxyFactory, whatever) and enjoy the freedom of working with simple, lightweight classes and objects. -- Rein Henrichs http://puppetlabs.com http://reinh.com