3 ms·
I think it depends on the situation, and it's difficult to for me to describe. I try to think about it like this: I am writing a class to represent a car. I
by tenderlove 14y ago
I think it depends on the situation, and it's difficult to for me to describe. I try to think about it like this:
I am writing a class to represent a car. I need to know if the cars doors are opened or closed. The `open` or `closed` attribute is the state of the car, so it makes sense that the Car object would have that state.
Now compare that to the use of `LanguageDetector` from the example:
LanguageDetector.new(@comment).set_language
Presumably this object is keeping a reference to the comment for it's internal state. When I'm dealing with an object, I like to say in my head "language detector, can you tell me the language for some text?". Nothing in my question gave the text a 1:1 relationship with the language detector. Since my question did not identify a relationship, I would not make the comment a part of the LanguageDetector object. I'd rather write something like this:
detector = LanguageDetector.new
language = detector.detect_language(@comment)
@comment.language = language
What might the LanguageDetector actually want to have as it's state? I think maybe things like encodings, or particular languages it supports. The question I ask is "language detector, what encodings or languages do you support?", and the relationship becomes clear. For example:
detector = LanguageDetector.new(:encodings => [...], :languages => [...])
# etc
I hope that makes sense, and that I don't sound too crazy (talking to myself and whatnot).