Sunday, October 2, 2016

Pillars of OOP

Pillars of OOP

Object-oriented programming is a programming paradigm of focusing code towards the construction and treatment of objects, or instances of classes. This mechanic is illustrated through features (pillars) which is important to understand and implement in order to minimize bugs, reduce complexity and create quality code!

Encapsulation:
Separate concerns. The waiter shouldn't care how the chef is making food, just that he makes it and the same holds that the chef shouldn't care how the waiter is delivering food, just that he's doing it. The implementation of a procedure should not be shared with other blocks of your code - they should remain separate and should interact minimally.

  • Prevents unintended consequences of changing code in one place.
  • Loosely coupled code for maintainability.
  • Examples: 
    • Access Modifiers (Public, Private, Protected, Internal, Protected Internal)
    • Accessors (get; set;)
Inheritance:
Code re-usability. You shouldn't have to redefine an entire set of properties and methods for classes that are similar - instead, you should structure the code so that classes inherit from other classes in order to reduce the amount of code written. Classes that have a similar relationship, either through properties or behavior, should have an explicitly defined relationship that allows one to 'inherit' from the other. Based on a "Is a" relationship.

  • Reduces code count
  • Improves structure and organization, leading to improved readability.
  • Examples:
    • The ":" operator extends a derived class (left) from a base class (right)
    • "is" and "as" keywords for casting (also upcasting and downcasting)

Polymorphism
Extract and distribute commonalities. The term derives from the ability to use the same name for what may be different actions on objects of different types. Humans can walk and so can dogs. We can abstract this commonality out from both, make a class called Walkability and extend it to classes that can walk. This explicit relationship means that humans and dogs can walk because they extend Walkability. This is typically done through interfaces or virtual methods - they act as a contract guaranteeing a specific function. The way that humans walk is different from dogs, but they still walk - same thing is applied here: while the implementation is different, we still guarantee that humans can "walk" and dogs can "walk". Based on a "has a" relationship.

  • Loosely coupled code for maintainability.
  • Flexibility to change commonalities among separate types
  • Reduce code count
For some, there is a fourth pillar (data abstraction), but I've decided to make a separate blog post on that so that I can explain why some include it and some don't, while also covering what it is.

Summary: Understand your pillars so that you can take full advantage of OOP to write better code.

No comments:

Post a Comment