James B. wrote:
Suraj K. wrote:
Who cares what the type/class of an object really is, so long as the
object can be interpreted in a meaningful way in the particular usage
context? Sounds like the fundamental concept of duck typing to me.
This is what I’m warning against:
First release of some library API
def account?
@account
end
In some naive end-user’s code:
@a.cancel if @a = foo.account?
Naive indeed. Why would anybody use a question mark method in that way?
They are only meant to be used in boolean contexts.
I think the convention lies not in what the return value of a
question-mark method is, but in what way the return value is used:
if foo.account?
foo.account.cancel
end
Later release of library API, after some internal changes
def account?
parent_has_account_and_is_active?
end
Now, what happens to the end user’s code?
‘account?’ is still meaningful as a true/false indicator method; code
(mistakenly) relying on a more meaningful return object may get a
surprise one day.
Exactly. That was foolishness on the user’s part.
I’m arguing that methods that end in “?” should be designed and used as
answers to true/false or yes/no questions. That they can return an
arbitrary non-nil object to indicate ‘true’ is convenient, but I’m
skeptical of the value of “?” methods being used as both boolean
indicators and object accessors.
Ah, now I understand your point. I never considered them being used as
object accessors because you would never know it was an object accessor
just by looking at the method name.
foo.account? does not appear like an attr_reader because of the
question-mark.
Its a matter of hiding implementation details, and self-documenting
code.
Now, should one do this?
def account?
@account ? true : false
end
Yuck! No way. This is what I was arguing against. No forcing of
return value to be true/false only.
Well, maybe; it might keep end-users from trying to be too clever.
I don’t see how they can be clever unless they look at the underlying
implementation of your classes. When I see the name of a question-mark
method, I think “this method answers a yes/no question”. There is no
way I would think otherwise unless I was given insider information about
the method’s implementation.
But I don’t think it should be baked into the language.
I think the “accessor” in attr_accessor might have mislead you guys
about this whole question-mark argument.