jeudi 12 mai 2016

Adapted Visitor Pattern with two return values in Java

I want to get a pretty print of a tree path along with a path containing the id's of each node. So basically I want to implement a visitor that creates two results.

I have created the following code variants:

Variant 1

class Visitor {
  private String displayPath;
  private String idPath;

  Visitor(Root root) {
    visit(root);
  }

  private void visit(Root root) {
    // traverse Tree and set displayPath and idPath
  }

  //getters for displayPath and idPath
}

Variant 2

class Visitor {
  private String displayPath;
  private String idPath;

  public void visit(Root root) {
    // traverse Tree and set displayPath and idPath
  }

  //getters for displayPath and idPath
}

Variant 3

class Visitor {
  public PathPair visit(Root root) {
    // traverse Tree and create a PathPair to return
  }
}

class PathPair {
  private String displayPath;
  private String idPath;

  PathPair(String displayPath, String idPath) {
    this.displayPath = displayPath, this.idPath = idPath;
  }

  //getters for PathPair
}

I've thought about the variants: 1. Ensures that the getters are only called after the visit is done, but it creates a lot of Objects and is somewhat unintuitive for the user (why would Instance creation already visit the root?).

  1. Someone could call the getters on the result of another root visit. This seems like a dangerous option.

  2. Seems the most clear and avoids errors in my opinion.

I would just like to know if I've overlooked a potential 4th option and whether my thoughts about the 3 variants are correct. Thank you.

Aucun commentaire:

Enregistrer un commentaire