vendredi 17 septembre 2021

Best practice for representing sequential systems (such as optical systems) with arbitrary levels of nesting in object-oriented programming

I have a sequential system S made of elements which can be either other sequential systems of the same type, or fundamental building blocks B.

In practice, for my specific application, let's assume that this can represent an overarching optical element/system S made of an arbitrary nested sequence of optical elements, ultimately made of fundamental optical surfaces (the building blocks B).

I am looking for the best practice (if possible a design pattern) for writing this in object-oriented programming, with the following requirements:

  • Arbitrary levels of nesting are allowed (a system can be made of sub-systems, themselves made of sub-sub-systems.... until reaching the fundamental building blocks).

  • A sequential system S should also be treated as a building block B.

Here is how I solved the problem so far (in Python syntax):

class BuildingBlock(object):
    def __init__(self):
        pass

    def bblock_method1():
        pass
    
    def bblock_method2():
        pass

class SpecificBlock(BuildingBlock):
    def __init__(self, bblock_attribute1):
        super().__init__()
        self.bblock_attribute1 = bblock_attribute1

class SequentialSystem(BuildingBlock):
    def __init__(self, element_list: list[BuildingBlock]):
        super().__init__()
        self.element_list = element_list
    def system_method1():
        pass

So we have:

  • A fundamental BuildingBlock class (which can even be abstract).
  • A specific SpecificBlock class which derives from BuildingBlock.
  • And a SequentialSystem class which also derives from BuildingBlock and contains a list of BuildingBlock instances.

We can then imagine that BuildingBlock defines abstract methods that SpecificBlock and SequentialSystem will implement in different ways (SequentialSystem taking into account the chained sequence that it contains).

Thus, by design, nothing prevents us from feeding a list of instances of children of BuildingBlock (including SequentialSystem instances) to a new overarching SequentialSystem, thereby allowing arbitrary levels of nesting.

My questions:

  • In your opinion, does the solution above follow best practices for such a problem ?

  • Is there a danger of overlooking complicated situations (mixed child types of BuildingBlock within element_list or multiple nesting) when designing unit tests ?

Thank you, and sorry in advance for the verbose description.

Aucun commentaire:

Enregistrer un commentaire