Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should constants ever be placed in an interface?

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.

like image 518
donturner Avatar asked Dec 07 '11 23:12

donturner


2 Answers

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

like image 98
Jaime Hablutzel Avatar answered Sep 26 '22 20:09

Jaime Hablutzel


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.

like image 42
Rob Hruska Avatar answered Sep 25 '22 20:09

Rob Hruska