mardi 15 octobre 2019

Best practices when having a "Root Class type" and a "NonRoot class type"?

I have tree structures where the nodes are mostly the same but there are small differences between "root" instances and "nonRoot" instances.

For example, imagine I have a method decide(), and the behavior for nonRoot nodes is to delegate to their parent, and then the root node needs to actually implement something.

It seems there are a few ways I can structure my code, such as the following 2:

CommonParent:

AbstractNode
 decide()
  this.getParent().decide()
NonRootAbstractNode extends AbstractNode
RootAbstractNode extends AbstractNode
 decide()
  looksGood ? yes : no

If statements:

Node
 decide()
  noParent?
   return looksGood ? yes : no
  return this.parent.decide()

The latter I don't like because of the additional complexity (methods should do 1 thing). The former becomes tricky with multiple inheritance.

Anyone know what the industry has found to work best in the long run?

Aucun commentaire:

Enregistrer un commentaire