Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does any kind of abstraction use interfaces instead of abstract classes?

Heyho,

There´s a question in my mind for some time now, which hopefully can be cleared quickly by some of you:

I am a big fan of MVC, ASP.Net Mvc in my case.

What I have noticed is the hype about interfaces. Every video, tutorial and book seems to solve any kind of abstraction with interfaces. I have adapted these patterns, understood why and how and I am basically very happy with it.

But I just don´t get why interfaces are used everywhere. I´ve almost never seen some abstraction being done with abstract base classes, which I don´t understand. Maybe I miss something? I know that you can only inherit from one base class while multiple interfaces are possible. But interfaces do have disadvantages, especially when some changes need to be done, which breaks your implementations. In my projects so far, I only used to pick interfaces for completely different classes.

For example, the whole repository pattern could be done with an abstract base class, still providing testability and exchangeability, or did I miss something?

Please point me to the part where my brain laggs :)

like image 791
Steffen Avatar asked Dec 03 '22 13:12

Steffen


2 Answers

Interfaces are used in tutorials, blogs and elsewhere because those authors are particularly influenced by a group of methodology called "design for testability".

Primarily, design for testability school of thoughts used interface every way because they want to be able to mock any component under tests. If you use concrete class, then a lot of mocking tools can't mock those class, and hence will make it difficult to test your code.

like image 82
Graviton Avatar answered Dec 28 '22 08:12

Graviton


A Story

I once attended a Java user group meeting where James Gosling (Java's inventor) was the featured speaker. During the memorable Q&A session, someone asked him: "If you could do Java over again, what would you change?" "I'd leave out classes," he replied. After the laughter died down, he explained that the real problem wasn't classes per se, but rather implementation inheritance (the extends relationship). Interface inheritance (the implements relationship) is preferable. You should avoid implementation inheritance whenever possible.

While using only or mostly Interfaces does have code reuse problems(as well as eliminating nice base classes), It makes it a lot easier to do Multiple Inheritance like things. As well as having widely different implementations that will work and where you don't have to worry about the base class changing or even what it does(you do have to implement the whole thing though so its a trade off).

P.S. I think the new Go language is based on interfaces rather then inheritance(looks sort of interesting).

like image 41
Roman A. Taycher Avatar answered Dec 28 '22 06:12

Roman A. Taycher