I am aware that putting constants in an interface is generally considered bad practice but...
I am using the Observer pattern to broadcast events from an object to a listener.
interface DownloadListener
{
public void sendEvent(int eventId);
}
The broadcaster uses constant ints to tell the listener which event has happened.
class DownloadTask
{
public static final int EVENT_DOWNLOAD_STARTED = 1;
public static final int EVENT_DOWNLOAD_COMPLETED = 2; //should these go here?
DownloadTask(DownloadListener listener)
{
listener.sendEvent(EVENT_DOWNLOAD_STARTED);
}
}
Would it be better to place the constants inside the interface? My thinking is that the interface is the contract between the broadcaster and the listener and therefore it should contain the details (constants) of that contract.
I'm developing for mobile (Java 1.3) so unfortunately can't use an enum type.
Interfaces describe services, so if the constant is part of the description or definition of the service it should go in the interface, so every implementation of that interface can reuse them. In your case for example constants should go to the interface
The interface
seems like an acceptable place for them.
I think your "putting constants in an interface is generally considered bad practice" statement really only applies if you're using the Constant Interface anti-pattern.
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