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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With