I am trying to teach myself programming, but I have always been very confused by the object oriented approach.
Recently, I have been reading about SOLID development principles.
When I create Classes, using Python, it seems I add the application logic there. However, this appears to defy the single responsibility principle, and injection principles.
For a simple example of my problem, let's assume that my ultimate goal is to change the TV to channel 10, turn the connected (but separate) surround sound system to max, and then turn the TV off.
I would do something like this:
from SpeakerSystem import DolbyDigital Class Tv(object): def __init__(self): self.speakers = DolbyDigital() self.volume = 10 self.channel = 1 self.power = 'Off' def turnOn(self): self.power = 'On' def turnOff(self): self.power = 'Off' def channelUp(self): self.channel += 1 def channelDown(self): self.channel -= 1 def volumeUp(self): self.speakers.volumeUp() def volumeDown(self): self.speakers.volumeDown() def setChannel(self, station): self.channel = station def process(self): self.channel = 10 while self.volume != self.max_volume: self.volumeUp() self.turnOff()
Ignore for a minute that this is a contrived example!
Then, to solve my problem i will simply instantiate
Tv, and run
The problem is that I always create many methods like process() here; I essentially bake in my application code in with the class.
I think this is wrong? The vast majority of methods in my class actually go about solving my problem directly; they clearly will not be useful to anyone, or even myself, outside of my specific problem domain.
In the example,
process is not useful to anyone (only useful for my niche problem). Imagine 10 more methods like that, which are totally useless.
Also, I have read that baking in
self.speakers = DolbyDigital() is also bad design, because now
Tv depends on it. And this gets messy when unit-testing; having to constantly mock out other objects. Many books suggest that objects should not even be responsible for initializing other objects....
The more I read about OOP and OODesign, it seems the class itself should be general, it should provide only the basic methods (it shouldn't actually do the whole job), and that the application code should somehow be separate. Is this true? If so, where should the application code go?
I thought about creating a plain old
main() file, however it seems that if I did that, the programming paradigm then shifts to procedural. And the whole point of learning OOP is to stick with OOP!?
I am truly utterly confused about it. Again, sorry for the seemingly dumb question, but I have no formal training, so just trying to improve with your help!
I have read several object oriented books, including those by Gamma et. al, Uncle Bob, and several other seminal books. It seems my question is so stupid/novice that they do not actually cover it.