Big list of events in GWT EventBus - java

In the examples provided by Google Web toolkit that they are adding the event handlers in one class only for the whole application.
As in - for Module1, 2 and 3 all events are registered in the main AppController class. I find this a bit monolithic and would not it better when we are using the MVP pattern that we declare a method called bind() in each of the Presenters that is as follows:
public class MyTestPresenter implements Presenter{
private void bind()
{
TestEvent.eventBus.addHandler(TestEvent.Type, new TestEventHandlerImpl() )
}
}
public class TestEvent
{
public static SimpleEventBus eventBus = new SimpleEventBus()
}
Query is:
If our application is huge - we would be using one eventbus to populate more than a thousand events in it - or would we design in such a way that we have separate instances of event bus for each module?.
Any cost of keeping the static event bus field. Any better design to give it's instance to all classes - passing it around to all classes through a constructor with each presenter class having it's reference seems a bit of clutter ...
What are activity and places in GWT when it comes to event handling? - Can someone give a pointer to how to understand the concept of activity/place in general?

Actually I dislike event bus implementation in GWT too. I've asked smt about before.
Now I develop some desktop application and I design eventBus in next way.
public interface EventBus {
void fireEvent(Event event);
<T extends Event> void addHandler(Class<T> eventType, Handler<T> handler);
interface Event {
}
interface Handler<E extends Event> {
void handle(E event);
}
}
So in usual Java application I would design it in other way, but here we should deal with issues connected with javascript and so on.
If our application is huge - we would
be using one eventbus to populate more
than a thousand events in it - or
would we design in such a way that we
have separate instances of event bus
for each module?.
I was thinking about this question too. I found that there are no any real advantages. For modularity you can separate visibility of your events. And there is some disadvantage. Suppose you should deal with several eventBusses in same class - code will be messy. Beside you should map this instances to classes somehow.
Any cost of keeping the static event
bus field. Any better design to give
it's instance to all classes - passing
it around to all classes through a
constructor with each presenter class
having it's reference seems a bit of
clutter ...
You can do both. In new Activity-Place framework it passed as parameter.
What are activity and places in GWT
when it comes to event handling? - Can
someone give a pointer to how to
understand the concept of
activity/place in general?
Activity it's like your old presenter but without low level view binding. Place just like history entry that used for specify windows.

Related

Is using an EventBus for simple method calling overkill?

I'm trying to create a UI library that basically holds a lot of methods and actions I typically use when building a layout. One example of such a function is managing the fab clicks. I have one fab in the main activity, and I change its function, icon, and visibility based on which fragment is loaded. I'm currently doing everything with interfaces as you can see here. It all works fine, but the only issue is that I have to make sure other users use activities and fragments that extend my interface.
Example
protected void hideFab() {
capsuleActivity().getFab().hide();
}
protected CActivityCore capsuleActivity() {
if (!(getActivity() instanceof CActivityCore)) {
throw new RuntimeException(s(R.string.capsule_activity_context_error));
}
return ((CActivityCore) getActivity());
}
If they don't need the functions for one fragment, they have to override a lot of my methods to make it not do anything. My other option could be to use an EventBus, and to just send various events whenever something is called and resolve it accordingly. That way, it no longer matters if users use my classes or not; if they only want the functions in a few fragments, they can just extend my fragment for those fragments and not worry about the rest.
My question is, would this be a nice and viable way of doing things, or is this moreso overkill as to how EventBuses should be used?
Another function I'm considering is to have the activity send a callback to the current fragment and have it run only if the fragment extends a certain class.
Current implementation:
#SuppressWarnings("unchecked")
protected <T extends Fragment & CFragmentCore> void onCurrentFragment(Class<T> clazz, #NonNull Current<T> callback) {
Fragment current = getSupportFragmentManager().findFragmentById(getFragmentId());
if (clazz.isInstance(current.getClass())) {
callback.onMatch((T) current);
}
}
But I could also instead use an EventBus with an event containing the class and a callback function.
Using an EventBus is a design choice. It has advantages and disadvantages, which you can easily find on Google.
There is no such thing as an "overkill" if you are able to simplify your code.
Apart from that, an EventBus is probably a good idea in your scenario, as it provides an easy way to manage View-Controller communication.

How to get EventBus instance in Composite extending class?

How to get com.google.web.bindery.event.shared.EventBus instance in com.google.gwt.user.client.ui.Composite extending class?;
I've readed: How to use EventBus for non-Presenter class in GWTP?, but I am looking for answer like:
BEST APPROACHES TO GWT DEVELOPMENT
I have widget that I would like to fire an event IndicatorEvent. But in this widget I don't have a handler for this event.
The handler is in other class. So to fire it I will use:
fireEvent(new IndicatorEvent("Custom Widget Message"));
Method fireEvent is avalible in com.google.web.bindery.event.shared;EventBus
public abstract void fireEvent(Event<?> event);
So I need an instance of EventBus in view class that extends Composite. This view doesn't have MVP stuff (presenters, uihandlers, etc.) it is simple one class element/widget.
What approach should I pick up?
Should I convert this to Presenter/View pair? (In gwtp presenters is EventBus reference from PresenterWidget class) And then using ui handlers, delegate execution from view to presenter?
Should I inject instance of EventBus into widget class?
Please help.
Any Widget can fire an event without using the EventBus.
If you know the recipients of this event, you can simply attach handlers directly to the recipients. To do that, you define this method in your composite widget:
public HandlerRegistration addIndicatorEventHandler(IndicatorEventHandler handler) {
return addHandler(handler, IndicatorEvent.TYPE);
}
and then in your other widget (recipient):
myCustomWidget.addIndicatorEventHandler(new IndicatorEventHandler() {
#Override
public void onIndicator(IndicatorEvent event) {
// do something
}
});
You will need to use EventBus if (a) there is no direct/easy link between the two widgets (firing event and event recipient), (b) there are many recipients, and/or (c) you do not want to create a dependency between parts of your code which contain event firing widget and event recipients.
We can assign only single component per view. So approach first doesn't make any sense as we creates lots of component/widgets for all small sections from particular view.
Second approach is comparatively more likable if we are already using some dependency injection framework like gin or dagger2.
I can add one more approach is to have simple setter method in component for passing eventBus instance from the parent class like presenter or controller where we are using/creating component object.
My conclusion will be it absolutely depends upon purpose and implementation of component. If we have interface-implementation or presenter-implementation kind of component stating some common behavior second approach is best suitable way. On the other hand if we have simple plane component serving just as small part of view, I will recommend third approach.

Best way to create an object listening framework?

Note, this question is not relevant to any other questions I've seen on this site. I have not found a duplicate.
I'm working on the framework for my 3D game engine, but before I go into the rendering stuff, I'm implementing utilities such as object listening for certain events.
I was thinking that using an interface called Listener and having any methods added with the annotation "Handler", and the method would be similar to this:
#Handler
public void onPlayerDeath(PlayerDeathEvent event) {}
This looks seemingly close to Bukkit's event handling used for enabling plugins to do certain actions on an event. I could then use this sort of framework to do achievements, task completion, and so forth.
I think there'd be a better way to do this, but this is the only way I can come up with.
If anyone could help out, it'd be great. Thanks.
You could either use custom events, as described here, or use Guava's EventBus.
I prefer Guava's EventBus as it provides a nice abstraction as to how events are handled. You can easily switch from sync to async handling without making too many changes.
i think factory pattern will be another choice. (http://en.wikipedia.org/wiki/Factory_method_pattern)
public class PlayerFactory {
public static Player createPlayer(){
//handle event
return new Player();
}
}
public class Player{
private Player(){}
}

Avoiding global state without cluttering constructors

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.

Objective-C delegates vs Java listeners

I've read a bunch of articles and readings on Objective-C delegates, trying to understand them. Coming from Java, they seem very much like Java listeners. For example, let's say I had a button in Java. When the button is pushed, I want something to happen. My code might look something like this:
ButtonListener myButtonListener = new ButtonListener();
someButton.addActionListener(myButtonListener);
...
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
Something like that. In objective-c it seems that I would do something along the lines of calling a setDelegate method for my button and passing it the "listener" as a delegate. The actual button class would then probably check if that delegate responded to some selector (ie. actionPerformed). If I'm thinking about this the right way, it does seem like delegates are just like listeners. Is that correct? Are there any major differences?
Thanks!
You're pretty much on the button there. The only real difference is delegates in obj-c generally implement multiple functions to perform various actions on events regarding the object they are delegating. For example, the UITextViewDelegate has the methods:
– textViewShouldBeginEditing:
– textViewDidBeginEditing:
– textViewShouldEndEditing:
– textViewDidEndEditing:
The only real difference I've found is you can't create your delegates inline, the way you can in java like:
someButton.setOnClickListener ( new View.OnClickListener {
#Override
public void onClick() {
//do stuff
}
});
they are similar, but not identical. a delegation pattern has broader definition, and often implementation defined tasks which can extend beyond listening alone. the tasks can include listening, or the delegate's implementation may be defined as listening (exclusively).
objc delegates are often used to avoid subclassing, and to serve as listeners or data providers. what a delegate does is defined by the protocol - it can serve as much more than a listener. so a delegate could be a data source/provider. it's just a means to offload implementation to another class, to remove from the class what is frequently customized, app-specific implementation.
NSButton/UIButton's already been specialized for this case via target+action mechanisms. you'd use target+action for this specific case.
Delegate is similar as listener or observer, protocol is similar as interface except protocol can define optional functions (aka messages). In Objective C, you can augment an existing class (without its source code) using category to adopt a protocol and make it a delegate, so that you don't need to create new anonymous inner classes at all. You can't do that in Java.
I think that a better Java analog to .NET delegates would be found in the java.util.concurrent pagkage: Callable, Future, Executor.

Categories