OOP Notes - robbiehume/CS-Notes GitHub Wiki

  • OOP is a programming paradigm based on the concept of objects, which contain data (attributes/properties) and actions (functions or methods)
  • OOP allows for easy code reuse and elimination of redundant code
  • It is also easier to maintain, because with abstraction you don't have to worry as much about changes affecting other parts of code that use that objects methods since there are limited parameters passed compared to a procedural language

Tips

Abstraction

  • Sometimes when using a class inside another it's best to use a higher-level class and create child classes, that way you can accept the parent class and if you want to change the child class later on it's a lot easier
    • Ex: you have a Computer class and need a hard drive
      • Instead of using a specified class, use a higher-level HardDrive parent class. This makes it easier if we want to swap the hard drive in the future
         // this is better                                         // this is worse
         class Computer {                                          class Computer {
             HardDrive hd = new SamsungHardDrive();                    SamsungHardDrive shd = new SamsungHardDrive();
         }                                                         }
      

4 Pillars of OOP (APIE)

  • Abstraction: only show the necessary details to the user of the object
    • Only care about calling the method, don't care about the underlying implementation
  • Polymorphism (many forms): allows you to use a method that behaves differently depending on the object
  • Inheritance: build a new class that inherits from a parent class and can add additional features
    • Can also override existing methods
    • Allows for good code reusability
  • Encapsulation: group related variables and functions within an object
    • Allows you to hide data access from the user, and instead use getters and setters

SOLID Design Principles (link)

  • Single-responsibility principle:
    • There should never be more than one reason for a class to change. In other words, every class should have only one responsibility / job
  • Open-closed principle:
    • Objects or entities should be open for extension, but closed for modification
  • Liskov substitution principle:
    • Every subclass or derived class should be substitutable for their base or parent class
  • Interface segregation principle:
    • A client should never be forced to implement an interface that it doesn't use, or clients shouldn't be forced to depend on methods that they don't use
  • Dependency inversion principle:
    • Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, they should depend on abstractions