Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any point to an interface if only one class implements it?

Looking at the (mature) codebase at my new job, there is an interface, and only one class implements it (as far as I can tell). Can/should I get rid of the interface?

like image 558
user343587 Avatar asked May 18 '10 01:05

user343587


People also ask

Should every class implement an interface?

In most cases, a final class is the best thing you can create. If a user doesn't like your class, they can simply choose not to use it. However, if you're building up a hierarchy of objects you should introduce an interface for every class.

Can a class implement only one interface?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Can we use interface without implementing it?

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces. A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.

What do you call an interface that should have only one method in it?

The interfaces with only one method are called Single Abstract Method(SAM) Interfaces.


2 Answers

No way! Its has zero harmful effects and one day somebody can swap an implementation without having to refactor tons of code.

like image 112
John Farrell Avatar answered Feb 10 '23 12:02

John Farrell


In addition to the good answers already provided - if at some point in the future that one class needs to be mocked for testing purposes, it's a lot easier to do so when there's already an interface available!

like image 23
John Rasch Avatar answered Feb 10 '23 11:02

John Rasch