How to Write Better Object Oriented Code — SOLID Principles

Using “Uncle Bob’s” five object oriented design principles to write better code.

Image for post
Image for post
Photo by Clément H on Unsplash
  • O - Open Closed Principle
  • L - Liskov Substitution Principle
  • I - Integration Segregation Principle
  • D - Dependency Inversion Principle

Single Responsibility Principle

Also coined SRP, this principle states “A class should have one and only reason to change, meaning that a class should have only one job”.

Open Closed Principle

Martin defines this as “Object or entities should be open for extension, but closed for modification”.

Liskov Substitution Principle

The definition for this one is a little scary: “Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.”

Interface Segregation Principle

A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.

Dependency Inversion Principle

The last, but not least, states “Entities must depend on abstractions not on concretions. The high level module must not depend on the low level module, but should depend on abstractions”.

interface DBConnectionInterface {
public function connect();
}

Conclusion

SOLID may be a little abstract, but hopefully some of these examples made it clear how you can adhere to and use SOLID to write better code. Code that follows SOLID is more testable, extendable, refactorable, and easier to work with.

Written by

Passionate about building cool shit. First-year undergrad student studying EECS and Business @ UC Berkeley MET Program and software developer at Carline

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store