Object oriented programming (OOP) best practices
In object-oriented programming, we have quite a lot of best practices to apply when writing code. We should make good use of SOLID principles, and object-oriented (OO) design patterns.
The following best practices can be applied on top of SOLID principles, and object-oriented (OO) design patterns.
- Extending Is Better Than Changing
- Avoiding Global State and Non-Deterministic Behaviors
- Avoid Static Classes for Helpers, Utilities, etc
- Separate Creational Logic from Business Logic
- Keep Complexity Level Low
- Keep the method small
- Avoid Too Many If or Switch Statements
The SOLID principles:
- Single Responsibility Principal
- Open/closed principle
- Liskov substitution principle
- Interface segregation principle
- Dependency inversion principle
Other OOP rules:
- “Hollywood principle” which means lower layers should not depend on higher layers.
- “Favor composition over inheritance” – composition allows changing/adding behavior at runtime and is more maintainable
- “Program to an interface, not to the implementation” – always use abstraction as a way of referencing instead of direct coupling to the concrete class