Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using interfaces to namespace constants in Android

Tags:

java

android

From what I've read using interfaces to define constants is generally looked down upon in Java except when you intend constants to be inherited by classes implement the interface. But I've come across code like this often in Android programs:

interface Tags {
    String BLOCK = "block";
    String TITLE = "title";
    String START = "start";
    String END = "end";
    String TYPE = "type";
}

Personally I like being able to group constants together like this into a namespace of sorts. So my question is there any disadvantage to doing this? I'm assuming it's probably not as efficient as using static final strings as the compiler can inline those.

like image 839
Comrade Chesley Avatar asked Apr 14 '11 03:04

Comrade Chesley


People also ask

Can I use interface for constants?

It's possible to place widely used constants in an interface. If a class implements such an interface, then the class can refer to those constants without a qualifying class name.

Can we use interface for constants in Java?

That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.

CAN interfaces have constant variables?

In an interface, we're allowed to use: constants variables. abstract methods. static methods.

How do you declare a constant in an interface?

The most common way to define a constant is in a class and using public static final . One can then use the constant in another class using ClassName. CONSTANT_NAME .


1 Answers

First, know that fields in an interface are implicitely static and final.

Constant interfaces are generally considered an anti-pattern (see http://en.wikipedia.org/wiki/Constant_interface). The better alternative would be:

public final class Tags {
    public static final String BLOCK = "block";
    // Other constants...

    private Tags() {}
}

Since the Tags class is final, no class can extend it. Instead, classes that want to use constants from Tags simply do:

import my.package.Tags;

and then:

System.out.println(Tags.BLOCK);

From Java 5, the constants can be imported directly:

import static my.package.Tags.BLOCK;
// Other static imports...

so they can be used like so:

System.out.println(BLOCK);
like image 81
Laurent Pireyn Avatar answered Oct 03 '22 08:10

Laurent Pireyn