Header like Class for defining constants in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you define a class of constants in Java?
I would like to define a class in my package to contain only the constant vales like defines in C. I am a C programmer learning Java so perhaps that is why I still want to have some header like class :)
For this purpose here is the class I have:
package com.myclasses
public class defines{
public static byte final ID_1= 0x01;
public static final ID_2= 0x02;
public static String company_name="XYZ";
}
Then somewhere in a another class in the same package, I use these defines as follows:
byte idval = defines.ID_1;
... and so on.
My question is for such a "header" class what is the best way of defining it?
It has only static variables so should I define the class also static?
What about the access modifier? Since it has defines in it I thought it could be made "public".
Please advise.

Don't
There are hardly any constants that have value in their own. They only make sense in context. That context is a real class, i.e. a class that has instances (at least one). Declare the constants in that class.
As for the modifiers: reduce the scope as far as possible: Private if only used inside the class where they are declared, public if anybody using the class needs the constants as well.
If you declare more then one constant of same type in one class, think about if a enum makes mores sense.
And yes, constants should be static.

This pattern is called the "constant class" pattern (I think).
One way of using it is to make it an interface and implement it, then you get the references for "free":
public interface Defines {
static byte final ID_1= 0x01;
static final ID_2= 0x02;
// etc
}
public class MyClass implements Defines {
byte idval = ID_1; // Note: No need to refer to the class "Defines" here
}
but most people consider this an anti-pattern, because it isn't a real interface (it has no methods). Nevertheless, it is kind of cool, and may be a good way for you to ease into java.
The "standard" approach is to define a "utility class", which is one that has only static fields and methods, give it a private constructor to reinforce that you shouldn't create one of these. This is what you have done - keep doing it.
If you have a few constants that are different values of "the same thing", eg directions on a compass, etc, strongly consider using an enum. You should read up on them.

Use a final class
eg : public final class defines {
// private constructor
private defines() {
}
}
The constants should be defined as
public static final <type> constantName = <value>;
Wouldn't recommend enums in this scenario as Enums should be used when we are having constants which are having some relation between them.
Having a utility class like this, is the approach we use in our project to define constants that needs to be accessed across a project.
If you needs the constants only in that certain class then defining them in the class itself will be the best solution. eg:
private static final <type> constantName = <value>;

Just use an Interface in Java to define all your Constants..
public interface Const {
String GOVERNMENT = "Government";
String PUBLIC = "Public";
...
}
You can use class also.

Related

Use Interface for declaring Constants or a Class [duplicate]

This question already has answers here:
Interfaces with static fields in java for sharing 'constants'
(8 answers)
Closed 9 years ago.
I use Interface for declaring Constants as they are public static final. Lot of times I've seen people write a class with public static final constant variables and sometimes I've done the same. Which one is the better practice to implement, the Interface or using a class?
public class MyCodeConstants {
public static final String VALUE_1 = "VALUE1";
public static final String VALUE_2= "VALUE2";
}
or
public interface MyCodeConstants {
public static final String VALUE_1 = "VALUE1";
public static final String VALUE_2= "VALUE2";
}
WHICH ONE IS A BETTER PRACTICE TO USE AND WHY??
In terms of design both are bad. A class should have methods in your software in order to respect the definition of a class and the encapsulation principle. Interfaces are used to indicate similar behavior of classes and shouldn't be used to stock constants. However, a good solution would be to create a new class that is called Value. You can find more details here :
Should a collection of constants be placed in a class or interface?
First, constants should only be specified that manner if they do need to be part of the public API, and you should always consider whether an enum would make more sense.
However, if it really does make sense to have public constants (intent names for Android, the HTTP status codes), then they should go on the type they belong to. In the case of HTTP status codes, they're most closely associated with HttpServletResponse, which is an interface, and so they go there. If the constants are associated with a class (and it's not a better design to pull an interface out of that class), they should go there.

Java Interface - constants and static class in normal interface

Consider following interface.
public interface ThirdPartyApiHandler {
public OperationResult doOperation(OperationInput input);
public static class OperationResult {
//members of OpeationResult. metrics after file processing
private int successfulRecords;
private int failedRecords;
}
public static class OperationInput {
//implementations call third party API to process this file.
private String inputBatchFile;
}
//Constant which would be same across all implementations.
public static final int GLOBAL_CONSTANT = 1;
}
Is above interface a bad design?
OperationResult and OperationInput are defined as static class. They would be only used by implementations and not anywhere else. Advantage that I see here is - I don't have to create separate files for these two classes. Also they get namespace of parent class.
I have read about constant interface. But in this case, I am defining constant in normal interface which are bound to be same across all implementations and would be used in those implementations.
I am using this pattern for first time so wanted to get suggestions.
OperationResult and OperationInput are defined as static inner class.
They won't be used anywhere else.
That's OK since they will not be used anywhere else. If they're long than I would prefer to have them in separate classes.
I have read about constant interface. But in this case, I am defining constant in normal interface which are bound to be same across all implementations and would be used in those implementations.
That's a good place to declare such a field.
Having nested classes in interfaces is only matter of additional namespace. This approach help to organize the code when small interfaces are created to support simple data structure.
I recommend you this lecture: Java Tip 75: Use nested classes for better organization.
Note that public and static are redundant in this case so you do not need them. What you need to remember is that having such classes do not limit other developers to use them in other parts of code.
From my point of view, this is a good design but, i would extend and replace the class with interfaces.
public interface ThirdPartyApiHandler {
OperationResult doOperation(OperationInput input);
interface OperationResult {
int getSuccessfulRecords();
int getFailedRecords();
}
interface OperationInput {
String getInputBatchFile();
}
final int GLOBAL_CONSTANT = 1; //This could be replaced by enum but no need
}
Is above interface a bad design?
That would depend on your implementation design and it's usability in your project. Logic looks all legal to me. Possible use case of such a design can be as follows
public interface A {
static class B {
public static boolean verifyState( A a ) {
return (true if object implementing class A looks to be in a valid state)
}
}
}
Also
public static class OperationResult {
//members of OpeationResult. metrics after file processing
private int successfulRecords;
private int failedRecords;
}
In above class you have instance variables successfulRecords and failedRecords . why not make the instance variable of these static classes also static so that you can access them using ThirdPartyApiHandler.OperationResult.successfulRecords. You can even have static getters and setters for your variables.
OperationResult and OperationInput are defined as static inner class.
Contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner".
Picked up above from this SO question. Read the 1st answer. I think that will answer all your questions.
Is above interface a bad design?
Quite simply, yes.
Putting any logic in an interface is semantically incorrect. An interface exposes functionality to consumers - that is its single purpose, and that should not be diluted.
Consider implementing any common functionality in a base implementation class and use inheritance, or in one or more services and use composition, in your different interface implementations.
EDIT - quote from Joshua Bloch's Effective Java
When a class implements an interface, the interface serves as a type that can be used to refer to instances of the class. That a class implements an interface should therefore say something about what a client can do with instances of the class. It is inappropriate to define an interface for any other purpose.

Interface Vs Final class to store the final variables

I have a class which contains only final variables.
E.g:
public class Constants
{
public static final String PREFIX = "some prefix";
public static final String SUFFIX = "some suffix";
//and so on...
}
Which type is recommended here - an interface or a final class?
Interfaces are used to define a contract. In the code you copy paste, these constants should be defined in a final class. Check What is the best way to implement constants in Java?
You should use a Final Class for this.
If you are creating a class which contains only globaly accessible final constants you should use enum.
Global constants as you put it should actually be in a properties file as it allows each application to configure them individually without a code modification. For object specific constants my general rule of thumb on Enum versus static final I typically lean towards how many elements there are to have and how related those elements are. If there is a big relation between them such as Suits in a deck of Cards then I would go for the enum. If it is default age for a user, then this becomes a final as there is no purpose to making it an enum as it would not need to be referenced in many areas. These are just some thoughts on each of the ways I have approached it.

Public static final declaration of an instance variables in JAVA Interfaces

Why we use public static final declaration of instance variables in a Java Interface?
All the variables are implicitly public static final in a Java Interface.
Is it a good coding practice to use public static final in constant variable although it is declared inside an Interface.
For example :
public interface TestInterface{
public static final String EX_CONSTANT = "ABC";
public static final int EX_INT_CONSTANT = 5;
public static final double EX_DOUBLE = 5.0;
public static final Integer EX_INTEGER = 10;
}
Use of uniform syntax in both classes and interfaces simplifies refactoring.
You may want to turn your interface into a class somewhere in future, or move these fields into a class, and you'll get a semantical difference if you overlook some fields defined without public static final (of course, we have tools for refactoring, but nonetheless).
I think it's the same thing as support of #Overriden annotation for implementations of methods declared in interfaces that was introduced in Java 6 - it's redundant in its current form, but may become useful in case of refactoring.
I don't think so. All interface variables are implicitly public static final so no meaning to mark them same.
From the book Effective java by JOshua Bloch
Item 19: Use interfaces only to define types
When a class implements an interface, the interface serves as a type that can
be used to refer to instances of the class. That a class implements an interface
should therefore say something about what a client can do with instances of the
class. It is inappropriate to define an interface for any other purpose.
One kind of interface that fails this test is the so-called constant interface.
Such an interface contains no methods; it consists solely of static final fields, each
exporting a constant. Classes using these constants implement the interface to
avoid the need to qualify constant names with a class name. Here is an example:
// Constant interface antipattern - do not use!
public interface PhysicalConstants {
// Avogadro's number (1/mol)
static final double AVOGADROS_NUMBER = 6.02214199e23;
// Boltzmann constant (J/K)
static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
// Mass of the electron (kg)
static final double ELECTRON_MASS = 9.10938188e-31;
}
The constant interface pattern is a poor use of interfaces. 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. Worse, it represents a commitment: if
in a future release the class is modified so that it no longer needs to use the constants,
it still must implement the interface to ensure binary compatibility. If a
nonfinal class implements a constant interface, all of its subclasses will have their
namespaces polluted by the constants in the interface.
There are several constant interfaces in the Java platform libraries, such as
java.io.ObjectStreamConstants. These interfaces should be regarded as
anomalies and should not be emulated.
If you want to export constants, there are several reasonable choices. If the
constants are strongly tied to an existing class or interface, you should add them to
the class or interface. For example, all of the boxed numerical primitive classes,
such as Integer and Double, export MIN_VALUE and MAX_VALUE constants. If the
constants are best viewed as members of an enumerated type, you should export
them with an enum type (Item 30). Otherwise, you should export the constants
with a noninstantiable utility class (Item 4). Here is a utility class version of the
PhysicalConstants example above:
// Constant utility class
package com.effectivejava.science;
public class PhysicalConstants {
private PhysicalConstants() {
} // Prevents instantiation
public static final double AVOGADROS_NUMBER = 6.02214199e23;
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
public static final double ELECTRON_MASS = 9.10938188e-31;
}
Normally a utility class requires clients to qualify constant names with a class
name, for example, PhysicalConstants.AVOGADROS_NUMBER. If you make heavy
use of the constants exported by a utility class, you can avoid the need for qualifying
the constants with the class name by making use of the static import facility,
introduced in release 1.5:
// Use of static import to avoid qualifying constants
import static com.effectivejava.science.PhysicalConstants.*;
public class Test {
double atoms(double mols) {
return AVOGADROS_NUMBER * mols;
}
...
// Many more uses of PhysicalConstants justify static import
}
In summary, interfaces should be used only to define types. They should not
be used to export constants.
IMO, Interface is a contract. Once variables are declared or defined they are not going to change. That's why generally we make them public static final.
Readability is another factor which makes declaration redundant.
Admittedly, it's redundant. Usually people just don't know that they're implicitly public static final and declare it anyway. Ditto with things like declaring:
public abstract interface Test { // Interfaces are always abstract
public void testMethod(); // Interface methods are always public
abstract void anotherTestMethod(); // Also redundant
}
Usually it just boils down to the fact that people don't know that they don't have to declare it one way or the other. I once talked to someone (who was a seasoned programmer) that thought the default case in switch is required or it won't compile.
That being said, the only argument to be made for adding them is that they clarify what their actual visibility and whatnot actually is. It's a matter of readability and clarification, and whether or note to include them is irrelevant in terms of how it actually behaves.
When you are working in a team of programmers, you will find junior programmers who do not know the fact that by default the variables are public static final in the interface, and seeing the variables declared that way will give them extra information about the interface and the use of its variables.
You are correct: it is redundant. I don't like to add redundant syntax at any time. However the practice does has its adherents. Some also like to add parentheses around return-expressions, on the fallacious grounds that it's like an 'if' statement; extra parentheses to 'clarify' arithmetic expressions that a third-grader would understand; etc. It's all part of the rich tapestry of life.

How can I have a constant variable common to all classes in a package?

I want a constant variable to be common to all classes in a package. Is there a way I can do this without making an interface just with the one definition in it, and making every class implement that?
In Java, all constants have to reside in a type (class or interface). But you don't have to implement an interface to use a constant declared inside.
You can try by putting something like this in your package:
interface Constants {
static final String CONSTANT = "CONTANT";
}
and then, using it like this:
String myVar = Constants.CONSTANT;
This way, you still have your interface, but no classes implement it.
Generally applications have a "Constants" class or interface that holds all constants.
I generally to to group constants into logical classes. For instance if there can be two kinds of employees, regular and contract:
class EmployeeType
{
public static final String REGULAR = "regular";
public static final String CONTRACT = "contract";
}
and use it as EmployeeType.REGULAR
If the constants cannot be grouped this way, have a separate class/interface to hold these.
class Constants
{
public static final String APPLICATION_DOMAIN = 'domain';
}
You need not extend/implement this class interface to use the values. The constants will generally be declared public static final, you can access them directly: Constants.APPLICATION_DOMAIN
Use a package private class:
class Constants{
public static final int MY_VALUE = 1234;
}
This can only be accessed by classes from the same package:
int val = Constants.MY_VALUE;
You can do this in various ways:
One way (as mentioned here) is to create a Global constant interface and have a public static final attributes of each constants.`
Create properties file. By having a properties file, you'll have a Key value pair (separated by a = operator) each declared on a newline. Here's a tutorial on how to create and use properties file.
Seems like to be a good candidate for an entry in a property file to me.
You can use an abstract class to serve as the base class for each impls in that package.
You could make a special (static) class with just this variable. Later you can add other constants or whatever you need to that class.

Categories