Should I use singleton for program state? - java

I have read this SO article, which tells us singletons are very very evil and should be avoided like an epidemic. It also tells us that singleton is just like a "global".
This makes me wonder if I really need something that acts like a program runtime state, would singleton be a bad idea?
For example I have a JavaFX application which can spawn many windows. Each of the windows have at least two stylesheets - one for controlling layout (like alignment etc), and another for theming.
The theme stylesheet can be switched out into another theme stylesheet at runtime, and it should globally affect all windows that are open at that instance. To me, it makes sense for me to make a singleton class that has a ObservableList of stylesheets, which all windows can bind their Scene's stylesheet property to.
Is this really a bad idea? If it affects testing, how exactly does it affect testing negatively? I understand each of the windows should be tested indepedently of each other, but the actual behavior is that all of them are supposed to look thematically the same. Furthermore, I don't think it should affect other areas which each window should really be independent of each other.
If this is really bad, what should be the approach to achieve the same result in the above example?

Actually you could get the same behavior using dependency injection.
In the main line of your application you'll instantiate a class like UIContext, and whenever you open a new window, you'll give that UIContext instance to its constructor.
All windows share the same UIContext instance, but it's not a singleton, it's just you've injected the whole UIContext into many other dependent classes.
That is, if you would need to implement tests, you could give a sample/fake UIContext to your windows with no hassle.

Related

Can I have a classloader find Java classes dynamically?

I want to select different implementations of classes dynamically, based on a runtime condition. Let's say I have a class with fully qualified class name C. My running system may have many definitions of class C, each of which is in its own jar. I have a runtime condition (held in a ThreadLocal) that tells which definition should be chosen.
I was asked in a comment to clarify the original requirement, so I will clarify the requirement as best I can. There are multiple teams writing software to contribute to this system - something like 4000 classes in many independent modules. What's more they can change over time. They are currently running in separate JVMs so there is no issue with classes overlapping. Now we are considering running them in the same JVM with multiple releases running simultaneously on the same JVM; which specific set of implementations used being differentiated by the ThreadLocal. So the original problem was how to allow a thread to at one time run one set of implementations and at another time run another.
I have a tomcat application that is currently using OpenJDK 8.
I believe I can write a custom ClassLoader that manipulates the classpath to choose the definition of C differently based on the ThreadLocal. But I'm afraid the results will be cached somewhere such as JVM Code Cache. Unless I can override that behavior too, the next time the class is needed, the runtime condition may have changed and the version in the cache would be wrong.
Is there any way to do what I need to do?
Well, the simple solution would be to NOT have multiple definitions of class C, but instead have 'class C1', 'class C2', etc (i.e. they don't overlap and can be simultaneously loaded) and then your runtime property just picks the right one as appropriate. That is way-way the easiest solution, so strongly consider it first. But it may not meet your needs.
If you truly need to have multiple separate implementations of a single 'class C', then what you are effectively talking about is a 'hot swap' scenario. Fortunately, Tomcat and other tools got good (with limitations) at hotswapping long-time-back. You likely already know this, but 'hot swapping' meets the need of a developer who codes 'class C', deploys it to a container, tries it out, realizes it has a glitch, makes a quick code edit and wants to run the modified code without relaunching the container. Hotswapping does this by basically overlaying the new implementation in the JVM. It only works up to a point because each 'redeploy' pollutes the 'class space' of the JVM and you eventually run of of 'class space memory' and/or the JVM starts going unstable. Depending on your needs and tolerances though, hotswapping might work.
The clean way to do what you want is to define C as an interface, then you can load and use any class that implements interface C

How to make a function accessible to certain classes only?

I am working on an API for a software so my users can extend it without modifying the source code. But, I want only certain functions to be accessed by certain classes for security reasons. Is there anyway to do this? Also, I have no code because I have no idea on how to do this.
Thanks! -Trent
I have two thoughts on this, one is that you can look at how Minecraft Forge created their plugin API.
Another way is to have a limited API between your core code and the actual plugins, but, you need to be careful of the platform. For example, if you write the core application in Java or C#, then I can use Aspect Oriented Programming (AOP) to bypass your security and have my code change the behavior of yours.
If you use functional programming (FP) languages, then you can protect more from this type of approach, if you also are not using languages on these platforms, but they are not perfect.
So, there is a trade-off between power and convenience, so how useful do you want your application to be, and how secure?
One possible solution that may work is if you go with something similar to Minecraft, though I doubt they do this, but, give a stub application to the user. They can extend it with plugins, and the interface functions they can modify are in the stub. When the program starts, the plugins are loaded, and the interface may be modified or extended, but, then the core program is pulled down and put into the stub, and then the actual program runs. The core program can be recompiled and manipulated so method names are changed, so reflection is harder to use, but taking this approach, and doing it well, would be hard.
BTW, I like Alex T's response, I just gave different terms to some of his, such as AOP instead of reflection and immutability is part of FP.
You mention jar, which means you are using something that runs on a JVM, so you may want to read up on AspectJ, as it can significantly alter the behavior of applications. You can have private methods, but I can put code that runs instead of yours, or change the parameters or the return value before or after the method is called.
To protect variables inside of classes, you can make them private, and accessible via getter and setter methods with varying levels of protection. This also applies to classes themselves; if you wanted to prevent the user from being able to instantiate a class, you could mark the class' constructor as protected to allow instantiation only within it's package.
If you wanted to hide the implementation details of a class altogether, you could declare the class as class X instead of public class X, which would hide methods from the API for standard development.
This will quickly get you the behaviour you're after, but there's an aspect of Java called reflection, which allows an executable Java program to analyze and manipulate it's own implementation; in this regard, no field or method is ever completely safe.
You can also safeguard variables by providing access to them via 'immutable' Objects; these are objects designed to forbid the caller from modifying the original source contents.

How to find all initializations of instance variables in a Java package?

I'm in the midst of converting a legacy app to Spring. As part of the transition, we're converting our service classes from an "instantiate new ones whenever you need one" style to a Springleton style, so I need a way to make sure they don't have any state.
I'm comfortable on the *nix command-line, and I have access to IntelliJ (this strikes me as a good fit for Structural Search and Replace, if I could figure out how to use it), and I could track down an Eclipse install, if that would help. I just want to make absolutely sure I've found all the possible problems.
UPDATE: Sorry for the confusion. I don't have a problem finding places where the old constructor was being called. What I'm looking for is a "bullet-proof" why to search all 100+ service classes for any sort of internal state. The most obvious one I could think of (and the only one I've really found so far) is cases where we use memoization in the classes, so they have instance variables that get initialized internally instead of via Spring. This means that when the same Springleton gets used for different requests, data can leak between them.
Thanks.
In Eclipse you can just right click on a variable/type and there is an option for References (or Declarations) -> (Workspace / Project / Hierarchy) which can help you find all instances of it neatly.
I would suggest using Eclipse's built in refactoring tool, it will do its best to change every instance associated to the class accordingly. I would go a step further and rename the class of that you want to change so, at worst case, a full compile would fail and you can easily fix any of those issues.

Modify android internal class(es) / Call Handling

Since the whole Android stuff is open source I was thinking about to do some minor modifications in a few internal classes from the com.android.internal.telephony package and of course then I would love if somehow my application could use the modified classes. I was thinking about replacing the classes with the original ones at runtime by using reflection or other kind of unknown java tricks :D ...maybe what I'm trying to do is impossible :( I don't know that's why I'm asking.
Note: The changes in the internal classes would not change their functionality in any way, its more about extending their functionality so even if other apps would use the modified versions it would not break them!
Why I want to do it? What I'm trying to achieve ?
Well i would like to modify the com.android.internal.telephony.gsm.CallTracker internal class so i could do proper call handling (call blocking etc..)
Maybe if you know about another way how to do what I want to I would like to hear about it :)
Note2: I know about the method when you handle the android.intent.action.PHONE_STATE, action , but its simply too late to react when this action is broadcasted. I'm really looking for a better solution even if that solution involve ugly hacks :)
As always thanks for all your replies...
You cannot do this :) I'll let you imagine what would happen if any application was allowed to freely replace core parts of the system. You can download the Android source code and you can modify it and you can upload the modifications to your phone (if your phone is rooted/unlocked) but you cannot apply such modifications with a simple app.
Changing a classes functionality (methods, byte code) after a class ha been loaded is impossible. Reflection/Invocation does not affect classes but static fields and instances only.
Your looking at a way to add additional methods or change existing methods of a running system, because the classes in question probably will be loaded already when your 'hacking' application is executed.
The only technical approach that I see is to change the classes in advance and deploy a modified system. I'm just ignoring possible licensing issues and security at the moment. But even with this way, your software would depend on a custom OS, a branch from some andorid version, disconnected from official updates, and you'd have to ask your customers to install a custom OS with, say, unknown features.
Sidenote - I'm very happy, that this is really impossible, otherwise my mobile would already be full of trojans, viruses, etc...
Romain is correct you can't and shouldn't try to change existing system classes.
That said, implementing call screening as you suggest should be possible by creating a replacement to the dialer application that handles phone calls.
Specifically the intent ACTION_ANSWER should be handled by your application, which could then either implement a dialer-like interface or open the dialer app (or any other call manager) explicitly.
There are actually ways to hack on Android framework classes, it just depends on which ones you want to hack.
You must extend the class you intent to hack on.
If you want to override package private methods and/or access package private variables you can put your class in the same package.
You can use reflection.
I've actually had to do this to work around bugs. Romain is correct, to an extent. It all depends on the structure of the code you are trying to hack on. You definitely can't hack on Android internals, but you can hack on other framework classes like Activity, View, etc.

Management of Java string resources

I'm working on a java SE 1.5+ swing application, in conjunction with others. I'm wondering what the best way of managing string resources is. I understand the principles behind resource bundles etc. I'd like to avoid having one property file for every class that needs a string, as this seems a bit of overkill. Especially when you have a lot of classes that may only make a single reference to a string (say in an error handler). On the other hand it makes it easier when collaborating with others as you reduce the risk of merge conflicts.
It seems particularly cumbersome to have to load resource bundles, every time you need to display simple user feedback, likewise in error handlers, when many classes are involved.
What is the most effective way to manage strings in a fairly large application with hundreds of classes, many of which aren't GUI related, but need to pass informative messages back up to the GUI when exceptions occur.
I'm using NetBeans which generally creates a property file for each GUI class, for all text relating to buttons, labels etc.
What makes you think you have to have a separate properties file for every class? Generally you only need a few (or just one!) properties file (per language, of course).
Just call ResourceBundle.getBundle() with appropriate parameters - you can use the same bundle from multiple classes.
EDIT: Having one set of property files per dialog etc makes it easier to see where any particular string is coming from, but it makes it harder to reuse the same messages etc. Quite where the right balance is will depend on the application.
JSR 296 Swing Application Framework has support for resource management (and it looks like will be part of Java 7). SAF aims to pre-build parts of a Swing app that many people frequently need while encapsulating best practices. You probably don't want to tie to it directly but its worth taking a look at what they do to see whether it gives you some ideas. If I recall, they use cascading resource bundles with well-defined naming conventions. The latter means you know where to look and the former means that you can reuse properties across some portion of your package hierarchy.
Many JSR 296 resources collected here.
This may be naive, but what about storing them in a database, either embedded or external? This might simplify management, and changing languages more configurable.
I'm going to implement something similar to Launchpad's translation platform this year:
https://launchpad.net/+tour/translation
In a nutshell:
Concurrent translation
Phrase suggestions based on previously-entered phrases
Policies, e.g. Partly restricted and structured: anyone can suggest translations, while trusted community members review and approve new work
UPDATE
Of course, this builds on top of ResourceBundle etc, but is a nice way to manage all them strings ;-)

Categories

Resources