Exposing instance constants with non-static public final variables - java

I never see this kind of constants declaration in any Java code around me...
So i'd like to know if you see any drawback of using non-static final constants.
For exemple, i've declared a Guava function as a public constant of a given MaintenanceMode instance. I think it's better because if i created a getDecoratorFunction() it would create a new function instance each time...
Or the get function could return the single instance function that is kept private in the class, but it hads useless code... When we declare constants at class level, we declare directly the constants being public, we do not put them private and provide a public getter to access them...
public class MaintenanceMode {
/**
* Provides a function to decorate a push service with the appropriate decorator
*/
public final Function<PushService,PushService> MAINTENANCE_DECORATION_FUNCTION = new Function<PushService,PushService>() {
#Override
public PushService apply(PushService serviceToDecorate) {
return new PushServiceMaintenanceDecorator(serviceToDecorate,MaintenanceMode.this);
}
};
private final EnumMaintenanceMode maintenanceMode;
private final long milliesBetweenMaintenances;
private final Optional<ExecutorService> executorService;
public EnumMaintenanceMode getMaintenanceMode() {
return maintenanceMode;
}
public long getMilliesBetweenMaintenances() {
return milliesBetweenMaintenances;
}
public Optional<ExecutorService> getExecutorService() {
return executorService;
}
private MaintenanceMode(EnumMaintenanceMode maintenanceMode, long milliesBetweenMaintenances, ExecutorService executorService) {
Preconditions.checkArgument(maintenanceMode != null);
Preconditions.checkArgument(milliesBetweenMaintenances >= 0);
this.maintenanceMode = maintenanceMode;
this.milliesBetweenMaintenances = milliesBetweenMaintenances;
this.executorService = Optional.fromNullable(executorService);
}
}
And i can access this variable with:
pushServiceRegistry.decoratePushServices(maintenanceMode.MAINTENANCE_DECORATION_FUNCTION);
I guess it could lead to strange behaviours if my maintenanceMode was mutable and accessed by multiple threads, but here it's not.
Do you see any drawback of using this kind of code?
Edit: I can have multiple instances of MaintenanceMode, and all instances should be able to provide a different constant function according to the MaintenanceMode state. So i can't use a static variable that would not access the MaintenanceMode state.

The point of a getter would be dynamic dispatch. If you have no need for it, using a public final field is perfectly fine. I even routinely write bean-like objects that have no getters, just public final fields.

By making a constant non-static, you are basically saying that the constant can only be accessed when you have an instance of that class. But it is public (in the case of MAINTENANCE_DECORATION_FUNCTION) and it is part of that class so why not make it static? The constant is, after all, a constant and it does not require an instance of that class to be used elsewhere. The variable maintenanceMode is fine as it is a private constant.

Related

Static to non-static refactoring, can't have both?

I have a refactoring situation that I cannot find an elegant solution for...
Disclaimer:
Keep in mind that I am oversimplifying this example to reduce clutter, and not disclose things I am not allowed to disclose :)
As such, please do not assume that this is the ONLY code in my giant codebase, and offer solutions that cut corners or change parts of the design that I mention cannot be changed due to outside constraints.
The facts:
I have a utility class, it has a bunch of static methods, they utilize a singleton resource:
public final class Utility
{
private static final Resource RES = Resource.getInstance();
private Utility() {} // Prevent instantiating Utility
public static boolean utilMethodOne() { return RES.isSomething(); }
public static int utilMethodTwo() { RES.getNumThings(); }
...
public static void utilMethodInfinity() { ... }
}
Utility is in a library JAR that is used by several applications in a large codebase -- let's say on the order of 10,000 calls to its static methods, e.g.: if(Utility.utilMethodOne()) { ... }
Resource is an outside class from another library JAR.
Resource also has a method Resource.getInstance(String name) that will return a named instance, which may relate to a different underlying resource based on the name (internally it keeps the named resources in a Map<String,Resource>).
Resource.getInstance() returns the equivalent of Resoruce.getInstance(""), aka the default instance.
The situation:
The Utility needs to be enhanced to now execute against one of several resources, so my plan is to make the Utility an instantiable class with a non-static Resource member variable. Something like this:
public final class Utility
{
private Resource res;
public Utility(String resName)
{
this.res = = Resource.getInstance(resName);
}
public boolean utilMethodOne() { return this.res.isSomething(); }
public int utilMethodTwo() { this.res.getNumThings(); }
...
public void utilMethodInfinity() { ... }
}
Now all this is great, and I can start creating Utility objects that access their specified resource instead of just the default one. However, as I mentioned, there are 10-100K method calls that are now invalid as they were calling static methods!
The problem:
My plan was to keep the static methods in Utility, and have them use the default instance from Resource, while adding in non-static variants for the instantiated Utility objects that use their "local" resource reference.
// Best of both worlds:
public static boolean utilMethodOne() { return RES.isSomething(); }
public boolean utilMethodOne() { return this.res.isSomething(); }
Maybe I can't have my cake & eat it too:
error: method utilMethodOne() is already defined in class Utility
public static boolean utilMethodOne(String sql)
So it seems I am going to have to either...
Introduce a whole new BetterUtility class for places that want to use the named-resources.
Update 10,000 places to instantiate & use the revised Utility object.
...? (hint: this is where your suggestions come in!)
I really don't like 1 or 2 for a variety of reasons, so I need to ensure there is no better 3 option before settling. Is there any way to retain a single class that can provide both the static & non-static interfaces in this case?
UPDATE 2020-06-01:
I am coming to the realization that this magical option 3 doesn't exist. So out of my original two options I think #2 is best as it's just one time "just get it out of the way and be done with it" type effort. Also incorporated some of your suggestions in the design(s).
So now that I have a direction on this, I am left with [hopefully only] one more key decision...
Update all the calls to create new objects
// For a one-off call, do it inline
boolean foo = new Utility("res1").utilMethodOne();
// Or when used multiple times, re-use the object
Utility util = new Utility("res1");
boolean foo = util.utilMethodOne();
int bar = util.utilMethodTwo();
...
Given the amount/frequency of usage, this seems like a whole lot of wasted efforts creating short-lived objects.
Follow the pattern that Resource itself uses, creating my own named-singleton map of Utilities (1:1 with their respectively named Resource)
public final class Utility
{
private static final Map<String,Utility> NAMED_INSTANCES = new HashMap<>();
private Resource res;
private Utility(String resName)
{
this.res = Resource.getInstance(resName);
}
public static Utility getInstance(String resName)
{
synchronized(NAMED_INSTANCES)
{
Utility instance = NAMED_INSTANCES.get(resName);
if(instance == null)
{
instance = new Utility(resName);
NAMED_INSTANCES.put(resName, instance);
}
return instance;
}
}
public boolean utilMethodOne() { return this.res.isSomething(); }
public int utilMethodTwo() { this.res.getNumThings(); }
...
public void utilMethodInfinity() { ... }
}
// Now the calls can use
Utility.getInstance("res1")
// In place of
new Utility("res1")
So essentially this boils down to object creation vs. a synchronization + map lookup at each usage. Probably a little bit of premature optimization here, but I'll probably have to stick with this decision long term.
UPDATE 2020-06-29:
Didn't want to leave an "Internet dead end" here...
I did eventually get all the call sites updated as described above (including option #2 from the 2020-06-01 update). It has made it through all testing and been running in production for a week or so now in various applications.
It seems that you may want to turn the Utility into a singleton map that will have the same static methods that access the singleton without any arguments on for the function invocations (just like you have now)
The singleton will support a static method of adding a new resource, you will then add it to the map.
In addition you can overload the existing methods to also accept an argument resource name, that will then use a particular resource from the map, otherwise will use the default entry from the map.
Keep the old methods and the new methods static.
private static final String DEFAULT = "RESOURCE1";
private static Map<String, Resource> resources = new HashMap();
static{
// initialize all resources
}
public static boolean utilMethod() { return resources.get(DEFAULT).isSomething(); }
public static boolean utilMethod(String resourceName) { return resources.get(resourceName).isSomething(); }

What if the benefit of using a final instance in the classic singleton pattern (if any)?

In the below snippet, Singleton1#INSTANCE is not final, while Singleton2#INSTANCE is:
public class Singleton1 {
private static Singleton1 INSTANCE = new Singleton1();
private Singleton1() {}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
public class Singleton2 {
private static final Singleton2 INSTANCE = new Singleton2();
private Singleton2() {
public static Singleton2 getInstance() {
return INSTANCE;
}
}
What is the benefit of Singleton2 over Singleton1 (if any)?
There is none, Java wise. Class initialization happens atomically, within locks. No thread will be able to see Singleton1#INSTANCE partially created.
At this point, use final to clarify (to developers) that this field should not change.
I'm fairly certain that the answer is none for performance. It could prevent a bug if someone were to try and modify the reference at some point during the maintenance cycle.
final is basically used for two purposes in java -
1) For immutability - If a field is final, then it can only be initialized only once. So, if INSTANCE is not final then you can reinitialize creating one more object but this can only be done as constructor is private. So, basically final can avoid any other bugs which can be introduced at later stage as mentioned by Elliott.
2) To ensure that object is properly constructed before publishing (it is in context of multithreading) but since we are instantiating the INSTANCE on class loading (eager loading). It will not cause any issues. It will be created long before it will be used.

Singleton or static class?

I have the following class :
public class EnteredValues {
private HashMap<String, String> mEnteredValues;
public boolean change = false;
public boolean submit = false;
private static final EnteredValues instance = new EnteredValues();
// Singleton
private EnteredValues() {
mEnteredValues = new HashMap<String, String>();
}
public static EnteredValues getInstance() {
return instance;
}
public void addValue(String id, String value) {
if (mEnteredValues.put(id, value) != null) {
// A change has happened
change = true;
}
}
public String getValueForIdentifier(String identifier) {
return mEnteredValues.get(identifier);
}
public HashMap<String, String> getEnteredValues() {
return mEnteredValues;
}
public void clean() {
mEnteredValues.clear();
change = false;
submit = false;
}
}
This class is used to manage the values that a user has already entered, and the class should be accessible to all classes across the application.
When the activity changes I 'reset' the singleton by calling the clear method.
I chose the singleton pattern without really considering the option of a static class.
But now I was wondering if I shouldn't just use a static class..
What is the common way to handle a class that just manages values?
Is a static class faster as a singleton?
thx
The very fact that you are providing a clear method to reset the state of your Singleton dictates that you should not use Singleton. This is risky behavior as the state is global. This also means that unit testing is going to be a big pain.
One more thing. Never ever declare instance variables as public. Declare them as private or protected and provide getters and setters. Also, there is no need to initialize instance variables with a value that is their default value.
The main difference between a static class and the singleton pattern is that singleton may be used if you need to implement an interface or such. For this particular case I think you might be better off with a static class since you are not implementing any interface. Relating your question if its one faster to the other, I'd say is negligible the difference but using a static class will remove a small overhead of dynamic instantiation of the class.
What is bad in using singleton if you need such a design? If you need exactly one instance of some object designed to do specified things singleton is not a bad choice for sure.
#see Are Java static calls more or less expensive than non-static calls?
Read
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
From there:
Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
Just for style
I prefer not to rely on Singleton if I don't need to. Why? Less cohesion. If it's a property you can set from outside, then you can test your Activity (or whatever) with unit testing. You can change your mind to use diferent instances if you like, and so on.
My humble advise is to have a property in each of your Activities (maybe you can define a common base class?), and set it at activity initialization with a new fresh instance.
Your code will not know nothing about how to get it (except the init code and maybe you can change it in the future).
But as I've said... just a matter of taste! :)

Setting a final class attribute

Is it possible to set a value for a final attribute from a Private method called from the Constructor of that Object?
public class FinalTest {
private final Object a;
//Constructor
public FinalTest() {
setA();
}
private void setA() {
a = new Object;
}
}
For the above class, compiler gives me an error saying I can't set the value for 'a' from the method.
I understand that its not possible to set value for a final variable from outside a constructor, but in the above case, I am actually doing it in a way within the constructor. So why isn't this allowed?
It's not allowed because you could call setA() via some other non-constructor method later on which would violate the final protection. Since final is a compile time enforced operation, the compiler enforces final by forcing initialization to occur in constructors or in-line.
In your simple example, all looks good but if you later updated your class to something like the following, the problem become more obvious...
public class FinalTest {
private final Object a;
//Constructor
public FinalTest() {
setA();
}
private void setA() {
a = new Object;
}
public void doSomething() {
this.setA(); // not good because a is final
}
}
Just a note: The compiler has to assume the worst case scenario. By declaring an attribute "final", the compiler has to ensure that the attribute cannot be modified outside of the constructor.
In a case where the method is called using reflection (for example), the compiler would never see it, ever. It's a lot easier to prove something is possible than impossible, that is why the compiler works the way it does.
Final checking is done at compile time not at runtime time. In your case compiler can't be sure that setA would not be called from some other method.
Why do you need to set the value of final variable from a private method ?
You may do it in this way :
public class FinalTest {
private final Object a;
{
a=new Object();
}
//Constructor
public FinalTest() {
}
}
In this case the object will be initialized on every FinalTest initialization.

How can I know whether an instance of a class already exists in memory?

How can I know whether an instance of a class already exists in memory?
My problem is that don't want read method if exist instance of Class
this is my code
private void jButton (java.awt.event.ActionEvent evt) {
PNLSpcMaster pnlSpc = new PNLSpcMaster();
jtabbedPanel.addTab("reg",pnlSpc);
}
I want check instance of PNLSpcMaster of course I can check by static boolean but I think this way is better.
If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:
This is the common singleton idiom:
public class PNLSpcMaster {
/**
* This class attribute will be the only "instance" of this class
* It is private so none can reach it directly.
* And is "static" so it does not need "instances"
*/
private static PNLSpcMaster instance;
/**
* Constructor make private, to enforce the non-instantiation of the
* class. So an invocation to: new PNLSpcMaster() outside of this class
* won't be allowed.
*/
private PNLSpcMaster(){} // avoid instantiation.
/**
* This class method returns the "only" instance available for this class
* If the instance is still null, it gets instantiated.
* Being a class method you can call it from anywhere and it will
* always return the same instance.
*/
public static PNLSpcMaster getInstance() {
if( instance == null ) {
instance = new PNLSpcMaster();
}
return instance;
}
....
}
Usage:
private void jButton (java.awt.event.ActionEvent evt) {
// You'll get the "only" instance.
PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
jtabbedPanel.addTab("reg",pnlSpc);
}
Or directly:
private void jButton (java.awt.event.ActionEvent evt) {
jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}
For basic usages the Singleton Pattern works very well. However for more sophisticated usages it may be dangerous.
You could read more about it: Why singletons are controversial
I think you're after the singleton pattern.
Several factors would contribute to obtaining a reliable solution in Java, as opposed to C++.
The following example is unreliable, although it could provide you with a correct enough answer if you use the hasAtleastOne() method.
class Example {
private static int noOfInstances = 0;
public Example() {
noOfInstances++;
}
public static boolean hasAtleastOne() {
if(noOfInstances > 0)
return true;
else
return false;
}
protected void finalize() throws Throwable {
noOfInstances--;
}
}
The unreliability stems out of the fact that destructors are not available in Java, unlike C++. It is upto the garbage collector to release the memory consumed by an instance - the instance could still be floating in memory as an orphan since no other object references it. Hence, you never know whether an object is no longer being referenced.
Admittedly, that is theoretically different from being absent in memory at all, but you will have to wait for the finalize() method to be called before you know for sure that no such instance of the class is available. Finalizers come with a warning - they are not to be relied upon in time-critical applications, since it could be a factor of a few seconds to minutes between object orphaning and finalization; in short there is no guarantee that they could be called.
The Dispose Pattern
You could add more reliability to the solution by implementing the Dispose pattern. This also requires the client of the class to invoke the dispose method to signal that the instance is to be disposed off, so that the instance count can be reduced. Poorly written clients will make the solution unreliable.
There isn't a reasonable way to find out whether or not an instance of a particular class already exists.
If you need to know this information, create a static boolean field and set it from the constructor:
class MyClass {
private static bool instanceExists = false;
public MyClass() {
MyClass.instanceExists = true;
}
}
For classes that have a notion of identity, the Identity Map pattern applies.

Categories

Resources