DEV Community

Cover image for SOLID Principles: They're Rock-Solid for Good Reason!

SOLID Principles: They're Rock-Solid for Good Reason!

Lucas Porfirio on February 02, 2024

Just started with object-oriented programming and feeling a bit lost about SOLID? No worries, in this article, I'll explain it to you and provide e...
Collapse
 
_ndeyefatoudiop profile image
Ndeye Fatou Diop • Edited

Love the article and the illustrations ! The last one is definitely my favourite since it is so much easier to test with that approach !
By the way you can add the language just after the quotes to highlight the code ☺️

Collapse
 
lukeskw profile image
Lucas Porfirio

Learning everyday πŸ˜…. Thanks!

Collapse
 
ruudzaki profile image
Kostiantyn Bilous

Good one! I just comment to Liskov's, that when your variable is a Type or a Collection of Types of the base class, in your caller class you shouldn't care to which objects (base or derived) it references, as their behaviour should be substitutable.

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

Awesome! Love your illustrations - it can be very hard to come up with a good idea to visualise abstract concepts.

Collapse
 
jamimeson profile image
jamimeson

Nice article, thanks for contributing to the community. One recommendation though, please make it more clear who the images belong to. My advice would be to include Ugonna Thelmaβ€˜s name explicitly at the top of the page, rather than at the bottom in a link titled β€œthis article”.

Collapse
 
adam_b profile image
Adam Braimah

Are the images actually licensed for use by Ugonna Thelma? If not, I'd go further and say they should be removed from the article altogether.

Collapse
 
peerreynders profile image
peerreynders • Edited

FYI:

CUPIDβ€”the back story - Dan North & Associates Limited

β€œIf you had to offer some principles for modern software development, which would you choose?” At a recent Extreme Tuesday Club (XTC) virtual meet-up, we were discussing whether the SOLID principles are outdated. A while ago I gave a tongue-in-cheek talk on the topic, so ahead of the meet-up one of the organisers asked what principles I would replace SOLID with since I disagreed with them. I have been thinking about this for some time and I proposed five of my own, which form the acronym CUPID.

favicon dannorth.net

CUPIDβ€”for joyful coding - Dan North & Associates Limited

What started as lighthearted iconoclasm, poking at the bear of SOLID, has developed into something more concrete and tangible. If I do not think the SOLID principles are useful these days, then what would I replace them with? Can any set of principles hold for all software? What do we even mean by principles?

favicon dannorth.net

… i.e. it's important to be just as familiar with the criticisms/limitations while always being mindful of the path of the expert beginner.

β€œBest Practices” are often β€œAdvice; Lacking Context”.

Collapse
 
josefjelinek profile image
Josef Jelinek

I cannot agree more with the above. Presenting something like SOLID without (relatively narrow) context, when it is useful while ignoring many contexts where it can be misleading to less experienced developers, is pretty irresponsible.

Following SOLID is sometimes a solution to your problem, sometimes, it is just introducing additional problems to solve, irrelevant to the solution for the original problem.

Collapse
 
prafulla-codes profile image
Prafulla Raichurkar

This is so good!, learnt a-lot from this :D

Collapse
 
vedangit profile image
Vedangi Thokal • Edited

Superrrr helpful article! Thank you so much

Collapse
 
keyurparalkar profile image
Keyur Paralkar

I loved the explanation so much, that I am going to bookmark this post and implement it. Thanks for this.

Collapse
 
papylataupe profile image
Papy-La-Taupe

That's a great read !

It raises some questions for me tho. I learned that in a dynamic web project in javaEE, we should create a manager calling every Object-related method, like "UserManager" will call UserDAO, who will call UserDAOJdbcImpl who will then implement every user methods, hence the whole CRUD.

But the article explains that i should have a unique manager, dao and daoimpl for each CRUD line.

I get the clarity but wich SOLID model should i chose then ?
And following on that, if the sole purpose of my servlet>manager>dao>daojdbc is to deal only one method, why not direct directly go to servlet>daojdbc ? It May not be pretty but its more logic no ?

Collapse
 
peerreynders profile image
peerreynders • Edited

if the sole purpose of my servlet>manager>dao>daojdbc is to deal only one method, why not direct directly go to servlet>daojdbc?

Congratulations.

You've just re-enacted the birth of Spring, circa 2003.

Expert One-on-One J2EE Design and Development | Wiley

What is this book about? The results of using J2EE in practice are often disappointing: applications are often slow, unduly complex, and take too long to develop. Rod Johnson believes that the problem lies not in J2EE itself, but in that it is often used badly. Many J2EE publications advocate approaches that, while fine in theory, often fail in reality, or deliver no real business value. Expert One-on-One: J2EE Design and Development aims to demystify J2EE development. Using a practical focus, it shows how to use J2EE technologies to reduce, rather than increase, complexity. Rod draws on his experience of designing successful high-volume J2EE applications and salvaging failing projects, as well as intimate knowledge of the J2EE specifications, to offer a real-world, how-to guide on how you too can make J2EE work in practice. It will help you to solve common problems with J2EE and avoid the expensive mistakes often made in J2EE projects. It will guide you through the complexity of the J2EE services and APIs to enable you to build the simplest possible solution, on time and on budget. Rod takes a practical, pragmatic approach, questioning J2EE orthodoxy where it has failed to deliver results in practice and instead suggesting effective, proven approaches. What does this book cover? In this book, you will learn When to use a distributed architecture When and how to use EJB How to develop an efficient data access strategy How to design a clean and maintainable web interface How to design J2EE applications for performance Who is this book for? This book would be of value to most enterprise developers. Although some of the discussion (for example, on performance and scalability) would be most relevant to architects and lead developers, the practical focus would make it useful to anyone with some familiarity with J2EE. Because of the complete design-deployment coverage, a less advanced developer could work through the book along with a more introductory text, and successfully build and understand the sample application. This comprehensive coverage would also be useful to developers in smaller organisations, who might be called upon to fill several normally distinct roles. What is special about this book? Wondering what differentiates this book from others like it in the market? Take a look: It does not just discuss technology, but stress its practical application. The book is driven from the need to solve common tasks, rather than by the elements of J2EE. It discuss risks in J2EE development It takes the reader through the entire design, development and build process of a non-trivial application. This wouldnt be compressed into one or two chapters, like the Java Pet Store, but would be a realistic example comparable to the complexity of applications readers would need to build. At each point in the design, alternative choices would be discussed. This would be important both where theres a real problem with the obvious alternative, and where the obvious alternatives are perhaps equally valid. It emphasizes the use of OO design and design patterns in J2EE, without becoming a theoretical book

favicon wiley.com
Collapse
 
papylataupe profile image
Papy-La-Taupe

Well i didn't touch java Spring yet but that's an interesting exponation, i'll be sûre ro check that, thanks 😊

Thread Thread
 
peerreynders profile image
peerreynders

Well that was over 20 years ago and I haven't been keeping track largely because it was my sense that it was becoming exactly what it was initially trying to avoid.

Collapse
 
simmol profile image
Pavlin Angelov

Not work with Java, but had enough experience in WEB to understand the pattern :)

Since I wrote way too many things and it became a bit dense and there is a big risk of confusing you more than helping, let me try to give you one thing to think about.

Don't design/write by patterns (Solid or the Big Four or any other), refactor into one of them, when you have a specific issue to solve.
Start with the simples solution that would solve your problem and go from there :)

I highly recommend reading refactoring.com/ from Martin Fallower - The original book was written with JAVA examples, and the newer edition uses Javascript (because it does not matter the language).

But the article explains that I should have a unique manager, dao and daoimpl for each CRUD line.

The idea of each layer is for flexibility - Managers decide which DAO (Data access object?! I would guess) to call based on their internal logic, which in turn uses your DAO (internal data representation object) which is persisted using Library specific
object, based on which framework/library for DB you choose to use.

This has nothing to do with SOLID, to be honest - SOLID should (If applicable for solving the problem), be applied on the BUSINESS logic, not the plumbing :)

Half of your chain is just implementation details of how you manage your DB object persistence. And gives you the flexibility to change one part without touching the core business logic.

The only thing in this chain that should be reviewed in the light of SOLID is the Manager (how does the manager make its decisions), everything else is Framework and tech library choices dependent. Not that it can't be done differently, but it's not coming out of the principles in the article themselves.

Some of these things start to make way more sense by just writing more code.
Write your proposed version servlet>daojdbc, then try to make it so servlet can be reused in different contexts and save another object (how would you manage that) ?

With enough changes done to the system and trying to follow the pain (of changing and retesting the same things over and over again) you will probably come to the same conclusion that separating Servlet from Manager from daojdbc objects makes sense :) in some cases.

The truth is these things don't make sense for a simple TODO app that you will never maintain or change ever again. They only matter if your problem is complex enough and a need arises to change it.

So create your servlet -> daojdbc solution if it makes sense for the requirements for your application now. Just be ready to change it once new requirement comes along ;)

Collapse
 
papylataupe profile image
Papy-La-Taupe

Thank you for taking the time writing such a complete answer .

I read it all of course and i think this quote summarize it quite efficiently, and I full agréé :

Don't design/write by patterns (Solid or the Big Four or any other), refactor into one of them, when you have a specific issue to solve.
Start with the simples solution that would solve your problem and go from there :)

Before reading this I was actually trying to explain the DAO/MVC2 process to a fellow classmate, and I ended up telling her "do your jsp, then your servlet, then you jdbcimpl. Then write all your code in it, and when it starts looking downright confusing, only then add your factory, manager, etc etc. By then you will have understood WHY you were doing it."

Collapse
 
mbarzeev profile image
Matti Bar-Zeev

Very nice and well written 🍻

Collapse
 
arcanjo10x profile image
Brendo

Great Article!!

Collapse
 
dscheglov profile image
Dmytro Shchehlov

@lukeskw great article )

I have a suggestion regarding the explanation of the OCP principle. Your example for OCP, which involves shapes, better demonstrates the idea of polymorphism than OCP and includes too many components in the schema, primarily because it is based on Java.

I prefer the explanation of OCP that involves sorting, where we start with hardcoded comparisons and then simply inject a comparison function.

The main idea of OCP is to extend from a narrow problem to a broader one, by extracting "specific details" of an algorithm from its general implementation.

Regarding LSP, TypeScript can catch all the violations you mentioned, except for throwing exceptions (actually, it's controversial whether this violates LSP or not, especially concerning "unexpected" ones). TypeScript handles variance and covariance well.

But LSP is also about a protocols as well. Let's look on the following example:

interface Incrementor {
  inc(value: number): number;
}

class FixedIncrementor implements Incrementor {
  constructor(private readonly delta: number) {}
  inc(value: number): number { return value + this.delta; };
}

class ConfigurableIncrementor implements Incrementor {
  private delta!: number; // we don't yet know this value when the instance is created

  init(delta: number) { this.delta = delta; }
  inc(value: number): number { return value + this.delta; };
}
Enter fullscreen mode Exit fullscreen mode

Both classes are ok with TypeScript, but only the FixedIncrementor follows LSP. The ConfigurableIncrementor doesn't because it expects its methods to be used in a certain order. This issue can't be fixed just by using TypeScript, which shows why it's so important to understand LSP.

Regarding ISP. The issue is not merely with the implementation of a class. The core principle is that an algorithm should depend only on what it uses.

Here's a pertinent example: My friend developed a backend project, using AxiosInstance wherever his services required making HTTP requests. However, he eventually found that he needed to replace Axios with the native fetch API.

To maintain functionality, he had to implement the entire AxiosInstance interface. However, had his services been dependent on something more specific, like Pick<AxiosInstance, "get"> or even better, an interface like IHttpGet { get<R = unknown>(url: string, config?: RequestConfig): Promise<R>; }, he would only have needed to implement the methods actually used in his project.

Nonetheless, it's clear that the AxiosInstance requires all of its methods for full functionality.

So, interface segragation is mostly on the client side.

DIP, perhaps my favorite principle. Your example is functional, but it's not complete. The Database interface should belong to the UserService, not to the classes implementing the interface.

Where "belongs" could mean up to and including avoiding the import of the Database interface and replacing the dependency with a new interface declared in the same module. This new interface should be as narrow as possible according to ISP:

interface IUserDataProvider {
  getUserData(login: string): Promise<UserData>;
}

interface IPswdVerificator {
  compare(plan: string, hash: string): Promise<boolean>;
}

class UserService {
  constructor(
    private readonly db: IUserDataProvider,
    private readonly pswdService: IPswdVerificator
  ) {};
  async authenticate(login: string, password: string): Promise<User | null> {
     const { db, pswdService } = this;
     const user = await db.getUserData(login);
     if (user == null) return null;

     const isPasswordValid = await pswdService.compare(password, user.passwordHash);

     return isPasswordValid ? user : null;
  }
}
Enter fullscreen mode Exit fullscreen mode

After this refactoring, everything must continue to work as expected.
Actually we can export the interfaces IUserDataProvider and then import it in the DataBase class implementations to show the inversion of dependency.

This is crucial for understanding DIP.

Certainly, we should avoid duplicating code. Typically, we declare interfaces separately from the classes that depend on them, as well as from the classes implementing them.

However, DIP implies that we should never depend on interfaces declared in external libraries. At the very least, we should aim in this direction.

Collapse
 
kiani profile image
kiani

A fantastic breakdown of SOLID principles for anyone venturing into object-oriented programming! This insightful article not only introduces the fundamentals of SOLID but also provides concrete examples to demystify its application in code development. The emphasis on the Single Responsibility Principle (SRP) is particularly noteworthy, emphasizing the importance of maintaining concise and focused classes. The discussion around avoiding the notorious "God Class" sheds light on the potential pitfalls many programmers encounter. Kudos to the author for simplifying these crucial principles and highlighting their impact on bug reduction, improved code quality, and enhanced development and maintenance. Additionally, for those diving into video editing programming, understanding SOLID principles is crucial for building efficient, scalable, and maintainable editing software. This resource is a valuable guide for beginners navigating the complex world of object-oriented programming and a solid foundation for building robust, maintainable software.

Collapse
 
epsi profile image
E.R. Nurwijayadi

Respect for the hardwork.

Collapse
 
hectorlaris profile image
HΓ©ctor Serrano

The best explanation of SOLID principles. Tks

Collapse
 
bigboybamo profile image
Olabamiji Oyetubo

Great illustrations and a great article

Collapse
 
uzeyir-yariz profile image
uzeyir-yariz

COOL

Collapse
 
gavindidrichsen profile image
Gavin Didrichsen

Excellent article!

Collapse
 
karanjamadar profile image
Karan

Good one bro!!!

Collapse
 
davidbmx profile image
David

Great post, is very useful

Collapse
 
tbose profile image
Musawenkosi

Great stuff... thank you

Collapse
 
masudalimrancasual profile image
Masud Al Imran

Nice post. Although I could not understand the lil padawan bit.

Collapse
 
dineshashok profile image
dineshashok

Really helpful to delve into OOPS! Thanks

Collapse
 
illantalex profile image
Illya Antonyuk

Thank you for a great explanation! πŸ‘

Collapse
 
ben_calc_i profile image
Ben Sewell

Love this a lot @lukeskw - am I OK to print your illustrations (properly!) for my office wall?

Collapse
 
astronoe profile image
ASTRONOE

The best article on SOLID principles I have seen so far.