Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should interfaces be placed in a separate package? [closed]

I'm new to a team working on a rather large project, with lots of components and dependencies. For every component, there's an interfaces package where the exposed interfaces for that component are placed. Is this a good practice?

My usual practice has always been interfaces and implementations go in the same package.

like image 989
kctang Avatar asked Jun 17 '09 03:06

kctang


People also ask

Should interfaces be in separate project?

Because interfaces can be implemented by multiple components, it's good practice to put them in a separate assembly from that of the implementing components.

Can interfaces be part of package?

All classes and interfaces in a package are accessible to all other classes and interfaces in that package. All the member elements and method of a class can be accessed from any method of any class under the same package, except when the data and method are declared private.

What is the correct way to implement an interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

Can package have interfaces in Java?

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.


1 Answers

Placing both the interface and the implementation is common place, and doesn't seem to be a problem.

Take for example the Java API -- most classes have both interfaces and their implementations included in the same package.

Take for example the java.util package:

It contains the interfaces such as Set, Map, List, while also having the implementations such as HashSet, HashMap and ArrayList.

Furthermore, the Javadocs are designed to work well in those conditions, as it separates the documentation into the Interfaces and Classes views when displaying the contents of the package.

Having packages only for interfaces may actually be a little bit excessive, unless there are enormous numbers of interfaces. But separating the interfaces into their own packages just for the sake of doing so sounds like bad practice.

If differentiating the name of a interface from an implementation is necessary, one could have a naming convention to make interfaces easier to identify:

  • Prefix the interface name with an I. This approach is taken with the interfaces in the .NET framework. It would be fairly easy to tell that IList is an interface for a list.

  • Use the -able suffix. This approach is seen often in the Java API, such as Comparable, Iterable, and Serializable to name a few.

like image 170
coobird Avatar answered Oct 03 '22 01:10

coobird