How to call methods from other classes not having an instance? - java

How can I call a method from a class that is not an object within another class, and has nothing in common with this other class?
In my case:
class GridUI {
com.google.gwt.user.cellview.client.DataGrid grid;
public void refresh() {
dataGrid.redraw();
}
}
class SomeBackendService() {
public foo() {
//have to trigger refresh of a specific grid
}
}
One possibility might be to make the refresh() and grid static. But that's bad design, and I cannot use this approach as I want to use several implementations of GridUI.
So, how can I refresh a certain gridclass in my app from any service that does not contain this grid as an object??

Just create and fire an Event for it in your service and make your grid register for that Event. It's probably best to use an EventBus.
Using a static Map<String, Grid> as was suggested in the accepted answer will work but it's not proper. You risk making mistakes and it's not as easy to manage when the number of grids increases.
The EventBus approach is more work upfront but in the end it's a better approach. You'll be able to reuse the EventBus throughout your application. It really helps keep your coupling down. You'll also easily be able to get different objects act on the same Event with little effort.

Alternatively create a components registry (basically a Map<String,Grid>), then fetch the grid from SomeBackendService using its id as key in the registry. (I guess you know which grid you want to refresh, right?)
Be careful with registries though:
make sure they are thread safe if need be (probably true in an UI app)
they tend to fill up and leak memory if not properly handled

Sorry for not answering that long time, i was in vacation.
Interfaces are some kind of classes.
But they do not implement any method, they have empty method bodies.
Each class, which implements an interface usually MUST implement its methods.
In C# You would Do :
enter code here
interface IMyInterface
{
void PleaseImplementMe();
}
class clMyInterface :IMyInterface
{
void IMyInterface.PleaseImplementMe()
{
MessageBox.Show("One implementation");
}
}
end
Please let me know, whether this is what can help You or not.

Related

Starting method in all implemented classes

I'm kind of new to Java and have a rather simple question:
I have an interface, with a method:
public interface Interface_Updatable {
public void updateViewModel();
}
I implement this interface in several classes. Each class then of course has that method updateViewModel.
Edit: I instantiate these classes in a main function. Here I need code that calls updateViewModel for all objects that implement the interface.
Is there an easy way to do it combined? I don't want to call every method from every object instance separately and keep that updated. Keeping it updated might lead to errors in the long run.
The short form is: no, there's no simple way to "call this method on all instances of classes that implement this interface".
At least not in a way that's sane and maintainable.
So what should you do instead?
In reality you almost never want to just "call it on all instances", but you have some kind of relation between the thing that should trigger the update and the instances for which it should be triggered.
For example, the naming of the method suggests that instances of Interface_Updatable are related to the view model. So if they "care" about changes to the view model, they could register themselves as interested parties by doing something like theViewModel.registerForUpdates(this), the view model could hold on to a list of all objects that registered like this and then loop over all the instances and calls updateViewModel on each one (of course one would need to make sure that unregistration also happens, where appropriate).
This is the classical listener pattern at work.
But the high-level answer is: you almost never want to call something on "all instances", instead the instances you want to call it on have some relation to each other and you would need to make that relation explicit (via some registration mechanism like the one described above).
There is no easy way to call this method on all classes that implement this interface. The problem is that you need to somehow keep track of all the classes that implement this interface.
A possible object-oriented way to do this would be passing a list containing objects that are instances of classes that implement the Interface_Updateable interface to a function, and then calling updateViewModel on each object in that list:
public void updateViewModels(List<Interface_Updateable> instances) {
for(var instance : instances) {
instance.updateViewModel();
}
}

How to call onclick listener from another window in Vaadin

I would like to call my Java method from listener that is located under separate view/modal window and execute it. This way I would use my method without rewriting code. This is neccesary for me because in some circumstances, I can't get same results. So I would like to invoke onclick methods from separate modal window. How can be this done in Vaadin? I would need example code, really don't know how to do this?
I think you should hold a reference to the object you want to call its method. but a better way to do that is using an interface and pass the object using that.
public interface A {
public void theMethod ();
}
class B implements A {
public void theMethod (){
//do something here
}
}
you can pass a reference of B to the class that hold listener and from there you can call the theMethod you want to call.
class YourWindow(){
private A theInstance;
yourWindow(A instance)
{
theInstance = instance;
}
...
void onClick(){
...
theInstance.theMethod();
...
}
I suggest you study design patterns.
Design patterns represent the best practices used by experienced
object-oriented software developers. Design patterns are solutions to
general problems that software developers faced during software
development. These solutions were obtained by trial and error by
numerous software developers over quite a substantial period of time.
using Mediator and Observer is very helpful in such situation.

Access a static variable from a service

My application has a service and my MainActivity has a static variable :
public static boolean appIsPlaying = false;
And my service code is something like this :
MainActivity.appIsPlaying = false;
This code works well but I'm not sure that it's a true way. So, would you help me if there is a problem with this solution?
Thanks
I don't really agree with the people who say let's just use getters and setters for everything, and that's the solution. Your solution is simple, but effective. There are no problems with this way of communication between a service and an activity per se. This isn't some public API, so using public fields isn't a definite no-no.
Problems can only arise if you have certain requirements which you have to fulfill. This from of interaction is the simplest, therefore it can't do much. For example, if you want to listen to the event of changing the value, then you will have a problem because you just set the value and don't notify the activity.
If that's the case, then you can bind to the service, and implement more complex interaction. Listening to the value changes could be done by storing listeners in the service and notifying them when changes happen.
There is not really the way to do it, there are more appropriate ones and less so. You have to choose one of them depending on your needs.
Put your static variable in a utility class and create static getters and setters with required validations. Making the class Single Instance is also preferred but what you are doing right is not without problems.

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!

How to test an anonymous inner class that calls a private method

We have a bunch of classes that listen for events from the server and then respond to them. For example:
class EventManager {
private Set<Event> cache = new HashSet<Event>();
private EventListener eventListener = new EventListener() {
void onEvent(Event e) {
if (e instanceof MyEvent || e instanceof YourEvent) {
handleEvent(e);
}
}
}
public EventManager(ServerCommunication serverComm) {
serverComm.addListener(eventListener);
}
private handleEvent(Event e) {
// handle the event...
// ...
cache.add(cache);
// ...
}
}
Here's a made-up example of the kind of thing we are doing. Here are the problems I see:
I'd like to test handleEvent to make sure it's doing what it is supposed to but I can't because it's private.
I'd also like to check that something got added to the cache too but that also seems difficult since cache is a private member and I don't want to add a needless getter method.
I'd also like to test the code inside the anonymous class's onEvent method.
For now, what I did was move all logic from the anonymous class to the handleEvent method, and I made handleEvent package private (my unit test is in the same package). I'm not checking the contents of the cache although I want to.
Does anyone have any suggestion for a better design that is more testable?
I would probably extract a EventCache component. You can replace this for your test with an implementation that counts the cached events or records whatever is of interest.
I probably would not change the visibility of handleEvent. You could implement a ServerCommunication that just raises the event from the test case.
Well, there are two approaches here: black box and white box.
Black box testing suggests you should only test the publicly visible changes. Does this method have any observable effect? (Some things don't - caches being an obvious example where they improve performance but may otherwise be invisible.) If so, test that. If not, test that it isn't having a negative effect - this may well just be a case of beefing up other tests.
White box testing suggests that maybe you could add a package-level method for the sake of testing, e.g.
Cache getCacheForTesting()
By putting "for testing" in the name, you're making it obvious to everyone that they shouldn't call this from production code. You could use an annotation to indicate the same thing, and perhaps even have some build rules to make sure that nothing from production does call such a method.
This ends up being more brittle - more tied to the implementation - but it does make it easier to test the code thoroughly, IMO. Personally I err on the side of white box testing for unit tests, whereas integration tests should definitely be more black box. Others are rather more dogmatic about only testing the public API.
I assume your EventManager is a singleton, or you have access to the particular instance of the class you're testing.
1 - I suppose you can send events to your class. Your method is private, and nobody else can call it, then sending an event should be enough.
2 - You can access that through reflection, if you really need to. Your test would depend on a particular implementation.
3 - What would you like to test, actually? If you want to be sure that this method is called, you can replace the EventListener with another EventListener object through reflection (and eventually call the onEvent method of the first listener from your new listener). But your question seems to be more about code coverage than actual unit-testing.
Sometimes, when coming across private methods that I want to test... they are simply screaming to be public methods on another object.
If you believe that HandleEvent is worth testing in isolation (and not through onEvent processing), one approach would be to expose HandleEvent as a public method on new/different object.
Use this opportunity to break the code up into smaller more focussed (default access) classes. A test is just another client for the code.
Note that the anonymous inner class' onEvent method is actually accessible, so calling it should not be a problem.

Categories

Resources