Why use the command pattern in GWT (or any web app)? - java

According to this video here [# 7:50] Google is recommending the use of the Command pattern on top of its request handling API. There is also a helpful looking project gwt-dispatch that implements that pattern.
According to gwt-dispatch documentation I need to create four classes for each command:
an action (e.g. command)
a result (e.g. response)
an action handler
a module
Assume my service API has 100 methods across 8 BSOs, can somebody explain to me why I want to create nearly 400 new classes? What awesomeness does this pattern buy?

One good reason to use the command pattern is, when you want to pass the command object to further delegates - so instead of copying all the arguments, it's easier to just pass the command object around. It's also useful for gwt-dispatch's rollback functionality (or the undo/redo functionality e.g. in Eclipse's UndoableOperations).
It helps to provide several variations of commands by using different constructors, and subclasses of commands.
I would not suggest to always use the pattern, but you don't save as much as you think, when you don't use it: You will often need result objects anyway - and it's possible to reuse the same return objects. In other cases, you can use the same object for the command and for the result.
The module can be used for multiple commands.

Related

Specify JDBI default plugin (SqlObjectPlugin)

Is there a way to tell JDBI I want to use a specific plugin (SqlObjectPlugin in my case) throughout my entire application, without having to re-specify upon each use? Throughout my application code I have the following:
var jdbi = Jdbi.create(dataSource);
jdbi.installPlugin(new SqlObjectPlugin()); // <== I want to make this part DRY
I'm tired of having that second boilerplate line repeated all over my code.
To the JDBI devs: I totally love the product! thx! :)
You have two options, which of the is best depends on the code of your application:
Instantiate Jdbi once and reuse it everywhere (using DI, static singleton, etc)
Use org.jdbi.v3.core.Jdbi#installPlugins, which, according to documentation, uses the ServiceLoader API to detect and install plugins automagically. Some people consider this feature dangerous; some consider it essential -- use at your own risk. But you still would need to call this method every time.

Dynamically build java/scala method body at runtime and execute it

Suppose I have the following Interface in java:
public interface DynamicMethod {
String doit();
}
I would like to build an Object during runtime which conforms to the above interface such that I inject doit method body in it and then execute it? Is this possible with Java Reflection API, or any other way? Or probably in some way in Scala?
Note that doit body for my objects would be dynamic and are not known a priori. You can assume that in run-time an array CodeArray[1..10] of Strings is provided and each entry of this array holds the code for each doit method. I would appreciate if you could answer with a sample code.
The context:
I try to explain the context of the problem; nonetheless, the above question still remains independent from the context.
I have some commands say C1,C2, ...; each command has certain parameters. Based on a command and its parameters the system needs to perform a certain task (which is expressible using a java code.) I need that these commands are stored for future execution based on user demand (so the CodeArray[1..10] in the above holds this list of java codes). For example, a user chooses a command from the list (i.e., from the array) and demands its execution.
My thought is that I build an engine that based on the user selection, loads the corresponding command code from the array and executes it.
With your context that you added, it sounds to me like you have an Interpreter..
For example, SQL takes input like "SELECT * FROM users", parses and builds a tree of tokens that it then interprets.
Another example: Java's regex is an interpreter. A string like "[abc]+" is compiled into tokens, and then interpreted when executed. You can see the tokens (called Nodes) it uses in the source code.
I'll try to post a simple example later, but the Interpreter Pattern doesn't use dynamically generated code. All of the tokens are concrete classes. You do have to define all possible (valid) user input so that you can make a token to execute it however. SQL and regex has a defined syntax, you will need one also.
I think Byte Buddy would be helpful in your case. It's an open source project maintained by a very well respected Java developer.
Take a look at the Learn section, they have a very detailed example there:
http://bytebuddy.net/#/tutorial
Currently it's not very clear what's your aim. There are many approaches to do this depending on your requirements.
In some cases it would be enough to create a Proxy and an InvocationHandler. Sometimes it's reasonable to generate Java source, then invoke JavaCompiler in runtime and load the generated class using URLClassLoader (probably that's your case if you're speaking about strings of code). Sometimes it's better to directly create a bytecode using libraries like ASM, cglib or BCEL.

Allowing maximal flexibly/extensibility using a factory

I have a little design issue on which I would like to get some advice:
I have several classes that inherit from the same base class, each one can accept the same data and analyze it in a slightly different way.
Analyzer
|
˪_ AnalyzerA
|
˪_ AnalyzerB
...
I have an input file (I do not have control over the file's format) that defines which analyzers should be invoked and their parameters. Plus it defines data-extractors in the same way and other similar things too (in similar I mean that this is an action that can have several variations).
I have a module that iterates over different analyzers in the file and calls some factory that constructs the correct analyzer. I have a factory for each of the archetypes the input file can define and so far so good.
But what if I want to extend it and to add a new type of analyzer?
The solution I was thinking about is using a property file for each factory that will be named after the factories name and it will hold a mapping between the input file's definition of whatever it wants me to execute and the actual classes that I use to execute the action.
This way I could load that class at run-time -> verify that it's implementing the right interface and then execute it.
If some John Doe would like to create his own analyzer he'd just need to add a new property to the correct file (I'm not quite sure what would be the best strategy to allow this kind of property customization).
So in short:
Is my solution too flawed?
If no what would be the most user friendly/convenient way to allow customization of properties?
P.S
Unfortunately I'm confined to using only build in JDK classes as the existing solution, so I can't just drop in SF on them.
I hope this question is not out of line I'm just not used to having my wings clipped this way, not having SF or some other to help me implement an elegant solution.
Have a look at the way how the java.sql.DriverManager.getConnection(connectionString) method is implemented. The best way is to watch the source code.
Very rough summary of the idea (it is hidden inside a lot of private methods). It is more or less an implementation of chain of responsibility, although there is not linked list of drivers.
DriverManager manages a list of drivers.
Each driver must register itself to the DriverManager by calling its method registerDriver().
Upon request for a connection, the getConnection(connectionString) method sequentially calls the drivers passing them the connectionString.
Each driver KNOWS if the given connection string is within its competence. If yes, it creates the connection and returns it. Otherwise the control is passed to the next driver.
Analogy:
drivers = your concrete Analyzers
connection strings = types of your files to be analyzed
Advantages:
There is no need to explicitly bind the analyzers with their type of file they are meant for. Let the analyzer to decide itself if it is able to analyze the file. If not, null is returned (or an exception or whatever) to tell the AnalyzerManager that the next analyzer in the row should be asked.
Adding new analyzer just means adding a new call to the register() method. Complete decoupling.

Servlet and Command pattern, compile vs runtime?

I'm writing a Java servlet that acts as a Front Controller. To carry out functions I'm using the Domain Command pattern. Currently, I'm initializing all my commands and storing them in a map with the name (string) of the command as the key and the object as the value. Whenever the servlet receives a request, I get the command from the map by passing the command query from url as:
// at init
Hashmap<String, DomainCommand> commands = new Hashmap<String, DomainCommand>();
commands.put("someCommand", new SomeCommand());
// at request
String command = request.getParameter("command");
DomainCommand c = commands.get(command);
c.execute();
This works well and does what I want since my DomainCommands have no class attributes to be shared between threads. An alternative to this is using reflection to create the object like so:
String command = request.getParameter("command");
DomainCommand c = Class.forName(command).newInstance(); // assuming in same (default) package
c.execute();
Both of these work. Which is better from a performance/memory saving point of view?
Performance
When using Map the only cost is accessing a HashMap (negligible). Reflection on the other hand might take much more time and is less safe - remember you have to make sure the user is not passing bogus command, allowing him to run arbitrary code.
Memory
When creating DomainCommand at startup they will end up in old generation after some time, thus not being subject to garbage collection for most of the time. On the other when created per request most likely they will be garbage collected immediately. So in overall, the memory footprint will be comparable, except that the second approach requires mor GC runs.
All in all, map of commands is a much better approach. BTW if you DI frameworks like Spring or Guice (unless this is an overkill for you) or web frameworks like Struts/Spring MVC, they will do precisely the same work for you.
The first approach of storing the commands in HashMap is better. The problem with the second approach is that you have to load the command class every-time you execute that command.
In fact frameworks like Struts which precisely on command pattern with Controller Servlet as front controller with individual action classes as commands.
From performance perspective the 1st approach you mentioned is definitely faster.
How about the following options?
using Visitor pattern for command
storing your command beans and do a lookup for command bean by its name (from the request) in JNDI (have a service that retrieves the command from JNDI)
using IoC framework (Spring) where all the command beans are initialized from the container startup and lookup for command is done on the application context
Performance-wise I would prefer the 3rd option.
You asked for an answer specifically from a performance/memory saving point of view, and the other answers answer that. I agree that the Map approach is probably better in this regard.
However, you should be sure that this is even a concern before worrying about that at this point; I'm assuming the network overhead to one call to your servlet by far outweighs a single HashMap lookup of a short string.
A larger concern should be clarity and maintainability. In this regard as well, I would say that the Map approach is much superior, as it:
Doesn't tie the API (legal values of the command parameter) to the implementation (names of classes)
Makes it clear which classes are intended to be used as commands and which are not (very important if you later want to make a change)
Allows the API to be more flexible (for example, you could allow the command parameter to be case-insensitive, or to have more than one command map to the same class)
To quote the Zen of Python: "Explicit is better than implicit".
How about merging the 2 options together?
Struts does the exact same thing. It contains a Map that caches all your commands that has been requested by the Servlet. If the command doesn't exist, then it creates a newInstance() of the command (just like option 2 you've created).
The advantage of this is quicker execution of your process: Retrieve the command from the cache else create a new one & and store the created new command in cache. It's definitely faster than option 2.

Can Java self-modify via user input?

I'm interested in an executed script allowing user input to modify the process and corresponding source.
What precedents exist to implement such a structure?
Yes, depending on what is meant.
Consider such projects as ObjectWeb ASM (see the the ASM 2.0 tutorial for a general rundown).
Trying to emit the-would-need-to-be-decompiled Java source code is another story: if this was the goal then perhaps the source should be edited, re-compiled, and somehow loaded in/over. (This is possible as well, consider tools like JRebel.)
Happy coding.
You should not be able to modify existing classes. But if you implement a ClassLoader then you can dynamically load classes from non-traditional sources: network, XML file, user input, random number generator, etc.
There are probably other, better ways.
Maybe the Java scripting API is what you're looking for:
http://docs.oracle.com/javase/6/docs/api/javax/script/package-summary.html
http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html
I wrote an app once that used reflection to allow tests to be driven by a text file. For instance, if you had a class like this:
class Tuner(String Channel) {
tune(){...
play(){...
stop(){...
}
You could execute methods via code like:
tuner=Channel 1
tune tuner
play tuner
stop tuner
It had some more capabilities (You could pass objects into other objects, etc), but mostly I used it to drive tests on a cable box where a full write/build/deploy in order to test took on the order of a half hour.
You could create a few reusable classes and tie them together with this test language to make some very complex and easy to create tests.
THAT is a DSL, not monkeying around with your loose-syntax language by eliminating parenthesis and adding underscores and dots in random locations to make it look like some strange semi-English.

Categories

Resources