R
R
Rodgenk2013-12-23 17:23:50
Java
Rodgenk, 2013-12-23 17:23:50

Should I use instanceof if there are several different objects in the JTree?

There are several different types of objects in my JTree tree (6 pieces).
Different objects require completely different methods to work.
Each class has about a dozen of its fields.

<code lang="java">
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getModel().getChild(currentNode, i);
    Object ob = node.getUserObject();
    if(ob instanceof DescriptionTemplate) {
        // todo...
    }
</code>

How justified is the use of the instanceof operator in this case?
When using instanceof, a large number of branches are generated.

Can this problem be solved in another way?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
OnYourLips, 2013-12-23
@OnYourLips

How justified is the use of the instanceof operator in this case?
This is mistake.
https://ru.wikipedia.org/wiki/%D0%9F%D1%80%D0%B8%D...

P
paralainer, 2013-12-27
@paralainer

Do not forget about the possibility of using strategies.
Very approximate code, but the essence is clear:

private static final Map<Class, Action> strategies = new HashMap<>();
    
    private static interface Action {
         void doAction(Params params);
    }
    
    static {
        strategies.put(ANodeType.class, new Action() {
            public void doAction(Params params){
                 ...
            } 
        });

        strategies.put(BNodeType.class, new Action() {
            public void doAction(Params params){
                 ...
            } 
        });
    }
    
    ...
    
    public void handleTreeNode(Object node, Params params){
       strategies.get(node.getClass()).doAction(params);
    }

In general, there is an option to implement the Action interface with all types of nodes (renaming it, for example, to JTreeNode) and it will look something like this:
public void handleTreeNode(JTreeNode node, Params params){
       node.doAction(params);
    }

But here you need to look at whether it is possible to change the code of the classes that are stored in the tree and how it will be architecturally correct. (Whether they are special objects for the tree or general objects of the system)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question