20. Clean Code & Best Practices
What are DRY and KISS?
JuniorAnswer:
- DRY: Don't Repeat Yourself.
- KISS: Keep It Simple, Stupid.
What is YAGNI?
JuniorAnswer: You Ain't Gonna Need It. Don't implement features until they are actually needed.
What is Composition over Inheritance?
MiddleAnswer: A principle that suggests achieving polymorphic behavior and code reuse by composing objects with other objects that implement the desired functionality, rather than inheriting from a base or parent class.
Imagine, that you have an old class in monolith, this class has many methods and is needing change, how would you refactor?
SeniorAnswer:
- Understand & Test: Write tests for the existing functionality to ensure no regressions are introduced during refactoring.
- Identify Responsibilities: Identify the core responsibilities of the class and extract them into smaller, single-purpose classes (SRP).
- Decouple: Use Dependency Injection to decouple the class from its dependencies, making it more testable.
- Incremental Refactoring: Refactor in small, incremental steps, running tests after each change.
- Apply Design Patterns: Use patterns like Strategy, Factory, or Service objects to handle complex logic or multiple conditional paths. Detailed Design Patterns Guide
What is the Law of Demeter?
SeniorAnswer: A design guideline that says a module should not know about the innards of the objects it manipulates. "Don't talk to strangers."