Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Constants in Java [duplicate]

Tags:

java

constants

Is this a good idea, to group constants in classes inside Constants class container like

public final class Constants {
  public final class File {
    public static final int MIN_ROWS = 1;
    public static final int MAX_ROWS = 1000;

    private File() {}
  }

  public final class DB {
    public static final String name = "oups";

    public final class Connection() {
      public static final String URL = "jdbc:tra-ta-ta";
      public static final String USER = "testUser";
      public static final String PASSWORD = "testPassword";

      private Connection() {}
    }

    private DB() {}
  }

  private Constants() {}
}

It allows to use Constants.DB.Connection.URL instead of DbConnectionConstants.URL.

like image 347
albus.ua Avatar asked Dec 28 '22 08:12

albus.ua


2 Answers

I generally prefer to put constants in the class where they belong. For example, the file constants could be in FileManager (or something like that), where they are used. The connection constants could be in your DBUtil class, where they are used.

Think about the JDK. Does it have a gigantic Constants class? No. The constants used by (and with) BorderLayout are in the class BorderLayout. The constants used by (and with) JOptionPane are in JOptionPane.

like image 133
JB Nizet Avatar answered Jan 08 '23 12:01

JB Nizet


Advantages:

  1. You get a nice "path" to your constants.
  2. You might get a cross-code constants convention, if colleages follow the guidance.

Disadvantages:

  1. With many constants and many "domains" of constants, that class might get too cumbersome to handle.
  2. It's not intuitive. It reminds me more of Ant properties than java constants.
  3. It prevents modularization of your code. Say you want to separate your DB connecting package and File handling package to different jars which might be used by different applications. It is redundant to deliver your DB management jar with file handling constants. And you can easily get to have many such modules.

In conclusion, it's something that might be handy when you write just some little application for your own self. Generally, it is not a good practice.

like image 35
yair Avatar answered Jan 08 '23 12:01

yair