Alternatives to event observer - java

I am building an a application that uses the event observer pattern to allow points in the system to be extended easily by 3rd party vendors who wish to add their own functionality.
This works well however it relies on 1 thing:
I must decide which points in the system vendors may wish to extend the system and trigger an event in that particular point in the flow.
It is entirely plausible that a vendor may wish to extend a different part of the system that I have not triggered an event from.
What are the alternatives here, to allow the vendor to extend the system from any point in the system they choose - or as close to that goal as possible - using something similar to event observer i.e. the can simply hook into the system where the choose to?

Okay, so you need to do two things. The first is to go out and find some real clients, and talk to them. Where do they need extensions? They know that much better than you do. The second thing is to err on the side of not providing hooks. You can always add them later, but you will have to support anything that you put out, even if it's not used.
As #Holger said, there is no way to provide arbitrary hooks to any point in your system, and it's really not desirable for you to do so. That's a maintenance nightmare.

Holger mentioned already that AOP may help you. You simply annotate your code with your custom annotations and let your customers define their own aspects (they will be required to recompile the entire code base). For example:
#Data
public class Records {
#Saving
public void add(Record rec) {
// your code
}
}
Later, your customer may say "I want to be triggered every time anyone is saving some data". He will have to define his own "aspect" with this custom "shortcut" (pseudo code):
#Aspect
public class OnSaving {
#Before("execution(* #Data #Saving(..))")
public void shortcut(JoinPoint pnt) {
// your customer's code
}
}
Your source code won't be changed, just recompiled. I assumed AspectJ usage.

Related

What do i do if need to change a libraries functionality

I have a class in a Java Library(open-m3u) that I need to change just slightly.
The functionality is easy to implement on my own without using the library. The library is open-source so i have access to all of its code. The class is made in such a way that inheriting it or even changing that small part is not possible. My question is should I copy that class and all the classes that it depends on and put them in my own code base and change the functionality or should implement the functionality myself. Or is there another option?
The functionality is easy to implement on my own without using the
library.
IMHO, then that's the way to go. Your other options are:
Build the functionality around the library: you say that's not possible in your case.
Create a branch of the library in your own source control system. That means you'll have to keep that repository in sync with the library maintainers, which means a permanent burden. And you have to check what the library's license says about forking.
Copy the relevant parts into your code base and do the modifications there. Then you won't profit from future enhancements or bug fixes, but still have to maintain code that was created and architected by someone else, and doesn't exactly fit your requirements. And you have to check what the library's license says about copying parts into a foreign code base.
They all have their drawbacks.
As a general remark: in 25 years of professional software development, I've seen both successful usages of external libraries as well as complete failures. Some times, we invested more time into evaluating existing libraries (and then finding out that nothing matched) than we needed for implementing the project-specific solution on our own.
And every library you can do without, makes config management and rollout easier.
Decorator pattern allows you to add new functionality to existing object.
If java library you use has any class like this:
public class LibraryClass implement ILibraryInterface {
public void someMethod() {
...
}
}
Then you can create Decorator class:
public class LibraryClassDecorator implement ILibraryInterface {
private LibraryClass libObj;
public LibraryClassDecorator(LibraryClass libObj) {
this.libObj = libObj;
}
public void someMethod() {
libObj.someMethod();
// here you can do whatever you want.
// Add some additional logic
// transform result value if there is some
}
}
Note: you have to implement the same interface to follow Liskov substitution principle
A solution will be to make a class that extends the one you wanna change and overide the part you wanna change

Using the Command Pattern with Parameters

I have a ReloadableWeapon class like this:
public class ReloadableWeapon {
private int numberofbullets;
public ReloadableWeapon(int numberofbullets){
this.numberofbullets = numberofbullets;
}
public void attack(){
numberofbullets--;
}
public void reload(int reloadBullets){
this.numberofbullets += reloadBullets;
}
}
with the following interface:
public interface Command {
void execute();
}
and use it like so:
public class ReloadWeaponCommand implements Command {
private int reloadBullets;
private ReloadableWeapon weapon;
// Is is okay to specify the number of bullets?
public ReloadWeaponCommand(ReloadableWeapon weapon, int bullets){
this.weapon = weapon;
this.reloadBullets = bullets;
}
#Override
public void execute() {
weapon.reload(reloadBullets);
}
}
Client:
ReloadableWeapon chargeGun = new ReloadableWeapon(10);
Command reload = new ReloadWeaponCommand(chargeGun,10);
ReloadWeaponController controlReload = new ReloadWeaponController(reload);
controlReload.executeCommand();
I was wondering, with the command pattern, with the examples I've seen, other than the object that the command is acting on, there are no other parameters.
This example, alters the execute method to allow for a parameter.
Another example, more close to what I have here, with parameters in the constructor.
Is it bad practice/code smell to include parameters in the command pattern, in this case the constructor with the number of bullets?
I don't think adding parameters into execute will be bad design or violate command pattern.
It totally depends on how you want to use Command Object: Singleton Or Prototype scope.
If you use Prototype scope, you can pass command parameters in Constructor methods. Each command instance has its own parameters.
If you use Singleton scope (shared/reused instance), you can pass command parameters in execute method. The singleton of the command should be thread safe for this case. This solution is a friend of IoC/DI framework too.
The very purpose of this pattern is to allow to define actions, and to execute them later, once or several times.
The code you provide is a good example of this pattern : you define the action "reload", that charges the gun with an amount of bullets=10 ammunition.
Now, if you decide to modify this code to add bullets as a parameter, then you completely lose the purpose of this pattern, because you will have to define the amount of ammunition every time.
IMHO, you can keep your code as it is. You will have to define several ReloadWeaponCommand instances, with different value of bullets. Then you may have to use another pattern (such as Strategy) to switch between the commands.
Consider a case you have 95 bullets in hand in starting, and you have made 9 commands with 10 bullets and 1 command with 5 bullets. And you have submitted these commands to Invoker, now invoker doesn't have to worry about how much bullets are left. He will just execute the command. On the other hand if invoker has to provide the no of bullets at run time then it could be the case supplied number of bullets are not available.
My point here is that Invoker must not have to worry about any extra information needs to execute the command. And as mentioned in wiki "an object is used to encapsulate all information needed to perform an action or trigger an event at a later time"
Using the Command Pattern with Parameters
Consider the related 'Extension Patterns' in order to hold to a Top-Down Control paradigm 'Inversion of Control'.
This pattern, the Command Pattern, is commonly used in concert with the Composite, Iterator, and Visitor Design Patterns.
Commands are 'First Class Objects'. So it is critical that the integrity of their encapsulation is protected. Also, inverting Control From Top Down to Bottom Up, Violates a Cardinal principle of Object Oriented Design, though I see people suggesting it all of the time...
The Composite pattern will allow you to store Commands, in iterative data structures.
Before going any further, and while your code is still manageable, look at these Patterns.
There are some reasonable points made here in this thread. #Loc has it closest IMO, However, If you consider the patterns mentioned above, then, regardless of the scope of your project (it appears that you intend to make a game, no small task) you will be able to remain in control of lower-level dependency. As #Loc pointed out, with 'Dependency Injection' lower class Objects should be kept 'in the dark' when it comes to any specific implementation, in terms of the data that is consumed by them; this is (should be) reserved for the top level hierarchy. 'Programming to Interfaces, not Implementation'.
It seems that you have a notion of this. Let me just point out where I see a likely mistake at this point. Actually a couple, already, you are focused on grains of sand I.e. "Bullets" you are not at the point where trivialities like that serve any purpose, except to be a cautionary sign, that you are presently about to lose control of higher level dependencies.
Whether you are able to see it yet or not, granular parts can and should be dealt with at higher levels. I will make a couple of suggestions. #Loc already mentioned the best practice 'Constructor Injection' loosely qualified, better to maybe look up this term 'Dependency Injection'.
Take the Bullets for e.g. Since they have already appeared on your scope. The Composite Pattern is designed to deal with many differing yet related First Class Objects e.g. Commands. Between the Iterator and Visitor Patterns you are able to store all of your pre-instantiated Commands, and future instantiations as well, in a dynamic data structure, like a Linked List OR a Binary Search Tree even. At this point forget about the Strategy
Pattern, A few possible scenarios is one thing, but It makes no sense to be writing adaptive interfaces at the outset.
Another thing, I see no indication that you are spawning projectiles from a class, bullets I mean. However, even if it were just a matter of keeping track of weapon configurations, and capacities(int items) (I'm only guessing that is the cause of necessary changes in projectile counts) use a stack structure or depending on what the actual scenario is; a circular queue. If you are actually spawning projectiles from a factory, or if you decide to in the future, you are ready to take advantage of Object Pooling; which, as it turns out, was motivated by this express consideration.
Not that anyone here has done this, but I find it particularly asinine for someone to suggest that it is ok to mishandle or disregard a particular motivation behind any established (especially GoF) Design pattern. If you find yourself having to modify a GoF Design pattern, then you are using the wrong one. Just sayin'
P.S. if you absolutely must, why don't you instead, use a template solution, rather than alter an intentionally specific Interface design;

Using Proxy pattern to write a server a good idea?

For a school project, I need to write a simple Server in Java that continuously listens on an incoming directory and moves files from this directory to some place else. The server needs to log info and error messages, so I thought I could use the Proxy pattern for this. Thus, I created the following ServerInterface:
public interface ServerInterface extends Runnable {
public void initialize(String repPath, ExecutorInterface executor, File propertiesFile) throws ServerInitException;
public void run();
public void terminate();
public void updateHTML();
public File[] scanIncomingDir();
public List<DatasetAttributes> moveIncomingFilesIfComplete(File[] incomingFiles);
}
Then I've created an implementation Server representing the real object and a class ProxyServer representing the proxy. The Server furthermore has a factory method that creates a ProxyServer object but returns it as a ServerInterface.
The run-method on the proxy-object looks like this:
#Override
public void run(){
log(LogLevels.INFO, "server is running ...");
while( !stopped ){
try {
File[] incomingContent = scanIncomingDir();
moveIncomingFilesIfComplete(incomingContent);
updateHTML();
pause();
} catch (Exception e) {
logger.logException(e, new Timestamp(timestampProvider.getTimestamp()));
pause();
}
}
log(LogLevels.INFO, "server stopped");
}
The functions that are called within the try statement simply log something and then propagate the call to the real object. So far, so good. But now that I've implemented the run-method this way in the proxy object, the run-method in the real object becomes obsolete and thus, is just empty (same goes for the terminate-method).
So I ask my-self: is that ok? Is that the way the proxy pattern should be implemented?
The way I see it, I'm mixing up "real" and "proxy"-behaviour ... Normally, the real-server should be "stuck" in the while-loop and not the proxy-server, right? I tried to avoid mixing this up, but neither approaches were satisfying:
I could implement the run-method in the real object and then hand over the proxy object to the real object in order to still be able to log during the while-loop. But then the real object would do some logging, which is I tried to avoid by writing a proxy in the first place.
I could say, only Proxy-Server is Runnable, thus deleting run and terminate from the Interface, but this would break up the Proxy pattern.
Should I may be use another design? Or I am seeing a problem where there is none?
You're definitely thinking in the right way. You've hit upon an interesting notion.
Features like logging, as you've described, are an example of what we call cross-cutting concerns in Aspect Oriented programming.
A cross-cutting concern is a requirement that will be used in many objects.
. . therefore, they have the tendency to break object oriented programming. What does this mean?
If you try to create a class that is all about moving files from place A to place B, and the implementation of a method to do that first talks about logging (and then transactions, and then security) then that isn't very OO is it? It breaks the single responsibility principle.
Enter Aspect Oriented Programming
This is the reason we have AOP - it exists to modularize and encapsulate these cross-cutting concerns. It works as follows:
Define all the places where we want the cross-cutting feature to be applied.
Use the intercept design pattern to "weave" in that feature.
Ways we can "weave" in a requirement with AOP
One way is to use a Java DynamicProxy as you've described. This is the default in for example the Spring Framework. This only works for interfaces.
Another way is to use a byte-code engineering library such as asm, cglib, Javassist - these intercept the classloader to provide a new sub-class at runtime.
A 3rd way is to use compile-time weaving - to change the code (or byte-code) at compile-time.
One more way is to use a java agent (an argument to the JVM).
The latter two options are supported in AspectJ.
In Conclusion:
It sounds as though you're moving towards Aspect Oriented Programming (AOP), so please check this out. Note also that the Spring Framework has a lot of features to simplify the application of AOP, though in your case, given this is a school assignment, its probably better to delve into the core concepts behind AOP itself.
NB: If you're building a production-grade server, logging may be a full-blown feature, and thus worth using AOP. . in other cases its probably simple enough to just in-line.
You should use Observer pattern in this case:
The observer pattern is a software design pattern in which an object,
called the subject, maintains a list of its dependents, called
observers, and notifies them automatically of any state changes,
usually by calling one of their methods.
Your Observable will observe changes in directory, by time pooling, or as already was suggested here, with WatchService. Changes of directory will notify Observer which will take action of moving files. Both Observable and Observer should log their actions.
You shold also know that Observer pattern became a part of Java JDK by implementing java.util.Observable and java.util.Observer.
You can make your proxy aware of the real object. Basically your proxy will delegate the call to run method to the real implementation.
Before the delegation, the proxy first logs the startup. After delegation, the proxy logs the "shutdown":
// Snapshot from what should look like the run method implementation
// in your proxy.
public ServerInterfaceProxy(ServerInterface target){
this.proxiedTarget = target;
}
public void run(){
log(LogLevels.INFO, "server is running ...");
this.proxiedTarget.run();
log(LogLevels.INFO, "server is running ...");
}
This implementation can also be perceived as a Decorator pattern implementation. IMHO, I believe that to some extent (when it comes to implementation) Proxy and Decorator are equivalent : Both intercept/capture behavior of a target.
Look at Java 7's WatchService class.
Using Proxy behaviour for this is almost certainly overkill.

How to recover from legacy stuff in large system step by step?

Our team has been given a legacy system for further maintenance and development.
As this this is true "legacy" stuff, there is really, really small number of tests, and most of them are crap. This is an app with web interface, so there are both container-managed components as well as plain java classes (not tied to any framework etc.) which are "new-ed" here and there, whenever you want to.
As we work with this system, every time we touch given part we try to break all that stuff into smaller pieces, discover and refactor dependencies, push dependencies instead of pulling them in code.
My question is how to work with such system, to break dependecies, make code more testable etc? When to stop and how to deal with this?
Let me show you an example:
public class BillingSettingsAction {
private TelSystemConfigurator configurator;
private OperatorIdDao dao;
public BillingSettingsAction(String zoneId) {
configurator = TelSystemConfiguratorFactory.instance().getConfigurator(zoneId);
dao = IdDaoFactory.getDao();
...
}
// methods using configurator and dao
}
This constructor definitely does too much. Also to test this for further refactoring it requires doing magic with PowerMock etc. What I'd do is to change it into:
public BillingSettingsAction(String zone, TelSystemConfigurator configurator, OperatorIdDao dao) {
this.configurator = configurator;
this.dao = dao;
this.zone = zone;
}
or provide constructor setting zone only with setters for dependencies.
The problem I see is that if I provide dependencies in constructor, I still need to provide them somewhere. So it is just moving problem one level up. I know I can create factory for wiring all the dependencies, but touching different part of app will cause having different factories for each. I obviously can't refactor all the app at once and introduce e.g. Spring there.
Exposing setters (maybe with default implementations provided) is similar, moreover it is like adding code for tests only.
So my question is how you deal with that? How to make dependencies between objects better, more readable, testable without doing it in one go?
I just recently started reading "Working effectively with legacy code" by Michael Feathers.
The book is basically an answer to your very question. It presents very actionable "nuggets" and techniques to incrementally bring a legacy system under test and progressively improve the code base.
The navigation can be a little confusing, as the book references itself by pointing to specific techniques, almost from page 1, but I find that the content is very useful so far.
I am not affiliated with the author or anything like that, it's just that I am facing similar situations and found this a very interesting resource.
HTH
I'd try to establish a rule like the boy scout rule: When ever you touch a file you have to improve it a little, apart from implementing what ever you wanted to implement.
In order to support that you can
agree on a fixed time budget for such improvements like for 2 hours of feature work we allow 1 hour of clean up.
Have metrics visible showing the improvement over time. Often simple things like average file size and test coverage are sufficient
Have a list of things you want to change at least for the bigger stuff, like "Get rid of TelSystemConfiguratorFactory" track on which tasks you are already working and prefere working on things that already started over new things.
In any case make sure management agrees to your approach.
On the more technical side: The approach you showed is is good. In many cases I would consider a second constructor providing all the dependencies but through the new constructor with the parameters. Make the additional constructor deprecated. When you touch clients of that class make them use the new constructor.
If you are going with Spring (or some other DI Framework) you can start by replacing calls to static Factories with getting an instance from the Spring context as an intermediate step before actually creating it via spring and injecting all the dependencies.

Java equivalent of Cocoa NSNotification?

I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
Now the Loader defines a method for your other code to register for callbacks, like
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
The Loader, when it starts a scan, executes the following code
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you.
What sort of notifications are you looking for? If all you want is for one object to be able to tell anybody else "hey, I've changed, update accordingly", the easiest way is to use the existing Observer interface and Observable class. Or write your own with an interface that defines what you want to get called on the listeners from the one that's changed.
There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of *Event classes and *EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As Paul mentioned, there's java.util.Observable, which as you point out, requires subclassing. There's also java.beans.PropertyChangeSupport, which could be useful depending on your situation.
You could also write one yourself. The source for PropertyChangeSupport is likely available in the openjdk, and you could look at the abandoned Apache Commons Event project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone?
There's actually a facility built in to Java that does exactly what you want, but it's not something you may have considered, and, to be honest, it is likely a bit heavyweight for what you want.
That said, however, it does exist.
It's JMX.
You create MBeans, and then others can register for events from those MBeans. The MBean can then send of a Notification.
I personally wouldn't consider using it for this case (I'd just pound out my own), but the facility is there and it well defined and documented.
Not Java, but the IPython project has a notification center written in Python here that you could use as a template for a Java version.
In Java this would be a provider firing notifications to its listeners. But Java does not offer the loose coupling you get with Cocoa's NSNotification because in Java providers and subscribers must have references to each other. Compare for this chapter 18 in "Learn Objective-C for Java Developers".
There is an implementation of IOS NSNotificationCenter in Java.
You can find sources code in :
This Github project

Categories

Resources