Dave Thomas of The Pragmatic Programmer fame posted a few posts on class design in OO systems:
He makes the case that if a routine requires no external state, it should not be part of a class. I guess?
The entire point of classes is to create objects in a way that not only encapsulates their state, but hides if they even have state in the first place.
SomeClass.new.some_method
You want to call some_method
. In Ruby, you have to call that on some object. So you need that object. SomeClass.new
gives you that object. If that object needs state or not, it doesn't matter and shouldn't. This is what you have to do to call the method.
Compare to:
SomeNamespace.some_method
Here, again, you want to call some_method
which requires an object on which to call it. In this case, that object is the constant SomeNamespace
. You didn't create it, and it may or may not have state. If it does, it's likely global, which is complicated and undesirable.
Behind the scenes, if some_method
doesn't have state, I'd argue there's no real difference in these approaches, save for four characters: .
, n
, e
, and w
.
But creating some_method
as a stateless function means if you need it to have state later…it's fairly difficult to achieve without requiring all callers to change.
I'm just not really sure what the benefit is supposed to be.
Some proponents of Dependency Injection believe you should never call .new
(or new(...)
). If that's how your system is designed, I would say again, none of this matters. Something somewhere is creating your objects for you. They are probably being created with .new
and this is fine.
There's nothing wrong with making a class that currently has no state and has a no-arg constructor, and you will probably never regret designing your entire codebase that way.
.new
and call methods that have names is pretty darn debuggable.Unless otherwise noted, my emails were written entirely by me without any assistance from a generative AI.