mercredi 16 septembre 2020

When creating instances of one class reading from instances of another class, where should this logic be put?

Let's say I'm working with two graph models, MyNode and MyPath (grossly oversimplified)

class MyNode {
  id: number,
}
class MyPath {
  path: string,
}

To create a MyPath object, I have two options: either I create a path that only includes a MyNode, or I create a path connecting two other MyNodes:

function createRootMyPath(rootMyNode) {
  return new MyPath({ path: rootMyNode.id })
}
function createConnectionMyPath(myNode1, myNode2) {
  return new MyPath({ path: myNode1.id + '.' + myNode2.id  })
}

While MyNode and MyPath instances form a graph and have a very close relationship, they can also be used standalone as their own models.

When writing these two MyPath creation methods, where should I put them?

Do they belong in the MyPath class, despite having a strong dependency from the MyNode class? Should I move these two methods to a factory class? Or should I do something different altogether?

Aucun commentaire:

Enregistrer un commentaire