Home > Mobile >  OOP class design advice. Can a class instantiate and use another class that inherits from the same p
OOP class design advice. Can a class instantiate and use another class that inherits from the same p

Time:10-09

Currently in a situation where I have a series of classes that turn an API request JSON into objects. The objects are modeled after my database schema. I think the part that I'm struggling with is how to represent those entity relationships that are formed with foreign keys in my database.

The following classes are just for an example, the instance variables are much different for my application's schema.

class Table(ABC):
    def __init__(self):
        # stuff
        
    @abstractmethod
    def validateSchema(self):
        """Validates the resources column values."""
        pass


class ClassRoom(Table):
    def __init__(self, id, location_id, location):
        super().__init__()
        self.id = id
        self.location = Location(location_id, location)
        
    def validateSchema(self):
        # stuff

class Location(Table):
    def __init__(self, id, location):
        super().__init__()
        self.id = id
        self.location = location
        
    def validateSchema(self):
        # stuff
        

The part I'm concerned about is when I am creating an object of the same type as the class that has the object as an instance variable.

class ClassRoom(Table):
    def __init__(self, id, location_id, location):
        
        # Can I instantiate this class even if it inherits the same parent?
        self.location = Location(location_id, location)

Is this ok in OOP? Is there a better way to design my classes?

Also, these classes are just defined for the request JSONs that get sent to my API. Their purpose will be to facilitate column validation and a few other purposes. The specific validation I am hoping to implement in these classes comes from this other Stackoverflow post Flask sqlAlchemy validation issue with flask_Marshmallow. I'm not trying to recreate SqlAlchemy here.

CodePudding user response:

Your Table class is analogous to SqlAlchemy's db.Model class. And just as it can have references between different subclasses, so can you.

The specific design of your Classroom.__init__() method seems wrong. All the classrooms in the same location should have references to the same Location object, but you create a new one for each classroom. The Location should be a parameter, rather than the location ID and name.

class ClassRoom(Table):
    def __init__(self, id, location):
        super().__init__()
        self.id = id
        self.location = location

Then you can create multiple classrooms in a location:

loc = Location(loc_id, loc_name)
c1 = Classroom(c1_id, loc)
c2 = Classroom(c2_id, loc)
  • Related