I'm building a complex tree of objects. There are a total of five types, A
, B
, C
, D
, and E
. There is a single instance of A
, which is the root node. A
has one or more B
s as children, each B
has one or more C
s as children, and so on. The original data format is a stream that consists of 5 numbers (numerical IDs for A
, B
, C
, D
, and E
) plus metadata that may be associated with each one.
I'm attempting to add some level of filtering to my tree. My current approach is to take the input and pass it into the constructor for A
and then flow it down to the B
s that A
construct and the C
s that B
construct and so on. However, the filtering ultimately happens at the level of E
. If all of the E
s for a given D
don't exist, I don't want to create that D
. If C
doesn't have any D
s, I don't want that C
to exist.
My initial thought is to throw an exception, but that seems like using exceptions for flow control. Although some languages favor exceptions, I'm currently working in Java, where the tendency is for exceptions to be for exceptional conditions. I don't think that not matching a filter is an exceptional case.
What are my options for ensuring that my final tree only contains nodes with children and the filter is applied?