什么时候使用instanceof的正确决策? [英] When is using instanceof the right decision?

查看:86
本文介绍了什么时候使用instanceof的正确决策?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我一直都明白的那样, instanceof 适用的主要情况是:

As I've always understood it, the main cases where an instanceof is appropriate are:


  1. 实现 Object.equals(Object)。所以如果我正在编写一个列表类,并且由于任何原因而不扩展 AbstractList ,我将实现 equals(o)首先测试 o instanceof List ,然后比较元素。

  2. A对于不 的特殊情况,重要(算法?)优化可以改变语义,而只改变性能。例如, Collections.binarySearch 对RandomAccess 测试执行实例,并使用稍微不同的二进制搜索 RandomAccess 和非 RandomAccess 列表。

  1. Implementing Object.equals(Object). So if I were writing a List class, and not extending AbstractList for whatever reason, I would implement equals(o) by first testing o instanceof List, and then comparing elements.
  2. A significant (algorithmic?) optimization for a special case that does not change semantics, but only performance. For example, Collections.binarySearch does an instanceof RandomAccess test, and uses a slightly different binary search for RandomAccess and non-RandomAccess lists.

我不认为 instanceof 表示这两种情况下的代码气味。但是有什么其他情况下使用 instanceof 是明智的吗?

I don't think instanceof represents a code smell in these two cases. But are there any other cases where it is sensible to use instanceof?

推荐答案

p>旧版代码或控件之外的API是 instanceof 的合法用例。 (即使这样,我宁愿在其上写一个OO层,但时间有时排除了这样的重新设计。)

Legacy code or APIs outside of your control are a legitimate use-case for instanceof. (Even then I'd rather write an OO layer over it, but timing sometimes precludes a redesign like that.)

特别是,基于外部类层次结构的工厂似乎是常见用法。

In particular, factories based on external class hierarchies seem a common usage.

这篇关于什么时候使用instanceof的正确决策?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆