Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming against interfaces: Do you write interfaces for all your domain classes?

Tags:

I agree, that programming against interfaces is a good practice. In most cases in Java "interface" in this sense means the language construct interface, so that you write an interface and an implementation class and that you use the interface instead of the implementation class most of the time.

I wonder if this is a good practice for writing domain models as well. So, for example if you've got a domain class Customer and each customer may have a list of Orders, would you generally also write interfaces ICustomer and IOrder. And also would Customer have a list of IOrders instead of Orders? Or would you use interfaces in the domain model, only if it is really driven by the domain, e.g. you've got at least two different types of Orders? In other words, would you use interfaces because of only technical needs in the domain model, or only when it is really appropriate with respect to the actual domain?

like image 594
cretzel Avatar asked Sep 30 '08 07:09

cretzel


People also ask

Should I create an interface for every class?

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.

Should I create an interface for every class Java?

No, it's not necessary for every class to implement an interface. Use interfaces only if they make your code cleaner and easier to write. If your program has no current need for to have more than 1 implementation for a given class, then you don't need an interface.

Should you use interfaces everywhere?

It is only a good thing where you need it, and bad everywhere else. If you are using an interface on a place where should be high cohesion, then you are doing it wrong. Every interface has a cost and a value, if you are not considering it and blindly make them everywhere, then you are doing it simply wrong.

Do I need to use an interface when only one class will ever implement it?

Interfaces can be implemented by multiple classes. There is no rule that only one class can implement these. Interfaces provide abstraction to the java.


1 Answers

Writing interfaces "just because" strikes me as a waste of time and energy, not to mention a violation of the KISS-principle.

I write them when they are actually useful in representing common behavior of related classes, not just as a fancy header file.

like image 77
Rik Avatar answered Oct 22 '22 10:10

Rik