static variables in interfaces

Discussions

EJB design: static variables in interfaces

  1. static variables in interfaces (4 messages)

    Was wondering whether it is good practice to have static variables on interfaces..
    and refer to those variables via the interface.

    eg

    public Interface MyInterface {

    Threaded Messages (4)

  2. One of the most common reasons to this is essentially to simulate the use of Enums. If you happen to use them for a simillar purpose, I'd stronly recomend that you take a very close look at the Jakarta Commons Lang project. They have an implementation for TypeSafe Enums which is excellent.
  3. thanks for the reply...
    I use them generally to keep states eg;

    public interface State {
      public static int ON = 1;
      public static int OFF = 2;
     }

    ----------------------------------


    public class Something {
      
     public boolean doLightAction(int state) {
      if(state == State.ON) {
         somethingOn();
         return true;
       }
      else {
       somethingOff();
       return false;
      }
     }

    } //class

    Then... a client code would have...

    public static void main(String [] ar) {
      Something a = new Something();
      a.doLightAction(State.ON);
     }

    ----------------------
    So is this a good way of doing what i want? dont know how to describe how i want but so thats why i gave like a snapshot of what i mean...
  4. static variables in interfaces[ Go to top ]

    Hi!

    This is a very good way of doing what you want. One alternative is to use a class with a private constructor (to prevent instantiation) instead on an interface. But an interface works fine as long as you don't implement it. See java.sql.Types for an example.

    Using int constants is correct, since it allows you to use switch/case (instead of several if-statements) in the future.

    Another good idea is to use the values 1, 2, 4, 8, 16, ... instead of 1, 2, 3, 4, ... By using the first sequence, you can add constants and givethe value a meaning. Example: java.awt.Font uses this, and therefore Font.BOLD+Font.ITALIC can be used in the code to mean both "bold" and "italic". This is great!!!

    Using the 1, 2, 4, 8, 16, ... sequence also makes it possible to use the SQL AND operator when searching for records in a database. I always use this type of int constants to describe states, and then I can search for (as a short example) State.OPEN + State.PREPARED to get all records in the "prepared" or in the "open" state.

    /Tomas
  5. static variables in interfaces[ Go to top ]

    You really want to look into the Enum Pattern and use the implementation from the Jakartas Commons Lang package. This patter will give you typesafety in your code.