❓ Have you ever wondered what interfaces are for in object-oriented languages?

They are more than a just a class with abstract methods.

They play a key role in many design patterns and principles.

A thread 🧵 about 6 key aspects of interfaces.
1⃣ Interfaces establish knowledge boundaries.

When you call an interface method, you can often ignore what is under the hood.

Example: class 'C' need not know the exact database that stores the data.

🔑 Interfaces reduce complexity because they allow us to separate concerns.
2⃣ Interfaces establish architectural boundaries.

The separation in the previous example is also "physical".

You can change the 'Database' module without affecting the 'C' module.

🔑 Interfaces allow us to design systems that are loosely coupled and therefore more testable.
3⃣ Interfaces define a communication protocol.

The buttons of your calculator are its interface.

When you push '+', you send the 'sum' message.

Same with objects.

When A calls a method on B, A sends a message to B.

🔑 Interfaces define the messages objects understand.
4⃣ Interfaces establish a contract.

They set:

🔹Expectations

If you call "setSide" on a square, you expect all 4 sides to change.

🔹Obligations

If you implement "setSide", you must change 4 sides or you'll break the contract.

✏️ Have a look at: Liskov Substitution Principle
5⃣ Interfaces make polymorphism possible.

You can write a function that uses "Shape" and it will work for "Square" and "Circle".

If you ever need "Triangle", you don't have to modify the function.

This is how you write abstract code.

✏️ Have a look at: Open-Closed Principle.
6⃣ Interfaces allow you to manage dependencies.

Control flow can go from class 'C' to class 'Database Access' without the former depending on the latter.

Control flow dependencies need not mirror source code dependencies.

✏️ Have a look at: Dependency Inversion Principle.
In summary:

✨ Interfaces are a key part of object-oriented languages ✨

They allow you to create well-designed systems that:

✅ Keep complexity under control.
✅ Separate concerns.
✅ Are modular, loosely coupled, and testable.
✅ Are easy to change.

This is power ⚡️
To end the thread, a disclaimer:

I've written this thread with statically typed languages in mind.

In dynamically typed languages, interfaces are usually an implicit concept, so some of the ideas apply and others don't.

Maybe, I can prepare a thread about this one day 🤔
You can follow @macerub.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: