Use Interface or Class for Constants? - java

There is a lot of negative comments about using interface for constants in Java. I just want to know for Android development if it is the same, and the reason why.
I have this question because I heard the battle between Enum and static final. Enum is not a good thing for Android development, and I found a YouTube video post by Android Developer that suggests developer to use static final instead of Enum.

It depends on what you are trying to do. If you need to store a collection of typesafe static data, then use enums. For example, you might use a collection of coin types for representing currency.
Like this:
public enum Coin {
PENNY,
NICKEL,
DIME,
QUARTER;
}
For static data that is not of the same type, use static final values.
For example:
static final int FREEZING_TEMP_FAHRENHEIT = 32
static final double GRAVITY = 9.81
It depends on if you can group that static data such that it should be stored as a collection of things. If so, enum. If not, static final.

What do you mean by interface for constant? In most of my apps I have a Singleton class Constants that has some public static final field (stuff that is known at development time) and some public fields (stuff that is only known at runtime and is initialized when the singleton instance is initialized by the first call to Constants.getInstance()). If some of my fields need a context to be set, usually I add a method initialize(Context context), that is the first thing I call in MainActivity's onCreate.

For constants I generally create a resource for it. For strings for example you would use strings.xml, you can have integer constants as well. This method is useful because you abstract your content from your code which I feel is more organized. For constants needed for a specific class I would keep them scoped inside the class though!

Related

What are the drawbacks of enums in Java?

While looking at jhipster, I have stumbled across the following class
public final class AuthoritiesConstants {
public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {
}
}
I was wondering why they did not use enums like for example
public enum AuthoritiesConstants {
ROLE_ADMIN,
ROLE_RESPONSABLE,
ROLE_MANAGER,
ROLE_COLLABORATEUR
}
Are there any drawbacks using enums?
One possible answer is that enums were introduced in Java 1.5. While this seems like ancient history, some libraries still use string constants or numeric constants for compatibility reasons.
Another possible answer is that those are not really semantically enum elements, but constants used by an external interface and are only ever accessed via their string value. In such cases, using enums and calling name() each time would be redundant.
Other than that, you should never use enums over string constants in such cases.
1. It is much like class it’s extend java.lang.Enum so you can’t extend
other enum. Another potential problem is you don’t get along with
Expression Language (EL) in JSP.
2. There are things that can be done in normal classes but maybe you can
not do with enum class because of it is a special class. For example,
accessing a static field in the constructor that not possible with
enum.
3. When you working with JSP then you can not be accessing enums nor
calling enum constants because it’s not supported (which is possible
after EL version 3.0)
These are Major drawback.
.
If a value is only really meant to be referenced as a String, then I would leave it as a String constant for simplicity's sake.
Enums are more complicated than String constants with additional functionality and nuance. Check out this question about the difference between an enum's toString and name methods.
If you ever need to change the value of a String constant, it is a one-line change. With an enum it can get more complicated due to having separate values for name and toString, and those values possibly being used in conditional logic.

Use static properties for constants with java

In my java program I use a Constants.java class. In this class I created about 50 Strings properties in this way
public static final String startError = "The program could not be started, please ......";
public static final String logPath="/Users/hgvu/";
In my program I use this class in this way for example
System.out.println(Constants.startError);
I am new in the domain, do you think it's a good idea to make fields in the Constants class static ?
Make your class final, like public final class Constants. And Java doesn't let you create top-level static classes, I think you meant making fields static when you asked "do you think it's a good idea to make the Constants class static". The answer is yes, it is the best way to go about it.
In my opinion Constants should not vary - therefore they should always be static... This also means you can access the constant variable values without having to initiate the Constants.java class
you wont be able to define a Static class in java unless it is nested, but if you want the constants to be shared across, then making it a nested class does not make any buyout.
But you can make your class final and have private constructor would be a good choice if you want this class to only contain your constants

What is the use of the enum singleton in Java?

When the Gang of four introduced the singleton pattern, they also had to explain, why not to use static class fields and method instead. The reason was: the possibility to inherit. For Java it had sense - we cannot normally inherit the class fields and methods.
Later the "Effective Java" book appeared. And we know now that the existence of reflection destroys the singularity of the singleton class with private constructor. And the only way to make a real SINGLEton is to make it as a single item of an enumeration. Nice. I had done some myself this way.
But a question remains: While we cannot inherit from enumeration, what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Edit. Thanks to the #bayou.io I see that in https://softwareengineering.stackexchange.com/a/204181/44104 there is a code that can trick the enum, too, and create again two exemplars of the enum singleton. The other problems are mentioned there, too. So, there is no need to use enum instead of the usual singleton class pattern, too? BTW, all enum pluses that are mentioned here till now, work for singleton classes, too.
what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Because enum is an object so it can not only be passed around but also implement interfaces.
Also since we are making a class, we can use the different public/private options available to all kinds of classes.
So in practice, we can make a singleton that implements an interface and then pass it around in our code and the calling code is non the wiser. We can also make the enum class package private but still pass it around to other classes in other packages that expect the interface.
If we used the static methods version, then the calling class would have to know that this object is a singleton, and our singleton class would have to be public so the other classes can see it and use it's methods.
There's nothing particularly wrong with the "good old fashioned singleton", enum "singletons" are just convenient - it saves you the need to muck around with boiler-plated code that looks the same in every singelton.
To me, a singleton makes sense wherever you want to represent something which is unique in its kind.
As an example, if we wanted to model the Sun, it could not be a normal class, because there is only one Sun. However it makes sense to make it inherit from a Star class. In this case I would opt for a static instance, with a static getter.
To clarify, here is what I'm talking about :
public class Star {
private final String name;
private final double density, massInKg;
public Star(String name, double density, double massInKg) {
// ...
}
public void explode() {
// ...
}
}
public final class Sun extends Star {
public static final Sun INSTANCE = new Sun();
private Sun() { super("The shiniest of all", /**...**/, /**...**/); }
}
Sun can use all the methods of Star and define new ones. This would not be possible with an enum (extending a class, I mean).
If there is no need to model this kind of inheritance relationships, as you said, the enum becomes better suited, or at least easier and clearer. For example, if an application has a single ApplicationContext per JVM, it makes sense to have it as a singleton and it usually doesn't require to inherit from anything or to be extendable. I would then use an enum.
Note that in some languages such as Scala, there is a special keyword for singletons (object) which not only enables to easily define singletons but also completely replaces the notion of static method or field.
ENUM singletons are easy to write. It will occupy very less code, which is clean & elegant if you compare with implementation of lazy singleton with double synchronized blocks
public enum EasySingleton{
INSTANCE;
}
Creation of ENUM instance is thread safe.
ENUM singletons handled serialization by themselves.
conventional Singletons implementing Serializable interface are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton
private Object readResolve(){
return INSTANCE;
}
Have a look at this article on singleton

What kind of global variable is bad practice in java?

For many of my java projects, I use database extensively, what I usually do is to have a property.xml file to hold all my strings and settings.
And then I would have a class CNST to hold all the static constants corresponding to those in the xml file.
Those constants are initialized by the xml file once when the program starts, and used as globals anywhere later on in the program.
However, after reading many articles these days, it seems that using globals at all is not such a good practice. So please can anyone may indicate a good practice fo this situation? Thanks.
In general global variables should be avoided when it is possible => this however is not an issue if they are constants. For cases like this one when you (presumably) initialize this global-settings wrapper object at the beginning and nothing is changed afterwards, there are these options:
Having constants (public static final) which are initialized in static block
Having the variables private static final initialized in static block and exposed via getters
Creating a singleton and having the variables private final exposed via getters
The 2nd and 3rd point has advantage over the 1st that in getter methods you have encapsulated the values of variables and can change/insert code which manipulates the value to be returned to calling method without effecting the (calling) code dependent on it.
Using global variables means they are visible to many classes who can manipulate the data then.
So you will have to take care of your data is it is widely visible.
And if you are using multithreading then you are in trouble as anybody can modify that data, so lots of scope for data getting corrupted.
As a matter of practice i follow following points:
Keep variable visiblity minimal, private if possible.
Make it immutable wherever possible.
You can freely use public static constants or variables. If you use non-static variables then good practice is to use Getters and Setters. If your class conatains only static constants then you can also use private constructor to restrict creating instances of this class.
public class Global {
public static final int A;
public static final int B;
private Global() {} // use only when you have only static fields and methods
static {
A = 1;
B = 2;
}
}
You can create a public static variable instead of Global variable that would be a better idea.
Check out this link.
One other approach is to create a class that follows the singleton pattern, so there can only be one instance of the class and keep the variable in the singleton class and access it with get and set methods.
Edit1:-
Go for the old style in case of declaring the constants. Something like this:-
(public/private) static final TYPE NAME = VALUE;
I would not recommend creating a class in that case.

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.

Categories