OOP Flashcards
Abstraction
When you’re using a function you shouldn’t need to know anything about how it works under the hood.
eg. if I as a user want to switch my tv on, I don’t need to know what exactly it’s doing, I just need to perform the action of switching it on
Inheritance
Inheritance lets one object acquire the properties and methods of another object
Reusability is the main benefit
Animal -> Dog
Animal -> Cat
Polymorphism
“the condition of occurring in several different forms.”
Animal -> Dog
Animal -> Cat
Dog can use methods from Animal directly, or it can override and do its own thing
The real power of polymorphism is sharing behaviours, and allowing custom overrides.
Encapsulation
“the action of enclosing something in or as if in a capsule”
Removing access to parts of your code and making things private
Limit what pieces of your code can be accessed. Make more things inaccessible, if they aren’t needed.
Getters and setters can be added to allow properties to be accessed in a way you can control.
Single responsibility
A class should have one and only one reason to change, meaning that a class should have only one job.
Instead of a vehicle class that has changeOil, getAirPressure I can have an Engine class with changeOil, a tyre class with getAirPressure
Open closed
Objects or entities should be open for extension but closed for modification.
When you split responsibility of a class you should do so in a way that behaviour can be extended/replaced
So if I have a vehicle class that is inherited by car, motorbike, van - I don’t need to implement accelerate in all sub classes, I can implement it at the parent level
Liskov substitution
This means that every subclass or derived class should be substitutable for their base or parent class.
So for example if I had an AutomaticCar that implements a Car interface and overrides a changeGear method to throw an UnsupportedException this would be a violation of the Liskov substitution principle
Interface segregation
More interfaces are better than too little
We can split the responsibility of a class without LSP violation
So maybe we have Vehicle -> Automatic vehicle -> sub class
Vehicle -> Manual vehicle -> sub class
Dependency inversion
Depend on abstraction and not concrete principles