Hasty Briefsbeta

Bilingual

OOP Principles That Will Take You Far

6 hours ago
  • #OOP Principles
  • #SOLID
  • #Software Design
  • The author shares a personal experience where a small code change, adding a discount code field, ended up affecting 17 files due to poor design, emphasizing the importance of practical design principles.
  • SOLID principles are explained stripped of complexity: Single Responsibility (one reason to change per class), Open/Closed (extend via new classes, not modifications), Liskov Substitution (subtypes must work as parents), Interface Segregation (many small interfaces), and Dependency Inversion (depend on abstractions).
  • Program to an interface, not an implementation, allows flexibility by depending on method names or interfaces, enabling easy swaps and test doubles without extra cost.
  • Tell, don't ask encourages moving logic into objects (e.g., calling account.withdraw(amount) instead of externally checking balance), reducing scattered logic and adhering to the Law of Demeter to avoid long chain calls.
  • DRY (Don't Repeat Yourself) is about avoiding conceptual duplication, not just textual; refactor on the third occurrence, and keep separate functions if they encode different ideas.
  • YAGNI (You Aren't Gonna Need It) advises against premature generalization; ship simple versions and refactor when real patterns emerge from multiple cases.
  • Tests are crucial for good design, as testable code aligns with design principles; writing tests first reveals friction, and TDD punishes bad design early, improving code quality.
  • Examples in Ruby and PHP illustrate applying principles: Ruby uses duck typing and implicit interfaces via message-passing, while PHP uses explicit interfaces and type hints, both achieving similar design goals.
  • The difference between message-passing (Ruby) and class-based (PHP/Java) OOP is noted, but principles like SOLID and DRY apply across languages, with local idioms adapting the intent.
  • Actionable advice includes picking one principle to try weekly, such as refactoring dependencies, replacing if chains with polymorphism, or deleting unused abstractions, to internalize design through practice.