Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces vs Public Class Members

I've noticed that some programmers like to make interfaces for just about all their classes. I like interfaces for certain things (such as checking if an object supports a certain behavior and then having an interface for that behavior) but overuse of interfaces can sometimes bloat the code. When I declare methods or properties as public I'd expect people to just use my concrete classes and I don't really understand the need to create interfaces on top of that.

I'd like to hear your take on interfaces. When do you use them and for what purposes?

Thank you.

like image 884
Shai UI Avatar asked Aug 11 '26 08:08

Shai UI


1 Answers

Applying any kind of design pattern or idea without thinking, just because somebody told you it's good practice, is a bad idea.

That ofcourse includes creating a separate interface for each and every class you create. You should at least be able to give a good reason for every design decision, and "because Joe says it's good practice" is not a good enough reason.

Interfaces are good for decoupling the interface of some unit of code from its implementation. A reason to create an interface is because you foresee that there might be multiple implementations of it in the future. It can also help with unit testing; you can make a mock implementation of the services that the unit you want to test depends on, and plug the mock implementations in instead of "the real thing" for testing.

like image 105
Jesper Avatar answered Aug 14 '26 10:08

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!