在使用对象树时我应该避免使用instanceof吗?
我有一个代表不同语言构造的类层次结构:
Expression <- NumericLiteral
UnaryExpression
BinaryExpression
IndexingExpression
IteratedExpression
...
这些类的对象形成复杂的树层次结构,我必须在其上执行各种结构检查,例如,如果节点是 IteratedExpression,则其第一个子节点应该是 IndexingExpression。如果检查只涉及一个级别,我可以使用访问者模式,但在更复杂的情况下,如下例所示,我使用instanceof。
void visit(IteratedExpression node) {
if (!(node.getChild(0) instanceof IndexingExpression)) {
// report error
}
}
这是instanceof的正确使用还是我的设计有缺陷? 有哪些替代方案?
由于建议了一些替代方案,我想强调问题的第一部分:
这是instanceof的正确使用还是我的设计有缺陷?
I have a class hierarchy representing different language constructs:
Expression <- NumericLiteral
UnaryExpression
BinaryExpression
IndexingExpression
IteratedExpression
...
The objects of these classes form complex tree hierarchies on which I have to perform various structural checks, e.g. if the node is an IteratedExpression then its first child should be an IndexingExpression. If the check only involves one level I can use the Visitor pattern, but in more complex cases as in the example below I am using instanceof.
void visit(IteratedExpression node) {
if (!(node.getChild(0) instanceof IndexingExpression)) {
// report error
}
}
Is it a proper use of instanceof or I have a flaw in my design?
What are the alternatives?
Since there were some alternatives suggested I would like to emphasize the first part of the question:
Is it a proper use of instanceof or I have a flaw in my design?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样:
如果您想使用 Visitor,树中有多少层并不重要。
Like this:
If you want use Visitor it doesn't matter how many levels you have in your tree.
向
Expression
添加一个抽象方法并在其子项中实现它。所以每个班级都会有自己的检查。
add an abstract method to
Expression
and implement it in its children.so each class will have its own checks.