Java mechanisms at use in lambdaj closures - java

Lamdbaj allows the definition of closures in the Java language, various examples can be found
here
My question is regarding the underlying Java mechanisms at use, for instance, to define the println closure, the following code is used:
Closure println = closure();
{ of(System.out).println(var(String.class)); }
This closure can be subsequently executed via:
println.apply("foobar");
I am curious as to what mechanisms in Java would allow the call to of(...).println(...) to become associated with the println instance itself.
Naturally, the lambdaj source code is available to read but I was hoping for a slightly higher level explanation if anyone has one. My reflection skills go as far as a bit of introspection and executing methods dynamically.

I am Mario Fusco and I am the main developer of the lambdaj library.
First of all I would like to clarify something: lambdaj is not intended to replace any functional language. As I said last week in my speech at the Jug of Zurich if you have a chance to use Scala, go for it and never look back. Here you can find a resume of my speech where it is clearly stated that:
http://ctpjava.blogspot.com/2009/10/lambdaj-new-trends-in-java.html
I am an happy Scala developer too. But sometimes you are just obliged to develop in Java (in my experience, in the real world, about the 80% of times you cannot choose in which language you have to write your code) and in this case some of the lambdaj features could be helpful (or I hope so). I just wanted to bring to Java some functional features that are totally missing. Of course the result is not completely satisfying mainly due to the limitation imposed by Java itself.
As for the internal lambdaj mechanism, yes it uses a ThreadLocal in order to achieve that result. If you have other questions, curiosities or even better suggestions and constructive critics about lambdaj maybe you could be interested to register yourself to the lambdaj mailing list here:
http://groups.google.com/group/lambdaj
Bye
Mario

Well, of is presumably a static method which is imported statically so it can be called without the enclosing class name. I expect that var is the same. Both methods must return some type which have the methods subsequently called:
public class Printable {
public void println(Var var);
}
public class Fac {
public static Printable of(Object o) {
return new Printable(o);
}
public static Var var(Class<?> clazz) {
return new Var(clazz);
}
}
All of a sudden:
Fac.of(System.out).println(Fac.var(String.class));
Is valid Java. Using static imports, hey presto:
import static Fac.*;
of(System.out).println(var(String.class));
The curly-braces are obviously valid Java as you can add these in any method to aid in defining a lexical sope. This API-design style is called fluent and is best showcased by the JMock testing library.
By the way, if this is supposed to introduce closures to Java, it's quite ridiculous - the syntax is unreadably awful. Their I/O example actually made me laugh out loud. Try Scala!
EDIT - the two println calls are associated I believe because the first sequence of calls allow the library to capture the variables which you have passed in as parameters. These are probably captured in some ThreadLocal structure. When you then call a (also presumably static) println method, the library is using this captured data to actually execute the behaviour at a later point. Also testing related, the EasyMock test framework uses a similar mechanism (which uses Java proxies in the background) to capture expected values.

Related

When and how to Use "return this" in Java

I'm developing a simple java project to help me master the language and was researching on method chaining when I came across the return this statement. I'm not quite sure of its use cases apart from method chaining and what it means exactly to return this. Its documentation was obviously not written for newbies. Could someone help make it clearer?
return this;
returns the instance itself from the method.
Returning the instance is usually (but not always) used when implementing a fluent interface, which allows code to look like this:
myObj.method1().method2().method3();
This in turn is very commonly used (but not required) when implementing the builder pattern.
return this simply means "return the reference of the current instance".

OOP: Any idiom for easy interface extraction and less verbose auto-forwarding?

EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.

Anything in Guava similar to Functional Java's Effect?

I know one of the goals of pure functional programming is to eliminate mutability, and therefore to preclude side-effects. But let's face it, Java is not a functional language even with all of the functional-programming libraries that exist. In fact it seems that some of the FP-libraries know and expect this. For instance in Functional Java, there is the Effect class. In the Jedi FP library, there is the Command interface. This allows you to -- among other things -- apply a command pattern with type-safety to elements of an Iterable without the nasty for-loop boilerplate.
Command<PhoneNumber> makeCall = new Command<PhoneNumber> {
public void execute(PhoneNumber p) { p.call(); }
}
List<PhoneNumber> phoneList = ...
FunctionalPrimitives.forEach( phoneList, makeCall );
So the question is, is there anything like that in Guava?
EDITED AFTER ANSWER ACCEPTED FOR CLARIFICATION
I am developing a framework that helps with the "vertical problem" inherent in most Java FP-libraries, under a certain set of circumstances. So I would not actually make the code example as shown above: i.e., explicitly declare a new class implementation of Command with all of its vertical-noise icky-ness, simply for the purpose of immediately applying it right after the declaration.
I was thinking more along the lines of the actual command pattern, where there may be several possible commands declared elsewhere, and only one of them gets passed into the code which wants to apply it iteratively. Furthermore, the goal of my framework is to make it more idiomatic to create functional-interface objects (functions, predicates, commands, other simple lambdas) without simply moving the vertical problem elsewhere. I have long realized this is not within the scope of Guava. But as Command-like interface are available in other FP libraries, I just wanted to know if an analog existed in Guava.
A more complete code example, using my framework, might be something like this:
class Stuff {
private final Stuff CALLS_TO = callsTo(Stuff.class); // a proxy
public static final Command<Stuff> CMD1 = commandFor(CALLS_TO.someMethod1());
public static final Command<Stuff> CMD2 = commandFor(CALLS_TO.someMethod2());
// methods exist for use elsewhere, but are conveniently also wrapped as commands
public void someMethod1() {...}
public void someMethod2() {...}
}
class Activity {
public void handleIt(List<Stuff> stuffs, Command<Stuff> doCmd) {
doSomeThings();
...
forEach(stuffs, doCmd);
...
doOtherThings();
}
}
Nope!
Kevin Bourrillion, the Guava project lead, has said on Guava's functional features:
“The syntax sucks. At the same time, this stuff is now, has always been and will always be nothing but a stopgap measure until the right language change can come along, at which time we can finally really decide on the optimal syntax and have functional-style programming start actually making lives better in Java for once. So I’m undecided how much effort to put into the Function/Predicate stuff; it’s in the library more because it sort of had to be, not so much because we think it’s a crown jewel.”
We will probably change our strategy significantly when Java 8 comes along, but that won't be for a while yet.
Also, we haven't found many use cases for which we think the Command interface you describe would be the best solution. For example, we think that your above code would be much better written as
for(PhoneNumber phone : phoneList) {
phone.call();
}
the old-fashioned way. We could potentially be convinced of the merit of Command, but I think the "for-each" use case is almost always better done the old-fashioned way.

c++ templated methods

How are templated methods implemented in C++?
I'm thinking about implementing templates in the JVM and have got a possible implementation thought out for templated classes, but am unsure on methods.
If, for example, you did:
class Test
{
public static boolean isIterable<T>(T variable)
{
return T instanceof Iterable;
}
}
System.out.println(Test.isIterable(new int[] { 0 }));
Would I create a version of Test that replied to int[]? (In my implementation, the class would be named as such: $g$Test$A_Java_lang_int)
Please ignore any problems with generics (such as only requiring boxed objects), as I intend to remove them.
I plan on creating these resolved templates dynamically, and keeping track of the number of references so I can remove them if they are not used. I believe this is how .Net manages it, although I'd be happy to be wrong here!
Would I create a version of Test that replied to int[]?
Essentially, yes. Templates in C++ are purely a compile-time mechanism that uses a (glorified) macro mechanism to generate code based on a template for each type with which it’s instantiated.
(C++ actually does a lot more due to the possibility of specialisation but this is the gist of it.)
I would suggest trying to do this staticly by generating the classes. You might find http://trove.starlight-systems.com/ interesting as it has a templating approach to generating its primitive collections. e.g. TintLongHashMap This doesn't rely on any language features.
I would suggest you work out how to do this staticly before trying to do it dynamicly which is much harder.

Matlab / Java API callback

I'm designing an API (in Java) and expect to have users accessing the API from Matlab. The problem is that I want the API to provide a piece of functionality like:
javaApi.waitUntilPredicateIsTrue(Predicate<JavaObj> test);
My API (in the background) gets hold of instances of Java Obj (via some mechanism, e.g. polling). I want this API method to block until one of these instances, when passed to the Predicate evaluates to true. If I was calling this API from Java, I'd do:
javaApi.waitUntilPredicateIsTrue(new Predicate<JavaObj>() {
public boolean evaluate(JavaObj jo) {
return "READY".equals(jo.getState());
}
});
You get the idea.
How can this be called from within Matlab? Can I use anonymous inner classes from Matlab? Can I declare a Matlab classdef which extends the interface Predicate (can this cope with the Java generic version)?
That sounds like a tough question. I'm still running R2006b so this may have changed, but it looks like MATLAB will not translate function handles (incl. anonymous functions) and structures into Java objects. I don't know about MATLAB custom classes, since the syntax has changed. Strings, arrays, and cell arrays will translate properly. They don't comment at all on implementing interfaces. (:p :p :p BOO HISS)
edit: just found this page on Matlab Central, it talks about some undocumented interfaces.
Matlab has a much nicer solution than forcing users to create a whole class just to provide a single method. Take a look at their anonymous functions.
Note that anonymous functions in Matlab have odd scoping rules. Make sure you read the "Variables Used in the Expression" section of the linked help page. If you want more traditional lexical scoping, take a look at nested functions.
EDIT:
I am assuming that you will be doing the polling from Matlab, not passing the predicate function to Java. Example:
function waitForPredicate(pred)
while pred
end
end
waitForPredicate(#()javaApi.isMyConditionMet());

Categories

Resources