DIP - The Dependency Inversion Principle

The Dependency Inversion Principle is a part of SOLID, a mnemonic acronym which bundles a total of 5 design principles.

It is often associated with clean code.

But what exactly is it, is it important to you, should you even care?

🧵👇
1⃣ What does it state?

It states:

Modules that encapsulate high-level policy should not depend upon modules that implement details. Rather, both kinds of modules should depend upon abstractions.

This may sound a little complicated, but you can break it up, as follows:
1. High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g., interfaces).

2. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
Still not better?

Okay, view it this way:

Don't let anything you build depend on a concrete implementation of something.

Better depend on an abstract description of a contract, and let any implementor decide how to satisfy that contract.

👇
2⃣ An Example

Take a look at the following example (which is in TypeScript):

What you see here is one way of structuring a backend API.

A resource layer that implements the specific of the API, a service which contains the business logic, and repositories which handle ... class PositionRepository {   constructor() {} }  class Trans
... the persistence layer (e.g. database interactions).

And if you take a closer look, you can see that the high level class (resource) depends on a concrete lower level class (service) which itself depends on two (more) lower level classes (repositories).
The control flow thus goes from left to right, from the highest to the lowest level.

It is like a Singly Linked List, every higher-level module references at least one lower-level module.

👇
3⃣ What does it try to prevent?

Whenever you couple a module (a class, a function, a whole module) to another module, that first module depends on a lot of lower-level detail.

In object-oriented systems this also means that you can only replace the logic you depend on ...
... by deriving from exactly this class and overwriting existing logic.

This is a pretty tight coupling, and a lot of inflexibility.

It becomes pretty difficult to replace lower-level logic, and changes to the lower-level logic might have a larger impact on higher-level one.
Just imagine you'd now restructure the TransactionService from the example.

You couldn't tell, without taking an explicit look at the TransactionResource, that you maybe now have to also make adjustments there.

Another issue is the direct dependency on the lower-level module!
If you apply this example to a library, and class A depends on class B, and both originate from different modules, a user would always have a dependency on module A and module B (transitive).

A user couldn't even choose to not take B, because the direct relationship exists!

👇
4⃣ Fixing the issues

You can inverse the control flow by letting each concrete implementation either depend on an interface or implement said interface. interface PositionRepository {}   interface TransactionRepos
Instead of the control flow going from the highest to the lowest level modules, there is now an abstraction in-between them!

And before you shout it out loud, yes, this adds more code overall, as each interface also needs to be described first.
But do you remember the issue with module dependencies?

Instead of module A now requiring also module B, module B now requires module A (given module A defines the interface), and this gives users the choice whether they want to pull in B, as well, or want module C...
...as an alternative to provide another implementation of the interface, which might be a better option for their use case!

👇
5⃣ Should you care?

Well, it depends!

In dynamically typed languages like JavaScript, you already depend on interfaces pretty much everywhere, as you can simply call any method or property on any object.

As long as a user provides everything you require, you're good to go!
But as soon as static typing comes into play, you should indeed care.

You gain all benefits described within this thread, and it'll improve your code quality, usability, and maintainability a lot.

The benefits weigh pretty heavy, and should not be ignored!

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Oliver Jumpertz

Oliver Jumpertz Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @oliverjumpertz

22 Nov
Although I am not a data scientist by any means, I was recently asked what knowledge of math someone would need to be able to efficiently get into the field.

Well, I researched a little and came up with the following course track, starting with the basics.

🧵👇
Calculus 1 will cover a lot of the basics, relevant especially to optimization problems which are quite common in data science.

khanacademy.org/math/calculus-1
Calculus 2 will go even deeper and cover topics such as integration techniques and differential equations.

Especially integrals are pretty important for probability distributions and hypothesis testing!

khanacademy.org/math/calculus-2
Read 7 tweets
20 Nov
ISP - The Interface Segregation Principle

The Interface Segregation Principle is part of SOLID, a mnemonic acronym which bundles a total of 5 design principles.

It is often associated with clean code.

But what exactly is it, is it important to you, should you even care?

🧵👇
1⃣ What does it state?

The ISP sets a pretty simple statement:

"No client should be forced to depend on methods it does not use."

ISP applied to the extreme will result in single method interfaces, also called role interfaces.
You can take a look at the following example to get an idea of how the ISP can be violated in one way (this time it's in TypeScript): interface ReportService {  ...
Read 14 tweets
14 Nov
Clean code is important, clean code helps others understand your code, but clean code is also pretty subjective!

I want to give you my perspective on it, drawing from years of experience leading teams of developers as a tech lead and working in teams.

🧵
1️⃣ Clean code is important

Clean code helps people understand code.

The more your code is structured according to the opinion of the majority of developers, the more likely it is that other developers will understand your code!
A few principles of clean code are:

- Use meaningful and understandable identifiers
- Use functions and keep them as short as possible
- You don’t need comments most of the time when your code is human readable
- Don’t repeat yourself (DRY)
- Keep it Simple, Stupid! (KISS)
Read 18 tweets
27 Oct
Have you ever had to process events?

If you have, have you ever thought about if the order of events really matters?

There is a huge difference in complexity whether the order of events processed matters or not.
Imagine the following task/problem:

You want to analyze application logs, because you're curious how an API that starts a long running background process behaves performance-wise.

One log message signals the start, a few intermediate ones, and one message that signals the end.
1⃣
If you can somehow ensure that every log message you process comes in order, the problem is manageable.

When you get your end message, you know that you already processed the start message.

You could now, for example, just subtract the end time from the start time.
Read 8 tweets
14 Aug
Interviewing for a new position is never easy.

Algorithms & Data Structures are usually a pain for candidates, but so can System Design be.

Let me give you 7 steps that will help you to improve your experience in system design interviews.

🧵👇
1) Clarify The Requirements

Ask questions, and a lot of them!

Try to find out what exactly the interviewer expects from you.

Try to narrow it down as far as possible to the exact scope of the problem.

Even if the question is to (re)design an existing system, ask!
2) Define System Interfaces

Define all APIs that the system to design will need.

Explain what each API is for as detailed as possible, so the interviewer can jump in and tell you if you got a requirement wrong.

If you got something wrong, no problem, adjust accordingly.
Read 8 tweets
13 Aug
Improving developer experience is always a good investment.

It's even one of the investments with the highest return, in my opinion!

Some things that help to improve DX:

🧵👇
1) Providing All Relevant Information Up Front

Ensure that all information necessary is present in a README.md within the project's repository.

It should be sufficient enough to state what the project does, what problems it tries to solve, etc.
2) Making Sure Starting Out Is Easy

Does the project require some setup to be able to run/test/develop locally? -> Write an interactive script which sets everything up, maybe creating a config file / .env with meaningful defaults or settings from script input.
Read 8 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!