I’m very amateur when it comes to OOP, self taught using python.
My main concern is that of breaking concepts or entities into objects.
For instance, I have just written some code that controls a traffic light system attached to my raspberry pi.
The system contains:
- A car set off traffic lights (red, yellow, green).
- A button to request a crossing.
- And a green and red light to tell pedestrians when to cross
Now i ended up modelling my code as one entire class. Where methods inside the object call other methods in the object. E.g. when the object is initialized, the initialize method calls a “wait for button press” method, when the button press is detected that method then calls a “run through light sequence” method.
Is this bad practice? Should each concept/entity be a separate class/object, e.g. traffic light object, button object, pedestrian light object?
Sorry for the openness of the question.
Thanks for your help.
What you currently have violates the Single Responsibility Principle. Basically you class is doing too much.
What you can do is something like the following:
Have separate classes for car trafficlights, pedestrian traffic lights and the button to request to start crossing.
After that you can inject the button class into the pedestrian light class. And inject both the car as well as the pedestrian class into the “control” / “manage” class where the classes are used to manage the lights.
You could even abstract it even further after this by for example injecting the actual lights into the trafficlights classes.
You may also want to read about the other SOLID principles.