2010/6/14 Rein Henrichs <reinh / reinh.com>:
> On 2010-06-13 10:27:48 -0700, Micha Zajc said:
>
>> I write in ruby for few weeks and I have noticed that in ruby I use class
>> (static) methods more often than in "traditional" languages like java orc#.
>> In java I use instance methods for two purposes - maintaining object state
>> and to use polymorphic behaviour. In ruby polymorphism is available to class
>> methods as well as for instance ones so I don't see need for using instance
>> methods in stateless classes (for example typical application / domain
>> services).
>>
>> It is common for ruby programmers or maybe I have miss something?
>
> Classes are designed to instantiate objects. If you have classes that
> consist solely of class methods then they aren't functioning as classes at
> all but rather as convenient globally-available namespaces for singleton
> methods, which is a very procedural style of progrmaming. Procedural
> programming is not necessarily bad, but you are missing out on a great deal
> of the power and flexibility of an OOP langauge by writing procedural code.

As a compromise Michael could use module Singleton and thus define
instance methods without the overhead of creating new instances all
the time.

irb(main):001:0> require 'singleton'
=> true
irb(main):002:0> class Foo;end
=> nil
irb(main):003:0> (1..3).map { Foo.new }
=> [#<Foo:0x1029b494>, #<Foo:0x1029b478>, #<Foo:0x1029b45c>]
irb(main):004:0> class Foo; include Singleton; end
=> Foo
irb(main):005:0> (1..3).map { Foo.new }
NoMethodError: private method `new' called for Foo:Class
        from (irb):5:in `block in irb_binding'
        from (irb):5:in `each'
        from (irb):5:in `map'
        from (irb):5
        from /opt/bin/irb19:12:in `<main>'
irb(main):006:0> (1..3).map { Foo.instance }
=> [#<Foo:0x10268b88>, #<Foo:0x10268b88>, #<Foo:0x10268b88>]
irb(main):007:0>

Singleton pattern allows for easier migration if at a later point in
time instances need state.

> Then again, if the system works for you and maintainability and other core
> values do not appear to suffer, who's to say you're doing it wrong? Even
> asking the question shows that you're thinking critically about the
> tradeoffs involved here, which is a good start.

Absolutely agree!

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/