S - Single Responsibility
A class should only have one reason to change eg reporter class not doing formatting and auth and not tied to db
O - Open/Closed
Entities should be open for extension but closed for modification
- to avoid code rot - not touch original source
Uncle Bob says: Separate extensible behavior behind an interface, and flip the dependencies
Example: calculating area of shapes with if, elseif
Should be:
-
A shape has an interface. ``` class Square implements Shape {
public function area() { return $this->width * $this->height; }
}
* Don't need to modify source.
* Code to an interface.
Polymorphism - different behaviour while sharing common interface.
## L - Liskov Substitution
Derived subclasses must be substitutable for their base class
function all(){ return []; }
#vs
function all(){ return collect(); }
```
Return values different so cannot be substituted.
If checking type then alarm bells should ring.
- Signature must match.
- Preconditions can’t be greater.
- Post conditions at least equal to.
- Exception types must match.
I - Interface Segregation
A client should not be forced to implement an interface that it doesn’t use.
E.g. AndroidWorker forced to implement sleep() method of WorkerInterface. break into smaller interfaces like Workable and Sleepable behaviours
D - Dependency Inversion
- not injection
- should depend on abstractions
- decoupling code
High level code is not concerned with the details. Low level code is more concerned with details and specifics.
High level code should depend on interfaces not concrete.
House owns electrical socket, tv must conform to socket.
IOC inversion of control
read about this High level code should depend on an abstraction.