0

I want to implement a scala library for graphs. This library should also contain different types of trees.

1 the class tree extends the class graph

2 the class graph has a method getAllPrecursors(Node n) which returns all the Nodes fron which you can reach n.

3 the class tree has the method getParent(Node n) which returns the parent of the Node n (as an option, None marking the root)

Now, if someone calls the method "getAllPrecursors" for a tree I want to display a warning like " trees have at most 1 precursor, use getParent instead".

Is there any way to do this? Is there any better way of building this library? Should Trees not be a subclass of graph?

user2887596
  • 641
  • 5
  • 15

1 Answers1

2

Firstly, don't worry about performance unless you can prove that the performance of this code is significant to overall performance: "Premature optimisation is the root of all evil"

However you can do what you want by overloading getAllPrecursors and marking it deprecated:

class graph {
  def getAllPrecursors(n: Node): List[Node] = ...
}

class tree extends graph {
  def getParent(n: Node) = ...

  @deprecated("Use getParent rather that getAllPrecursors", "1.0")
  override def getAllPrecursors(n: Node) = List(getParent(n))
}

This will give a deprecation warning if you use getAllPrecursors on a value of type tree but not on a value of type graph (even if that value is actually an instance of tree)

As far as the design goes, it would be better to have getAllPrecursors and getParent as methods on Node (and TreeNode) rather than on the graph itself.

Tim
  • 26,753
  • 2
  • 16
  • 29
  • The question was more design oriented. Performance is fine, but getting a list of precursors seems unnecesary. Wouldn't @deprecated be misleading, since the method is not deprecated but rather unnecesary? – user2887596 Jun 25 '18 at 12:27