Object-oriented – Another “Why use Abstract/Interface” question. But I’m a solo developer. Why use it

abstract classinterfacesobject-oriented

I know the purpose of it and everything. I see myself as a solo developer for a couple more years.

I always see answers that it is contract. Yes I get it.

But here's something on my mind:

If a class did not provide what an Interface wants, it'll throw an error.

Well, if a class really needs that method, it'll throw an error still if there's something that calls it and it's not there right?

What's the difference?

I can just actually implement it and go along with the "norms" but that will leave me hanging with the question "why". I don't like blindly following something without understanding it.

EDIT:

I tried searching for answers about this question many times before and what I always find is something like "So when someone else…". Haven't tried working with someone else before and I am not sure if that really is the reason on why use an Interface.

I mean, because I do everything my own so I do know what something in my code needs right? And again, even if I forget to implement a method, I will still see an error that says a method is not defined.

EDIT 2:

The Dependency Injection is a very good answer. Implementing Interfaces on those helps in case you need to swap out dependency implementations. You are somehow confident that what you need is provided.

It is a little more clear to me now that it is a Contract between components (maybe between developers too)

Best Answer

I always see answers that it is contract. Yes I get it.

I can just actually implement it and go along with the "norms" but that will leave me hanging with the question "why".

If you're asking why, you maybe don't really get it.

Using interfaces is a decoupling technique. They allow some portion of your code to be ignorant of the implementation details of another portion of your code. This allows you to change those implementation details secure in the knowledge that the other parts of your code are not impacted.

That reduces the cognitive load when making the changes. That reduces the testing effort necessary to make sure that things work properly after the changes. And they make things a lot easier when you need multiple implementations to coexist at the same time.

But sometimes you don't need those benefits, so interfaces are just overhead then. The best way to really learn this sort of impact is to write code. Write some with interfaces. Write some without. See how the design shifts with each. See how changes to the program impact it differently depending on the design.

Related Topic