Organizing Actions in a Swing Application? - java

My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long.
Is it common to break actions into their own classes possibly within a sub-package called actions?
If not, how's this complexity usually tamed?
Thanks

If it is possible that your actions could be reusable (e.g., from keyboard shortcuts, other menus, other dialogs, etc.) and especially if they can work directly on the underlying model (rather than on the UI), then it is generally better not to have them as anonymous classes.
Rather, create a separate package, and create classes for each.
Often, it also makes sense to not instantiate these directly but rather have some sort of a manager that defines constants and initializes and returns sets of actions, so that you could, for example, offer different action sets at different versions or set certain actions only for internal releases.
Finally, check whether your actions can be refactored into a class hierarchy. They often can, which saves code replication, and also helps you add robustness (e.g., check for certain conditions before letting the action execute).

That's typically how I do it. Each action gets it's own class which has a reference to the "app" object so it can get to resources it needs. I usually have an action manager that holds all the actions so there's one place to access them as well as one place to update their enablement and stuff.
Eventually this also becomes unmanageable at which point you should start thinking about using an app framework like Eclipse RCP, the NetBeans framework, JIDE, etc. This is especially true if you want to support user-defined keymaps and stuff like that.

What I do is create a package (package tree actually) for action classes, then instantiate each class according to context. Almost all of my action classes are abstract with abstract methods to get the context (ala Spring).
public abstract class CalcAndShowAction extends AbstractAction {
//initialization code - setup icons, label, key shortcuts but not context.
public void actionPerformed(ActionEvent e) {
//abstract method since it needs ui context
String data = getDataToCalc();
//the actual action - implemented in this class,
// along with any user interaction inherent to this action
String result = calc(data);
//abstract method since it needs ui context
putResultInUI(result);
}
//abstract methods, static helpers, etc...
}
//actual usage
//...
button.setAction(new CalcAndShowAction() {
String getDataToCalc() {
return textField.getText();
}
void putResultInUI(String result) {
textField.setText(result);
}
});
//...
(sorry for any mistakes, I've written it by hand in this text box, not in an IDE).

Related

CQRS How to avoid repeating fields between command and event?

I'm implementing a project using CQRS and Event Sourcing. I realized that my commands and my events are nearly always the same.
Let's say I have a command CreatePost :
public class CreatePost implements Command {
private final String title;
private final String content;
}
The event fired from this command is the same :
public class PostCreated implements Event {
private final String title;
private final String content;
}
How do you handle that in your applications ?
EDIT : Of course I'm aware of basic OOP technics. I could create an abstraction having the common fields, but this question needs to be taken in the CQRS/ES context.
How to avoid repeating fields between command and event?
I wouldn't -- not until I absolutely can't stand it.
Fundamentally, commands and events aren't objects, they are messages - representations of state that cross boundaries. I think it's important that your in memory representation not lose sight of that.
One of the characteristics of message schemas is that they evolve over time, so you need to be aware of compatibility. And here's the kicker: events and commands evolve on different time scales.
Command messages are how your domain model communicates with other processes; changes to that part of the API are driven by exposing/deprecating functionality.
But in an event sourced world, events are messages from previous versions of the domain to the current version. They are part of the support we need to deploy new models that resume work from where the old model left off.
So I would keep commands and events separate from one another - they are different things.
If you are seeing a lot of duplication in the fields, that may be a hint that there's some value type that you haven't yet made explicit.
CreatePost
{ Post
{ Title
, Contents
}
}
PostCreated
{ Post
{ Title
, Contents
}
}
Simply implement a model for your Post, i.e.:
public class PostModel {
private String title;
private String content;
// Add get/set methods
}
Then re-use this in both your events and commands.
Just compiling this answer from the discussion we had in comments.
Compose, don't inherit
I would definitely not use inheritance in a situation like this because it will just add unnecessary complexity, also there is no behavior to inherit there.
Another option is to have a well-defined contract for your commands and events. That is to have two interfaces — IPost and IEvent — and implement those in the commands and events.
Regarding naming: we all know that naming is hard, so you should choose names wisely, according to your business or technical language/vocabulary requirements.
Why split into two interfaces?
Because a command usually carries more information required for its handler than an event carries for its event handler, event handlers should be kept as thin as possible. It's better to carry only the needed payload.
Closing words
Separating commands and events is a must, since commands are representing an operation that's happening now, whereas events are representing actions that happened in the past. They might usually be an outcome of a command, indicating to the outside world — from the viewpoint of a bounded context — that something happened inside your current BC.
How to avoid repeating fields between command and event?
Just don't. The cost of dependency + risk of wrongful mutualization are higher than the maintenance gain. You can live with that duplication, just like you probably live with duplication between your domain model, view model, query model, etc. today.
You can use whatever you want as long as it is just an implementation detail.
In PHP I use a lot traits for this kind of reusability. You can use even inheritance but the clients (the code that uses those classes) should not depend on the base class; it would be best if they even don't find out that your event and command class share something but I don't have enough Java experience to tell you how to do it.
P.S. I would not go with creating interfaces, as I specified above, this should be just an implementation detail.
I've run into this, and almost universally I've not found a case where the event needed different properties than the command for a particular domain action. I definitely find the menial copy/paste duplication of property getters/equals/hashCode/toString pretty annoying. If I could go back, I'd define a marker interface Action and then
interface Command<T extends Action> {
T getAction();
// other properties common to commands of all action types...
}
class AbstractCommand<T extends Action> implements Command<T> {
public T getAction() { ... }
// other properties...
}
interface Event<T extends Action> {
T getAction();
// other properties common to events of all action types...
}
class AbstractEvent<T extends Action> implements Event<T> {
public T getAction() { ... }
// other properties...
}
Then for each domain action, define concrete implementations.
class ConcreteAction implements Action {
// properties COMMON to the command and event(s)...
}
class ConcreteCommand extends AbstractCommand<ConcreteAction> { ... }
class ConcreteEvent extends AbstractEvent<ConcreteAction> { ... }
If the command and event action properties need to diverge for some reason, I'd put just those particular properties in the ConcreteCommand or ConcreteEvent classes.
The inheritance model here is very simple. You may only rarely need to do anything more than extend the abstract classes with nothing more to implement than the common Action. And in the case where there are no properties needed for the Action, just define a class EmptyAction implements Action implementation to use in those types of commands and events.

Where to put common attributes and method implementations if I can't change the parent class?

I am working with JavaFX, specifically with:
javafx.scene.shape.Rectangle
javafx.scene.shape.Ellipse
javafx.scene.shape.Line
I need additional methods so I created the interface MoreFunctions. I created three new classes that inherit from above classes and implement MoreFunctions, i.e.:
public class MyRectangle extends javafx.scene.shape.Rectangle implements MoreFunctions {
...
}
This is fine as long as MyRectangle and MyEllipse have different implementations of the additional methods. But where do I put methods that have the same implementation? I can't change the parent class since I can't modify the framework. Is a default interface method the only (feasible) way to go? But then what about common attributes that methods rely on?
EDIT: An example of a common method
public void toggleSelection() {
if (!selected) {
setStrokeWidth(5);
setStroke(Color.RED);
selected = true;
}
else {
setStrokeWidth(0);
selected = false;
}
}
This requires
private boolean selected;
It sounds a bit like you are looking for mixin functionality, which doesn't really exist in Java. You might be able to simulate mixins using Java 8 functionality or via a special purpose 3rd party mixin support library.
However, things might be a bit more straight-forward for other developers if you use either pass through methods or composed objects. Each of your Shape subclasses can delegate the functionality to common classes implementing particular functionality (e.g. selection toggling), rather than relying on new language features like default methods.
You can see the difference in inheritable or inherent functionality versus a delegated or compositional approach by examining the way selection capability is handled in various JavaFX classes. ToggleButton has a selectedProperty, so it is directly implementing the selection functionality. However, ListView has a selectionModelProperty, so the selection modeling capability of the ListView is delegated to an associated class, rather than directly implemented in the ListView itself.
Of course, things get a little complicated when you have MVC style systems like JavaFX Controls, but you probably don't need to code your system to that level of complexity. Though, you might want to examine how CSS support is added to controls and consider implementing functions such as styling a selected shape using similar CSS based support, rather than coding the style directly in code.

Java make components talk to each other

Let's say I have a gui, and the gui is composed of two parts where each part has its own class.
So one class contains a JLabel.
And second class contains a text field with a submit button.
How would I go about making those two components talk to each other?
This is of course a simple example, but if I have two classes where I use one for submitting data, and one for showing the submitted data, then how do I make the two components communicate?
Some thoughts:
Don't add such bindings to the GUI classes, look for a pattern like MVC
Unidirectional change propagation (input -> output as in your example) is usually never problematic, but in many cases, full synchronization of editable component groups is required. So one may keep that in mind during development of the simple case for good reusability of any custom class or interface.
Avoid infinite circular updates with a flag, rather than with a comparison of component values.
Whatever you do, keep things separated and whatever pattern you use, don't add bidirectional references (e.g. among GUI class <-> controller)
Regardless of MVC, there could be a controller class, getting all necessary references to the UI objects (i.E. JPanels with nested JTextFields and JLabels, etc.) via constructor.
On construction, that controller can attach itself to those nested components.
The controller should preferably contain nested, inner or perhaps anonymous classes for implementing the listener interfaces, rather than adding the listener interface to the controller itself. First, to encapsulate these listeners and second, to avoid the event source distinction, if the same interface needs to be implemented for multiple components (sources). These listener implementations (perhaps pretty generic PropertyChangeListener's) could then act as, or use mediator objects (as mentioned), for updating other components.
If you have a submit button, you can add an action listener to it. When clicked you can call a method in your other class that will receive the string and then display it on your JLabel. However having multiple classes for different components isn't usually a good idea, and having a MVC like what Sam said is much better.
Class with JTextArea
//Have this object created
JLabelClass JLC = new JLabelClass();
//When submit button is clicked run this
JLC.displayText(JTextArea.getText());
Inside Class with JLabel
//add this method
public void displayText(String text){
JLabel.setText(text);
//Refresh Gui and display stuff....
}
Hope this helped... Sorry about the formatting I'm still new to StackOverflow

Is it an ok practice to have a member ClientBundle in a containing ClientBundle?

In my app, I have MyAppResources, which will mainly contain custom styles for the app. I am thinking about what is a good way to go about applying custom styles to standard widgets, such as a CellTable, along with custom styles on the layout and custom widgets?
My question:
Since MyAppResources is a singleton (it doesn't have to be, as mentioned in other posts), but CellTableResources isn't, and CellTableResources is a member of this instance that is an interface also extending ClientBundle, will a proxy 'CellTableResources' be created on every MyAppResources.INSTANCE.cellTableResources().foo()?
If so, could I create a MyAppResources.CELLTABLE_RESOURCE_INSTANCE to get around this? Or would the creation of the proxy be negligible, even if there are plentiful calls to MyAppResources.INSTANCE.cellTableResources().#?
Secondly, more of a discussion question: what is best practice in regards to using multiple ClientBundles in this case? Should I instead use CellTableResources seperately (remove it from MyAppResources), using GWT.create(CellTableResources.class); in a widget that needs it (or using a singleton like I have for MyAppResources)?
MyAppResources:
public interface MyAppResources extends ClientBundle {
public static final MyAppResources INSTANCE = GWT.create(MyAppResources.class);
#Source("MyAppStyles.css")
public MyAppCssResource css();
public CellTableResources cellTableResources();
}
CellTableResources:
public interface CellTableResources extends CellTable.Resources {
interface CellTableStyle extends CellTable.Style {
}
#Override
#Source({ CellTable.Style.DEFAULT_CSS, "CellTableStyles.css" })
CellTableStyle cellTableStyle();
#Source("green_light.png")
ImageResource getGreenLight();
//...
}
Thank you for reading.
Multi-part question, so I'm going to try to hit this in several parts:
What is the cost of GWT.create()?
Most of the GWT class is 'magic', things that you cannot wrote for yourself in other ways, as they call on the compiler to fill in specific details for you. These are often different when running in dev mode vs compiled to JS.
In the case of GWT.create, it turns out that this is compiled out to new - it is used just to create new instances. So what is the cost of a new instance versus a singleton? This depends entirely on the object being created. If there are no fields in the object, then the cost is essentially free - in fact, the compiler may choose to actually remove the constructor call, and rewrite all later methods as static anyway!
This is what happens in most cases - GWT.create should be considered to be very cheap, unless you are doing something silly like calling it within a loop that is run many times.
What happens when I list a ClientBundle method inside another ClientBundle?
Well, what happens when you list anything inside a ClientBundle?
Anything that can be listed in a ClientBundle must be annotated with #ResourceGeneratorType, indicating how to generate that type. For example, here is ImageResource:
/**
* Provides access to image resources at runtime.
*/
#DefaultExtensions(value = {".png", ".jpg", ".gif", ".bmp"})
#ResourceGeneratorType(ImageResourceGenerator.class)
public interface ImageResource extends ResourcePrototype {
//...
It calls on ImageResourceGenerator to create images as needed. Any class described in that annotation must implement com.google.gwt.resources.ext.ResourceGenerator, which describes how to get ready to work, how to create necessary fields, how to initialize them, and how to finish up.
So what does this look like for ClientBundle itself? Check out com.google.gwt.resources.rg.BundleResourceGenerator - it is a very simple class that just calls GWT.create() on the type of the method given. So, predictable, this means that those 'child' ClientBundles are created via GWT.create, more or less the same as you might otherwise do.
Okay, what does that mean in this specific case?
It turns out that ClientBundles instances don't have fields where they track newly created objects from, but instead have static members that they use instead - effectively singletons. This means that once you have called a method once, the instance it returns will be the same instance created as the next time you call it. Two different ClientBundles with the same contents will of course then keep two different copies of the objects, but it doesn't matter how many times you create a ClientBundle - its internals will always be the same.
Anything else?
Yep! Remember that you are dealing with interfaces here, not classes, so you can actually extend more than once at once!
public interface MyAppResources extends
ClientBundle,
CellTable.Resources,
CellTree.Resources {//etc
//...
Now, if two interfaces describe the same methods you may have problems, but if not, this can provide an advantage when generated sprited images. Each individual ClientBundle will draw on its own pool of images when preparing them for use - if you have a ClientBundle within a ClientBundle, they won't work together to sprite images into bigger pieces. To get that, you need to make just one ClientBundle type. This may not matter in your particular case, but I figured it was also worth mentioning.

Is this a good way to handle events in Java?

I'm making a game in Java, and I think I have a good idea of how to handle events. Does this sound right?
A Window class--the view. It's a representation of the World at the current moment.
There's also a Game class -- the controller. (The model's implementation is irrelevant for this question).
The Window class doesn't care about events. Therefore, the event listener simply dispatches them to the Game class (via something like game.notifyEvent(Event e);.
The Game class, upon receipt of this event, will start updating values and the like, and some variables (like the location of the player) will be changed. At this point, it uses its class variable Window w to notify it of the changes (via various methods such as w.movePlayer(Position p), etc.
SO, does this sound like something that would make sense to you?
Yes, what you're doing makes some sense. I find it much more intuitive to have the Window listen to the Game than the other way round. I've also found that Java is much more maintainable if you separate out the different areas of the GUI and pass the Game into each of them through a fine-grained interface. I normally get the GUI elements to listen to changes in the model, and request any interactions to be dealt with. This way round makes for easier unit testing, and you can replace the GUI with a fake for acceptance testing if you don't have a decent automation suite, or even just for logging.
Usually splitting up the GUI results in some panels purely listening, and some panels purely interacting. It makes for a really lovely separation of concerns. I represent the panels with their own classes extending JPanel, and let the Window pass the Game to them on construction.
So for instance, if I have two panels, one of which displays the results and one of which has an "Update" button, I can define two interfaces: INotifyListenersOfResults and IPerformUpdates. (Please note that I'm making role-based interfaces here using the IDoThisForYou pattern; you can call them whatever you like).
The Game controller then implements both these interfaces, and the two panels each take the respective interface. The Update interface will have a method called RequestUpdate and the Results interface will have AddResultsListener. Both these methods then appear on the Game class.
Regardless of whether you get the Game to listen to the Window or the Window to the Game, by separating things through interfaces this way you make it much easier to split the Game controller later on and delegate its responsibilities, once things start getting really complicated, which they always do!
I think you should implement the Observer design pattern (http://en.wikipedia.org/wiki/Observer_pattern) without using .NET's events. In my approach, you need to define a couple of interfaces and add a little bit of code. For each different kind of event, create a pair of symmetric interfaces
public interface IEventXDispatcher
{
void Register(IEventXHandler handler);
void Unregister(IEventXHandler handler) throws NotSupportedException;
}
public interface IEventXHandler
{
void Handle(Object sender, Object args);
}
X denotes the specific name of event (Click, KeyPress, EndApplication, WhateverYouWant).
Then make your observed class implement IEventDispatcher and your observer class(es) implement IEventHandler
public class Dispatcher implements IEventXDispatcher, IEventYDispatcher ...
{
private List<IEventXHandler> _XHandlers;
private List<IEventYHandler> _YHandlers;
void Register(IEventXHandler handler)
{
_XHandlers.Add(handler);
}
void Unregister(IEventHandler handler) throws NotSupportedException
{
//Simplified code
_XHandlers.Remove(handler);
}
private MyMethod()
{
[...]
for(IEventXHandler handler: _XHandlers)
handler.Handle(this, new AnyNeededClass())
[...]
}
//Same for event Y
All the code is hand-written. I have little experience with Java but I believe this pattern may help you!

Categories

Resources