What is the correct way to declare project constants in Java?

This may seem like a silly question for Java developers, however, I am new to Java and my background is from low level c. I used the header file with all the constants related to my projects. (usually # define). I am currently working on a large Java project, and I need to create several constants that I need to make global (they fit into several classes and are used in different parts of the project)

It’s hard for me to decide where to put it, should I declare the same constant several times, one in each class?

Many frameworks use XML files to declare constants and definitions for the framework (Hibernate, Log4J, etc.). Is it wise to use this method in my project? if so, how can this be done easily?

+6
source share
2 answers

As with many things, there are many ways to do this. One thing you shouldn't do is declare them several times - it's just plain stupid .: P

Everything should be in a class in Java, so either:

  • Select the "main" class (let's say I have a project called "FTPServerApp" - I could post them there)
  • Create a class "Util" containing all of them

When you figure out where to put them, declare them this way:

public static final [type] [NAME_IN_ALL_CAPS] = [value]; 

It will be

  • make them available for all project code anywhere ( public )
  • only one copy of the value exists in all instances of the class ( static )
  • they cannot be changed ( final ).

ALL_CAPS_FOR_CONSTANT_NAMES , separated by underscores, is a symbol in Java.

So, if this was declared in a class called FTPServerAPP , and you had a constant called SERVICE_PORT , it could be:

 public class FTPServerApp { public static final int SERVICE_PORT = 21; ... } 

... and you will access it from any class, for example ...

  FTPServerApp.SERVICE_PORT 
+10
source

Take a look at the enumeration types ( http://download.oracle.com/javase/tutorial/java/javaOO/enum.html ). They should provide a mechanism for providing constants without defining a particular class (or an Interface with the required constants, like another option that people use).

Another technique that I find useful (similar to the FTPServerApp example above) is to determine the Context for any subsystem / component / etc., which contains not only the constants needed by the components in this system, but may also contain any what you want to make more visible or you don’t want individual components to be held. I think this looks like one of the GoF templates, but I looked at this book for so long that I can’t be sure (and I'm too lazy to watch it right now!)

+1
source

Source: https://habr.com/ru/post/899382/


All Articles