Hi I have a model that contain several items, now all of the items have a set of shared properties: id, name, parent. In addition some of this items are meant only to contain other items. Some are meant to connect to other items and so on. While trying to implement this I can think of doing inheritance but I can also think about doing composition (and have read a lot of comments saying to prefer this). So I can define a class with the basic properties whose main job is just to provide access and allow modification of them:
from attrs import define, Factory
@define
class BaseProperties:
identifier: str
name: str
parent_id: Optional[str]
@define
class ConnectorItem:
base_properties: BaseProperties
connections: "List[ConnectorItems]" = Factory(list)
@define
class ContainerItem:
base_properties: BaseProperties
children: "List[Union[ConnectorItem, ContainerItem]]" = Factory(list)
now the thing is that when I want to access to the name or id of a Container item for example, I would need to do:
container_item.base_properties.identifier
or define a property inside the ContainerItem.
@property
def identifier(self):
return self.base_properties.identifier
if i want to just use:
container_item.identifier
Now the first option feels like the user need to know about the internal implementation of my ContainerItem class and can lead to a lot of dot notation to access some of the members when the project grows.
The second option feels cumbersome when I would need to basically copy paste a bunch of setter and getter properties in each of the classes that contain the BaseProperties class.
Should I go with inheritance in this case instead of composition? The thing is that even if ContainerItem and ConnectorItem share the basic properties I wont be using them in the same context ever so i don't need polymorphism in this case just basic code re-usability i think.
What is a better way of implementing this case, knowing that this is a simplified version, in reality ConnectorItem might be composed from different classes to get different ConnectorItemTypes for example.
ContainerItem
a subclass ofBaseProperties
.