Pitfalls of composition where component is also a component of a sibling component?

  softwareengineering

I’m relatively new to structuring code in a composition style, and I have a situation where a component is also a component of a sibling component. I’m trying to figure out if there are likely to be unexpected issues with this.

Explaining the relation in more detail, I have a composite C that has components A and B. However, A is also a component of B. That is, B is also a composite, and also uses A as a component, even though B is also a component of C. Notably, B may potentially be replaced by a version of that does not always require A or will have two separate instances of A, so I don’t want C to use B‘s A, and it should have it’s own reference to A. But most often, C and B will need to refer to the same A.

As the concrete case, I’m building a machine learning framework for others to use. I’m attempting to build file-based dataset classes. There will be both a training and an infer dataset class. They both need access to a component that will take care of managing paths to the data files. The infer dataset needs to also have the ability to load the input data from the file paths. The training dataset will have the infer dataset as a component (so it can load the input data in the same way). The training dataset also needs to know how to load the labels from the file paths (not all infer datasets will have labels, which is why this is separate). So, most often, the training and infer dataset will need to share the same path management component. However, there are cases when the two datasets may have separate path management components, or one might be an alternative version of the class that does not have a path management (synthetic data generated on-the-fly, label and input data residing in different files, etc).

2

C uses A and B
B uses A

This is not that strange. Or really that important. What is important is understanding what B and C need from A.

It’s worth thinking about the dry principle for a moment. It teaches us not to worry about duplicated code as much as duplicated ideas.

B and C each have needs. For the moment, A meets those needs. But B and C are different things. It’s worth considering I, the interface between them and A.

The job of I shouldn’t be to allow everything A can do. It should be to express what B and C need. But only if they need exactly the same things. If they need different things, they need to express them through different interfaces. Even if those interfaces hold exactly the same code. Dry up ideas. Not code.

Give the users that kind of respect and this dependency knot should be easier to manage.

3

LEAVE A COMMENT