-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unspecified Style point: obj.is_a? vs obj.class == Class #416
Comments
Narrowing the type check feels like an anti-pattern to me, as it reduces the flexibility of the code. I'd advise against the use of explicit class checks. Let's see what the others will have to say about this. |
I'd say it has nothing to do with style, because Example 1: 4.is_a? Numeric # => true
Math::PI.is_a? Numeric # => true Example 2: 4.class == Fixnum # => true
Math::PI.class == Fixnum # => false Both examples reflect legitimate needs of real world problems and both should be used where needed. Can't see any possible guided preference here. |
I don't see why in the second case you wouldn't want to use |
Wrong example, my bad, I was writing it at night. I meant that |
@DanielVartanov Right, I agree that the functionality is not the same because By the way, if anyone is interested in a concrete example, I wrote this on a Stack Overflow answer:
And someone pointed out that it would be more appropriate to use |
@devonparsons, yes I see what you mean after reading your answer at stackoverflow. I do agree that Usage of |
I agree that inheriting from base classes is a common enough occurance that the point should be made explicit to promote safety. So perhaps an appropriate style point should read something like: Prefer
I'm sure @bbatsov can write that better than me but we get the gist |
Yeah, we can definitely add something along those lines, although I wouldn't use an example involving inheritance from String, as doing so is rarely a good idea. :-) A related rule might be that for API it's better check for capabilities than for types - e.g. if you check that something |
Although the case equality operator === is mentioned, of the two methods of class checking demonstrated here:
Neither are stated as preferred. I think it's fairly well agreed that
is_a?
is the the more Ruby way of doing things, but I've seenobj.class == Classname
fairly often as well and it's easily readable.The text was updated successfully, but these errors were encountered: