instanceof 被认为有害吗?

发布于 2025-01-07 16:12:49 字数 208 浏览 3 评论 0原文

我正在查看一些大量使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

贱贱哒 2025-01-14 16:12:50

是的,您走在正确的道路上。虽然 instanceof 当然有其用途,但大量使用通常表明您的类设计存在缺陷。

Yes, you are on the right track. While instanceof certainly has its uses, heavy use generally indicates that your class design is deficient.

看海 2025-01-14 16:12:50

在 Java 中,泛型可以/应该用于减少 instanceof 关键字的数量。这样,只需检查那些在编译时未知的少数内容。也就是说,instanceofgoto 不同 - 它不会过多地扰乱您的控制流程(尽管如果您不小心,它确实会引入许多额外的变量)。

我经常使用 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 like goto - 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 of instanceof is probably wrong. I would not know of a scheme to see if the use is good or bad for generic cases. The cast after instanceof is probably hurting more than the keyword itself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文