Avoiding global state without cluttering constructors - java

I have a project that is in need of refactoring. It is a Java desktop SWT/JFace application with approximately 40 GUI components with major components controlling the lifecycle of minor components. I want to have good modular design with low coupling, but I can't find a way to avoid global state without having very long constructors.
For example, the current approach to internationalization in the software is something like:
public class Main {
public static void main(String[] args) {
MyMessages.loadMessages();
}
}
public class MyMessages {
private static ResourceBundle messages;
public static void loadMessages() {
messagesBundle = ResourceBundle.getBundle("messages", "en");
}
public static void getMessage(String m) {
return messagesBundle.getString(m);
}
}
public class SomeComponent extends Component() {
public void init() {
String textboxLabel = MyMessages.getMessage("someMessage");
}
}
Other places in the code use singletons (for data models), which makes it hard to analyse dependencies as the codebase grows.
An alternative approach would be to make MyMessages stateful and pass the instance of it all the way through the hierarchy of GUI components. To me this seems messy, error-prone and not worth the hassle compared to the perceived benefit.
What other ways are there to design this in a way that:
Doesn't rely on what are essentially global variables.
Makes the dependency relationships explicit.
Doesn't clutter the code with lengthy constructors.
Should I consider dependency injection frameworks, or is there another approach that doesn't seem overkill for a small desktop application?

Should I consider dependency injection frameworks, or is there another approach that doesn't seem overkill for a small desktop application?
For a small desktop app, I would recommend using the dependency injection design pattern, but hold off on using an industrial-strength DI framework.
In your code, the message helper classes are OK, but your SomeComponent class is definitely not DI friendly:
public class SomeComponent extends Component() {
public void init() {
String textboxLabel = MyMessages.getMessage("someMessage");
}
}
SomeComponent is now tied to MyMessages.
Instead use something like:
public class SomeComponent extends Component() {
public void setTextBoxLabel(String value) {
// implementation depends on requirements
}
public void init() {
// do something with all the properties that were set
}
}
Basically just add setters to your component. This the first part of DI. Make it so all your classes are loosely coupled and each class just trusts that someone is going to take care of setting all it's properties. No need for global state because everything a component needs is going to be injected into it.
Of course once you do this, your startup code is going to become a nightmare because you have to create all these objects and set all their properties and it's all tied into your application. At which point you start refactoring your startup code and create builders and/or factories which take care of creating the objects for you.
Let's say one of the components is initialized by a properties file. You create a builder that reads the properties file, instantiates the component, set the components properties and returns the instance. The component knows nothing about properties files. It just has some getters and setters which it knows will be set at startup.
Later on you decide to use XML as the file format - but for a different app, while still using properties file for the first app. No problem - create a new XML builder that reads the XML file and builds the component - but the actual GUI component remains unchanged because it is completely decoupled from how it gets initialized.
The key is to review creational design patterns and figure out which patterns (builder, factory etc) help you to reliably create your components while avoiding global state.

I would use global state. Especially if you are re-using views. IMHO opinion there is nothing wrong with having some sort of lookup for the various components that are going to get heavy usage from all over the app.
Note that if you use a DI framework, then chances are going to be using some sort of global state implicitly (granted, this is implementation dependent on the DI framework). Considering Spring for example, the ApplicationContext is a global object that itself is going to keep various components around and/or manage the components' lifecycles, depending on the configuration for the various beans.
Having global components is not necessarily a bad thing. If the tradeoff is huge constructor signatures and passing references around, I'd take the global references (well I'd put them in some sort of Application object) any day.

How about using java logger api...in addition StreamHandler class can be extended and set the output stream to components. You can also track the messages and associated classes and methods.

Related

Alternatives to field injection in state pattern

I'm developing a game and the game consists of states such as intro, menu, loading, game, etc... These states are swapped (or placed on top of each other) by the state manager which is invoked within the states themselves as each state has a reference to the manager like this:
class IntroState extends State {
//....
void update() {
showIntro();
if(done) {
stateManager.swapState(new MenuState())
}
}
//....
}
I believe that this is the "state pattern", but please correct me if I'm wrong.
Certain states have certain dependencies to things such as settings and input configuration which is sent to the game core module from platform specific modules (for example PC platform has keyboard controls while mobile has touch controls) and as such they aren't and shouldn't be static.
Initially I had those dependencies as constructor parameters and I passed them around but then I ran into cases where certain states, such as my loading state which only renders a typical loading screen while loading resources, need to have dependencies which they don't use just so they can be passed to states which do depend on them. And then the more features I added, the larger the dependency list would become.
This looked bad so I created a simple/naive field injector using reflection which works, however reflection is quite slow on android and I'm not particularly fond of reflection.
I've briefly considered Dagger2 DI framework, which doesn't use reflection and promises solid performance, but annotation generated code and heavy assembly boilerplate turned me away from it quite quickly.
I am thus looking for suggestions on how could I send/request certain dependencies for my states without constructor clutter or reflection based field injection.
I have also had this problem and found that the simplest solution is the best one: collect all of your game services into one class.
So rather than this:
State mainMenuState = new MainMenuState(inputService, renderingService, gameStateService);
State loadingState = new MainMenuState(renderingService, gameStateService);
// etc...
Do this:
State gameServices = new GameServices(inputService, renderingService, gameStateService);
State mainMenuState = new MainMenuState(gameServices);
State loadingState = new MainMenuState(gameServices);
// etc...
And GameServices looks something like this:
public final class GameServices {
public final InputService inputService;
public final RenderingService renderingService;
public final GameStateService gameStateService;
public GameServices(final InputService inputService,
final RenderingService renderingService,
final GameStateService gameStateService) {
this.inputService = inputService;
this.renderingService = renderingService;
this.gameStateService = gameStateService;
}
}
My initial concern with this was that now every type of state can access every game service. However, this never proved to be a problem in practice; your IDE can check class usage before making large changes.
As for cross-platform logic, simply abstract it behind interfaces. So for example, 'InputService' could have a different implementation on each platform.
One of the hardest parts of game programming is knowing when to stop engineering. Remember, you're delivering a game, not a library. :)

Which design pattern can I use to supply several methods that create "pre-configured" UI components

Disclaimer: I’m new to programming in Java and working with “extreme” OOP in general, so the answer to this might be really simple.
I’m creating a user interface in Vaadin, a Web application framework that supplies lots of useful components for me. Often, I’m not entirely happy with the default settings for these components.
For example, if I want every TextField component to fire value change events immediately when the field loses focus. There are similar settings for UploadField, TextArea, ComboBox etc. that I want to set on every instance of those classes.
Currently, what I have looks like this:
public class ConfiguredComponents {
public static TextField createConfiguredTextField(String caption) {
TextField field = new TextField(caption);
field.setImmediate(true);
field.setSomeOtherOptions();
...
return field;
}
public static UploadField createConfiguredUploadField(...) {
...
}
// etc.
}
This doesn’t feel like a class at all! It’s just a collection of static methods, which I’ve been told to avoid. Plus, I would like to place the logic for each component in a separate file. The configuration gets quite involved sometimes, and it just makes more sense that way: these are all very tiny self-contained bits of logic.
Here are the solutions I’ve considered:
Keep it simple: I could get rid of ConfiguredComponents, and just make one big package containing small factory classes. For example, myproject.ui.components.TextFieldFactory knows how to create a configured TextField and nothing more.
Pros:
The ugly ConfiguredComponents class is gone.
All of the logic is in separate files.
Cons:
There’s no single interface to the creation of my configured components; the only thing keeping them together is the fact that they’re in the same directory. Basically, I have to expose a lot of tiny classes, and there’s no single class or object managing them. (This intuitively feels like a pretty bad thing, but I don’t know if it really is.)
There’s also no way to override or extend static methods, so “faking” UI stuff for testing gets harder.
The Abstract Factory pattern: I make ConfiguredComponents into an AbstractComponentFactory that manages a lot of smaller factories.
Pros:
All of the logic is in separate files.
The logic that actually configures my components is fully behind-the-scenes.
Cons:
I would need an instance of AbstractComponentFactory every time I want to create a component anywhere in the code for my views. This means either keeping a singleton object, which has a lot of downsides, or creating a new AbstractComponentFactory() every time.
I have to write new code in two or three places, instead of just one, if I wish to add new components to my little “library”.
Some other design pattern I don't know about: I’ve read a bit about Builder, and Facade, which feel like they might apply here, but I don’t understand them very well.
How would you approach this design decision?
If your components can be inherited, then go ahead; for each component that you want to alter default settings, create a new derived class and config settings in constructors. Otherwise,
Abstract factory pattern is a good choice. I think you are misunderstanding about this pattern. AbstractComponentFactory is just an interface, it does not manage anything. This interface looks like this:
interface AbstractComponentFactory {
public TextField createTextFiled(...);
public UploadField createUploadFiled(...);
...
}
In your situation, I think you need only one implementation for this factory:
class MaurisComponentFactory implements AbstractComponentFactory {
public TextField createTextFiled(...) {
new ... config ... return;
}
public UploadField createUploadFiled(...) {
new ... config ... return;
}
...
}
As you said, we should neither use Singleton nor create new MaurisComponentFactory everytime. Instead, we should create only one instance in the main() method, and then try to inject this instance to every place that need to create components.
One possible approach i can think think is to use AbrstractFactory with Service Locator or Registry patterns
Since you have myriad objects that does not have complicated instantiation process (if so resort to build pattern), you create objects with Abstract Factory and register them in registry. And resolve them as needed where ever you are.
or you may resort simple IOC container where your entire application is wrapped around

Test methods inside UI class without UI creation

On my personal proyect, I want to make unit-tests but I'm having troubles with that.
My project does not have a big logic layer. The most important logic is the interaction between UI and entities. Some exception are calculate some day from payments and others things. Those things rarely change and, I want to start with things that change frecuently.
For example, please look this class:
public class TabClient extends JPanel{
private JDateChooser dateChooser = ...
private JButton update = ...
private JButton search = ...
private JButton delete = ...
//other components specific for this panel/component
private SomeOtherClassComponent subComponent = ...
private void initComponents()
{
update.addActionListener(ClientHandler.getUpdateListener());
//Others buttons
}
protected void mapFrom(Entitie entitie){
subComponent.mapFrom(entitie);
dateChooser.setDate(entitie.getDateFor...());
//specific components mappings
}
protected void mapTo(Entitie entitie){
subComponent.mapTo(entitie);
entitie.setDateFor...(dateChooser.getDate());
//specific components mappings
}
}
This class is an example of a Tab (TabbedPane item) from my project.
The class ClientHandler is like a Mediator pattern who creates (and returns) EventListener to encapsulate the UI events. Some events call methos from Tab component like mapFrom
I want to write tests for the methods but I don't know where to start. If test with UI frameworks or refactor clasess to separate some things (what to separate? and where?) or what to do to start with unit-tests.
Nowdays, the test is made by hand using the app.
What I have to do to start with unit tests?
What I should test? Methods that interact with UI or what?
In order to have an (easily) testable class, they need to have a high degree of cohesion, which may not be your case
You may want to consider moving any business logic to specific services or to the domain layer so that you can more easily test them.
As you mentioned the most import part of your application is the UI, I would try to mock the TabClient dependencies, simulate (say) the press of a button by calling its action methods and then checking the mocked objects to make sure the appropriate flow was invoked (ie, assert the right methods of the right objects were called). You may need to refactor your classes a bit to make possible to mock their dependencies. Likewise, I would write tests for all relevant UI objects.
I have never tested Swing applications to be honest, nevertheless I found the following links that might shed some light on your question (though some of them might require UI creation):
UISpec4J
Java World
Stack Overflow

How can I make an existing Java class/interface implementation a singleton?

Suppose I am using an ApplicationContext implementation in Spring.
ApplicationContext is an interface in the Java Spring Framework and I cannot change it.
How do I ensure that there can be only one instance of this implementation?
For eg. I have the following code -
public class ApplicationContextSingleton
{
private static ApplicationContext context;
private static int numberOfInstances = 0;
public static ApplicationContext getApplicationContext()
{
if(numberOfInstances == 0)
{
context = new ClassPathXmlApplicationContext("spring.xml");
numberOfInstances++;
}
return context;
}
}
This way, I can ensure that there is only one instance of ApplicationContext, provided it is obtained as follows -
ApplicationContext context = ApplicationContextSingleton.getApplicationContext();
But that doesn't stop another programmer from saying -
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
thereby creating a new ApplicationContext. How to prevent this from occuring?
You want to make ApplicationContext a singleton, so I'd override the class with my own custom class, make sure it appears first on the class path, and make it have a private constructor.
That is, if you're dead set on making it a singleton. There are better ways to solve your problem, as pointed out by other answers and comments.
Should note that it's usually a bad idea to override pieces of libraries, as it can be the cause of headaches later, especially when you try upgrading your framework version.
Unless somebody can come up with something reeeeeally creative, I don't think there's a way to do this. This would be similar to trying to make an int a singleton. Just not gonna happen, as you don't have any control over the usage of classes you didn't write. You're just going to have to trust your developers not to create a second context.
Alternatively, and I can almost promise this will be out of the question, but you could get the full source for spring, make some code changes to make the context a singleton, and then build it out yourself. Not a likely solution, but I felt the need to point it out anyway.
there is no way to do that because
ClassPathXmlApplicationContext is not implemented as Singleton pattern by Spring.
Inform every one that you have a utility method to access the context object and creating context using new is expensive.
Use an automated build system that builds your code whenever it is committed to your software repository.
Integrate tools into your build process like FindBugs or PMD. If these tools trigger certain conditions, fail the build and allow no artifacts to be generated.
Create a case in your integrated tool that looks for developers creating their own context.
So you can't stop them from doing it, but you can stop them from pushing such things into your dev, qa, and prod environments. This might seem like overkill, but this sort of process will help with hundreds of things your developers -can- do but shouldn't.
Josh Block suggests using an enum in Effective Java. This isnt a link to that book, but it shows his and the older way (alternative) way of doing it

Should I add support for PropertyChangeSupport and PropertyChangeListener in a Java bean for a web application?

I noticed that some people write beans with support for the Property Change observer pattern.
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
public class SampleBean implements Serializable {
public static final String PROP_SAMPLE_PROPERTY = "sampleProperty";
private String sampleProperty;
private PropertyChangeSupport propertySupport;
public ChartBean() {
propertySupport = new PropertyChangeSupport(this);
}
public String getSampleProperty() {
return sampleProperty;
}
public void setSampleProperty(String value) {
String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY, oldValue, sampleProperty);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertySupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertySupport.removePropertyChangeListener(listener);
}
}
However, I remember reading that observer pattern is not commonly used in web based MVC patterns, due to the stateless nature of web applications.
Is it a good practice to follow the above pattern in web application Java beans?
To be honest only bother if you are actually going to need the feature. Most web applications don't need PropertyChangeSupport. I can't actually remember seeing it being used in any web app that I've seen. I've only seen it being used a Swing application.
A typical bean in a web application is a pretty short lived object, prepared to service the single request and then cast off in to the void to be garbage collected. The main issue is that web applications are my there nature concurrent and multi user this doesn't lend it self to longer lived objects with listeners and events etc.
PropertyChangeListener is of a rather poor design anyway - all that magic string comparison. Much better go for a simple models with ChangeListener (or similar) and bring together with composite models.
Unless you are doing something interactive and COMETy, then it doesn't make a great deal of sense in a web application. You generally have a pull model where all the current information is bundled up in one go. It may make sense where you have caches.
You can even write desktop applications in the same manner as webapps. Any change (or series of changes) and sync the GUI. This turns out to be quite compact. Also the performance costs are moved from the critical time of major changes (such as opening a window) to be spread over non-critical time where you have cycles to burn.
1) Don't add property change support unless you know you will need it.
2) If your bean is just a value object with nothing much more than getters/setters/equals/hashcode, then consider using an AOP framework (I like Spring) to wrap the object with advices used to implement property change events/support. This way your bean stays unpolluted with logic that is only needed in certain contexts (usually the UI) and that might change in different contexts. This is a lesson I learned when I added property change support to all the domain beans for a particular app - the UI used it, but it confused the server team (not used there) and was just noise where it wasn't used.
I also agree that at times you don't need to listen to individual properties, it is enough to know if anything in the object has changed.

Categories