Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which package should the implementation of a Java interface reside?

Let's say I have an interface:

package org.my.dicom.CEchoSCU;

public interface CEchoSCU {
    // stuff here...
}

I will also have an implementation of the interface:

public class SimpleCEchoSCU implements CEchoSCU {
    // stuff here...
}

My question is, which package should house the implementation? I have seen other developers place the implementation is in the same package as the interface (org.my.dicom, in this case), and also cases where a separate package is used (typically something like org.my.dicom.impl). Other than personal preference, is there any reason to prefer one over the other?

like image 839
Evan Haas Avatar asked Oct 19 '12 14:10

Evan Haas


2 Answers

A class implements, among other things, an interface. I would stick the class in a package that is related to what the rest of the class does/contains, not a package that reflects one interface it implements. For instance, if I had 200 classes that implement Printable, I wouldn't stick them all in a package com.mycompany.impl.printable. The Airplane class that implements printable would go in a package with other airplane stuff. The Boat class would go in a package with other boat stuff. The Car class that implements Printable would go in a package with other car stuff.

If all SimpleCEchoSCU (and any other future classes) does is implement CEchoSCU, then you should consider making CEchoSCU an abstract base class and deriving different implementations. And either way, (interface or abstract base class) things would be completely related and I would put them in the same package.

like image 176
Scooter Avatar answered Oct 13 '22 10:10

Scooter


Well, it is not a hard-and-fast rule as to where would you place your implementation class and interface. You can have them in any package, as long as they can be accessed where they are supposed to be.

But, of course, you would also want to have all your related classes in one package, and the class which is not related to your set of classes, to be in different package.

Most of the times, my approach is that : - I keep my interfaces in a different package, and the implementing classes in different package. That way, if I want to give my interfaces to some one else, then I can directly give away my package that contain all my interfaces.

But again, that completely depends upon your requirement, and the design practice that you follow in your code.

So my choice of package name generally is: -

  • com.someName.api -> For Interfaces
  • com.someName.impl -> For Implementing Classes.

That way I can easily separate my api from the implementation.

like image 28
Rohit Jain Avatar answered Oct 13 '22 10:10

Rohit Jain