instanceof 被认为有害吗?
我正在查看一些大量使用 Java 的 instanceof
运算符的代码。我会抵制住细节的诱惑,因为这是一个普遍性的问题。 instanceof
让我想起了 C++ 的动态转换,以及我很久以前读过的有关它的建议,如果您认为需要它,那么您的模型可能已关闭。这仍然是传统观念吗?它适用于 Java 的 instanceof
吗?
I am looking over some code that has heavy use of Java's instanceof
operator. I will fight the temptation to go into details, since this is a general question. instanceof
reminds me of of c++'s dynamic cast, and the advice I read about it, long ago, that if you think you need it, probably your model is off. Is this still the conventional wisdom? Does it apply to Java's instanceof
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您走在正确的道路上。虽然
instanceof
当然有其用途,但大量使用通常表明您的类设计存在缺陷。Yes, you are on the right track. While
instanceof
certainly has its uses, heavy use generally indicates that your class design is deficient.在 Java 中,泛型可以/应该用于减少
instanceof
关键字的数量。这样,只需检查那些在编译时未知的少数内容。也就是说,instanceof
与goto
不同 - 它不会过多地扰乱您的控制流程(尽管如果您不小心,它确实会引入许多额外的变量)。我经常使用
instanceof
,但如果有很多,那么我会认为它是代码味道。诀窍是想出更好的东西;如果可以,那么instanceof
的使用可能是错误的。我不知道有什么方案可以看出使用对于一般情况是好是坏。 instanceof 之后的转换可能比关键字本身造成的伤害更大。In Java, generics could/should be used to reduce the number of
instanceof
keywords. In that way only those few that are not known at compile time need to be checked. That said,instanceof
is not something likegoto
- it doesn't mess up your control flow much (although it does introduce many extra variables if you're not careful).I use
instanceof
regularly, but if there are many then I would consider it code smell. Trick is to come up with something better; if you can, then the use ofinstanceof
is probably wrong. I would not know of a scheme to see if the use is good or bad for generic cases. The cast afterinstanceof
is probably hurting more than the keyword itself.