My recent interest in Signals and Slots led me to a few other more detailed docs on the subject
Lambdas are not closures
A λ (lambda) is an anonymous function. In addition to Closures, Oracle are looking at including lambdas in JDK 7, which would bring more functional goodness to the feature stagnant Java. This InfoQ article sums up the situation nicely. It talks about the difference between lambdas and closures â a closure is a function that doesnât rely on any external arguments â it is a closed function. However, a lamda is an open function.
λx. x + y
(open function, depends on y)
λy. λx. x+y
(closed function, the inner open lambda is satisfied by y being supplied in the external function)
The former reminds me of Groovyâs closure currying
The proposed syntax looks something like this
inc = #(int x) (x+1); // single expression inc2 = #(int x) { return x+1; }; // block
The rest of the article talks about the proposed syntax for lambdas and the concerns with implementing in various code constructs that potentially conflict with existing Java language syntax and rules.
Graph Databases
A great article on the NoSQL movement, focusing on Graph Databases and the Neo4J implementation appeared on InfoQ.
Graph databases store a Node (aka vertex), that has properties (aka attributes), that is then linked to another node. The relationship (aka edge) between the nodes also has properties and has a direction and a type.
The article demonstrates that syntactically these databases look easy to manipulate. In Ruby (and presumably Grails) they map directly to classes and with the use of metaclasses and operator overloading, to allow the domain objects to be quickly in a neatly expressive way. For Groovy/Grails/Griffon, there is info on the Neo4j wiki
Because OO models are graphs, the need for ORM layer is removed. They map directly to the classes we are trying to store. Additionally the pain of upgrading the data in a class is reduced since adding a new column is less painful. More benefits can be found on the Neo4J website.
Neo4J is free for open source projects and there is an unsupported free single instance Basic edition for startups, but is paid for everyone else. There are 3 commercial editions, basic, advanced and enterprise priced at $588, $5,988 and $23,998 per annum (billed as monthly subscription). The free Basic is a good move, small companies who may elect a free alternative such as MySQL, Postgres or even the Oracle Express Edition. For the Basic & Advanced editions, you could argue that the development time saved would more than cover the fees charged.
The basic edition lacks monitoring which in my opinion should be included, especially if you are only going to get 2 support incidents per year with that package. However the advanced edition has that feature plus monitoring, a management console and allows hot backup and failover to a 2nd running node. It only differs itself from the high end one due to lack of high availability features and longer support response times. If you were using it for a production enterprise system, youâd probably want the 24/7 support and I think this pricing is comparable to a support subscription for any of the larger RDBMS vendors and with no upfront capex fees to note, though keeping in mind that at the enterprise level youâd be paying for multiple running nodes costs may run up quickly —- there is always negotiation though in this space.
Java WebStart Links & Specs
Start Here: http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp
Java Web Start Developers Site
FAQ: http://java.sun.com/javase/technologies/desktop/javawebstart/faq.html#72
Java Web Start Tutorial
Unofficial Java Web Start/JNLP FAQ: http://lopica.sourceforge.net/faq.html#turn-off-splash
Another great IDEA presentation
My favourite IDEA presenter, Vaclav Pech is talking about code analysis tools in IDEA. He talks about
- Code Inspections (live and on demand)
- Abstract Syntax Tree
- The structural code inspection â AST context helps understand the Structure search and replace dialog and how you can use its functionality to make an Idea warning with autofix
- language analysis
- the annotations like @NotNull, @Pattern in new JSRs and the IntelliJ specific annotations @Language for analysis of strings
- stacktrace detection
- dataflow to/from this
- duplicate detection
- dependency analysis
MigLayout
Iâm a bit late to the game here, but it seems a âspiritual successorâ (my term) to JGoodies form layout called MigLayout has been around since at least 2007 and is currently campaigning to be in JDK7
The following article gives a quick rundown of MiGLayout compared to Swings traditional layout managers: MiGLayout: The one Java layout manager that does it all
My Interpretation of the Signals and Slots Pattern
What happens
An ObservableClass ‘emits‘ signals when something interesting happens.
Examples of interesting things:
a property change in a bean;
a new db connection up;
a window closes
Emitting a signal is something that has to be done manually by the programmer after they’ve done the interested thing
Example
setProperty(Object newValue) {
this.property = newValue;
emit(newValue);
}
It means tell all the InterestedClasses to check out the signal and optional newValues passed and do something with it in a slot method
To let the ObservableClass know which InterestedClass methods to call (slots) when we emit the signal, we must connect them to each other.
We could also connect multiple slots to signals
Once connected however, the connection is quite loose.
The slot method is usually referred to as a string (though we could use closures in future). Thus slot or slots to execute when a signal is emitted is determined at runtime, by looking at the parameters in the emit and matching them to the parameters of the connected slots (methods).
Implementation Use Case:
- We are interested in one or more discrete events that happens in the lifetime of the Observable Class.
- We create Signal objects to represent each of these events that could ever be emitted by the ObservableClass. We usually do this in the constructor of the ObservableClass
- We update our methods to emit signals (call the emit method straight after the interesting thing has occured)
- If we want to send some event context data to any interested listeners (slots), we can pass parameters to the emit to pass on when the Signal is fired.
- In another class (or maybe even same one?) we write a method to execute when the interesting thing happens. This is called a slot
- We connect the signal to the slot via a connect method
-
When the interesting thing happens, the emit method on the Signal object is called. emit is responsible for letting all the connected slot methods to know to fire.
Other Notes (extentions)
- A signal can be connected to multiple slots (methods) in any number of different classes
- You can chain signals together
- Communication is one way from the Signal event to the InterestedClass.
-
The params in emited in the Signal can be more than the slot method (but not the other way around)
Comparison to the usual way done in Java Swing (Observer Pattern)
In Java, an Observable Event occurs. InterestedClasses must register their interest with the observable class.
The ObservableClass must keep track of who is listening and notify each of them when the event occurs.
The InterestedClasses must all implement the same notification method (and full method signature) in order to use the event. Potentially less runtime mistakes because the IDE will pick up at compile time
Remember the Signals and Slots pattern doesn’t care about the method signatures of who is listening and effectively can fire updates to different methods of different types.
Junit’s Theory’s as interprested by Schauderhaft and Groovy
JUnit theories sound promising. Many a time a developer writes a whole lot of @Tests along the lines of testParameterXzero(), testParameterXone(), testParameterXmaxInt(). The test code may be almost identical apart from the parameters being used in the class/method under test which is redundant and prone to error.
Theories offer a sound alternate, specifying a single test method, with a different set of annotations to the regular @Test defining a field or annotation based ParameterSupplier to inject a series of values into each test.
Schauderhaftâs blog provides a great summary of what theories are and how to write a parameter supplier to supply a series of datapoints in Java. The annotation based ParameterSupplier does look a little verbose but as Schauderhaft points out, they can be reused – annotation based data fixtures – excellent. I liked these two posts because they do a better job at explaining than the release notes. The blog also links to a blog about another Junit4 feature – parameterised tests – that seem to be a precursor to Theories, and a little simpler to setup. Another great source of how to use Theories is actually in the Groovy documentation about Junit integration. Closures make Datapoints a little more concise (or maybe the example is just simpler? hehe) along with the fact that test data (lists,maps) have a groovy conciseness to them to begin with.
Multiple Inheritance in Java
This is something thatâs usually taught to first year Java students. Though I had a small mental blank about how it was implemented. I knew that to get around the âlimitationâ*, you could specify a class with multiple interfaces, but that was only half the solution. What about the implementation?
Surprisingly it was hard to get a clear answer from the fractal patterns that Google found, a lot of developers saying, âoh yeah, you need interfacesâ but it didnât sound like they knew themselves.
So, this was my way, probably duplicated a zillion times, but here you go, hereâs a way:
We are going to have three classes, A, B & C (sorry for the lack of imaginative names here). Class C will extend both A & B. Weâll extra interfaces for A & B dubbed Ai & Bi respectively.
First an interface for the classes we are going to âextendâ from.
1: public interface Ai {
2: public void aMethod();
3: }
1: public interface Bi {
2: public void bMethod();
3: }
and now some implementation:
1: public class A implements Ai {
2:
3: public void aMethod() {
4: System.out.println("aMethod");
5: }
6:
7: }
1: public class B implements Bi {
2: public void bMethod() {
3: System.out.println("bMethod");
4: }
5: }
And now for our binding class, C. The class implements both interfaces, and takes in implementations of each of the super-classes as constructor arguments. The implementations of each method defined in the A and B interface is a delegate to the relevant A or B class that was injected in the constructor.
1: public class C implements Ai, Bi {
2: private final Ai a;
3: private final Bi b;
4:
5: public C(Ai a, Bi b) {
6: this.a = a;
7: this.b = b;
8: }
9:
10: public void aMethod() {
11: a.aMethod();
12: }
13:
14: public void bMethod() {
15: b.bMethod();
16: }
17: }
The call to the implementing a.aMethod() is effectively a super() call. You can then append your own extra implementation, or remove the delegating call and define your own.
So what about the diamond problem, when both A & B define a method that is named that same thing. In Java if you try to say a class implements interfaces that have duplicate signatures youâll get a compile time error. If Ai and Bi both had a method called cMethod() then the C class would refuse to compile.
Other ways
My research found other mentions. If you got lazy, you could have C extend A, and implement Bi. Then you wouldnât have to write the interface Ai and C would be a little smaller since it would only inject the B implementation and have a bMethod() delegate.
Another way was to have the 2nd class as a static inner class. Although I have no issue with this implementation working, as soon as I see âinnerâ, Iâm led to believe its re-use value becomes a bit more limited and certainly more cumbersome to refer to.
Notes
BTW, if you want to find a decent explanation of what to do and an interesting reading of a Mixin pattern implemented in Java, then see here.
* I say âlimitationâ in quotes because apart from the well known diamond inheritance problem that crops up with multiple inheritance in C++, from what I read, using multiple inheritance could be a code smell. Certainly the ambiguity that comes from not knowing exactly which one will be called or whether or not youâll know at compile time, or run-time is a concern. (Donât delay the Bad-news)
Inline Java In Perl
A former perl guru colleague of mine showed me Inline::Java, a way to embed Java in your perl programs and call perl from your Java classes.
The way it works is it invokes javac and creates some bytecode. It then runs its own perl mapper (reflecting on said bytecode) so that the Perl code can use the Java public methods and attributes.
If you reference a java package outside the scope of your code (eg java.util or your own packages in a separate jar), then this module will also reflect those too. You can specify a CLASSPATH environment variable so it knows where to look for these jars.
According to the bugs db there weren’t too many though how active the project still is remains to be seen. Apparently the implementation can be a bit slow but there is a JNI option to speed things up. I also suspect there is some problem with more unique java properties, apparently the module balks when it tries to see the Oracle 10 JDBC driver jar because of a public synchronized property.
Regardless if you’ve got Perl code that you want to migrate to Java, this would be a nice first step to bridge the gap.
See these sub modules for more info on how you can bridge the gap from the Java side
Inline::Java::Callback, Inline::Java::PerlNatives, Inline::Java::PerlInterpreter
Based on this, the equally cool, Java::Swing project emerged which leverages on the above.