Java Delegates? - java

Does the Java language have delegate features, similar to how C# has support for delegates?

Not really, no.
You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).
You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (#blueskyprojects.com)

Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
// C#
public delegate void SomeFunction();
declare an interface:
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
For concrete implementations of the method, define a class that implements the behaviour:
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
#Override
public void SomeFunction() {
// your implementation
}
});
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions:
// Java 8
SomeMethod(() -> { /* your implementation */ });

Short story: ­­­­­­­­­­­­­­­­­­­no.
Introduction
The newest version of the Microsoft Visual J++ development environment
supports a language construct called delegates or bound method
references. This construct, and the new keywords delegate and
multicast introduced to support it, are not a part of the JavaTM
programming language, which is specified by the Java Language
Specification and amended by the Inner Classes Specification included
in the documentation for the JDKTM 1.1 software.
It is unlikely that the Java programming language will ever include
this construct. Sun already carefully considered adopting it in 1996,
to the extent of building and discarding working prototypes. Our
conclusion was that bound method references are unnecessary and
detrimental to the language. This decision was made in consultation
with Borland International, who had previous experience with bound
method references in Delphi Object Pascal.
We believe bound method references are unnecessary because another
design alternative, inner classes, provides equal or superior
functionality. In particular, inner classes fully support the
requirements of user-interface event handling, and have been used to
implement a user-interface API at least as comprehensive as the
Windows Foundation Classes.
We believe bound method references are harmful because they detract
from the simplicity of the Java programming language and the
pervasively object-oriented character of the APIs. Bound method
references also introduce irregularity into the language syntax and
scoping rules. Finally, they dilute the investment in VM technologies
because VMs are required to handle additional and disparate types of
references and method linkage efficiently.

Have you read this :
Delegates are a useful construct in event-based systems. Essentially
Delegates are objects that encode a method dispatch on a specified
object. This document shows how java inner classes provide a more
generic solution to such problems.
What is a Delegate? Really it is very similar to a pointer to member
function as used in C++. But a delegate contains the target object
alongwith the method to be invoked. Ideally it would be nice to be
able to say:
obj.registerHandler(ano.methodOne);
..and that the method methodOne would be called on ano when some specific event was received.
This is what the Delegate structure achieves.
Java Inner Classes
It has been argued that Java provides this
functionality via anonymous inner classes and thus does not need the additional
Delegate construct.
obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
methodOne(ev);
}
} );
At first glance this seems correct but at the same time a nuisance.
Because for many event processing examples the simplicity of the
Delegates syntax is very attractive.
General Handler
However, if event-based programming is used in a more
pervasive manner, say, for example, as a part of a general
asynchronous programming environment, there is more at stake.
In such a general situation, it is not sufficient to include only the
target method and target object instance. In general there may be
other parameters required, that are determined within the context when
the event handler is registered.
In this more general situation, the java approach can provide a very
elegant solution, particularly when combined with use of final
variables:
void processState(final T1 p1, final T2 dispatch) {
final int a1 = someCalculation();
m_obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
dispatch.methodOne(a1, ev, p1);
}
} );
}
final * final * final
Got your attention?
Note that the final variables are accessible from within the anonymous
class method definitions. Be sure to study this code carefully to
understand the ramifications. This is potentially a very powerful
technique. For example, it can be used to good effect when registering
handlers in MiniDOM and in more general situations.
By contrast, the Delegate construct does not provide a solution for
this more general requirement, and as such should be rejected as an
idiom on which designs can be based.

I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas.
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html

No, but they're fakeable using proxies and reflection:
public static class TestClass {
public String knockKnock() {
return "who's there?";
}
}
private final TestClass testInstance = new TestClass();
#Test public void
can_delegate_a_single_method_interface_to_an_instance() throws Exception {
Delegator<TestClass, Callable<String>> knockKnockDelegator = Delegator.ofMethod("knockKnock")
.of(TestClass.class)
.to(Callable.class);
Callable<String> callable = knockKnockDelegator.delegateTo(testInstance);
assertThat(callable.call(), is("who's there?"));
}
The nice thing about this idiom is that you can verify that the delegated-to method exists, and has the required signature, at the point where you create the delegator (although not at compile-time, unfortunately, although a FindBugs plug-in might help here), then use it safely to delegate to various instances.
See the karg code on github for more tests and implementation.

Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.

I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.
static private final Method COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);
...
IoUtil.processDirectory(root,new Callback(this,COUNT),selector);
...
private void callback_count(File dir, File fil) {
if(fil!=null) { // file is null for processing a directory
fileTotal++;
if(fil.length()>fileSizeLimit) {
throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
}
}
progress("Counting",dir,fileTotal);
}
IoUtil.processDirectory():
/**
* Process a directory using callbacks. To interrupt, the callback must throw an (unchecked) exception.
* Subdirectories are processed only if the selector is null or selects the directories, and are done
* after the files in any given directory. When the callback is invoked for a directory, the file
* argument is null;
* <p>
* The callback signature is:
* <pre> void callback(File dir, File ent);</pre>
* <p>
* #return The number of files processed.
*/
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
}
static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
int cnt=0;
if(!dir.isDirectory()) {
if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
}
else {
cbk.invoke(dir,(Object[])null);
File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
if(lst!=null) {
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(!ent.isDirectory()) {
cbk.invoke(dir,ent);
lst[xa]=null;
cnt++;
}
}
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
}
}
}
return cnt;
}
This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.
Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".

It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:
private interface SingleFunc {
void printMe();
}
public static void main(String[] args) {
SingleFunc sf = () -> {
System.out.println("Hello, I am a simple single func.");
};
SingleFunc sfComplex = () -> {
System.out.println("Hello, I am a COMPLEX single func.");
};
delegate(sf);
delegate(sfComplex);
}
private static void delegate(SingleFunc f) {
f.printMe();
}
Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.

With safety-mirror on the classpath you get something similar to C#'s delegates and events.
Examples from the project's README:
Delegates in Java!
Delegate.With1Param<String, String> greetingsDelegate = new Delegate.With1Param<>();
greetingsDelegate.add(str -> "Hello " + str);
greetingsDelegate.add(str -> "Goodbye " + str);
DelegateInvocationResult<String> invocationResult =
greetingsDelegate.invokeAndAggregateExceptions("Sir");
invocationResult.getFunctionInvocationResults().forEach(funInvRes ->
System.out.println(funInvRes.getResult()));
//prints: "Hello sir" and "Goodbye Sir"
Events
//Create a private Delegate. Make sure it is private so only *you* can invoke it.
private static Delegate.With0Params<String> trimDelegate = new Delegate.With0Params<>();
//Create a public Event using the delegate you just created.
public static Event.With0Params<String> trimEvent= new Event.With0Params<>(trimDelegate)
See also this SO answer.

While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.

No, but it has similar behavior, internally.
In C# delegates are used to creates a separate entry point and they work much like a function pointer.
In java there is no thing as function pointer (on a upper look) but internally Java needs to do the same thing in order to achieve these objectives.
For example, creating threads in Java requires a class extending Thread or implementing Runnable, because a class object variable can be used a memory location pointer.

No, Java doesn't have that amazing feature. But you could create it manually using the observer pattern. Here is an example:
Write C# delegate in java

The code described offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:
class Class1 {
public void show(String s) { System.out.println(s); }
}
class Class2 {
public void display(String s) { System.out.println(s); }
}
// allows static method as well
class Class3 {
public static void staticDisplay(String s) { System.out.println(s); }
}
public class TestDelegate {
public static final Class[] OUTPUT_ARGS = { String.class };
public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);
public void main(String[] args) {
Delegate[] items = new Delegate[3];
items[0] = DO_SHOW .build(new Class1(),"show,);
items[1] = DO_SHOW.build (new Class2(),"display");
items[2] = DO_SHOW.build(Class3.class, "staticDisplay");
for(int i = 0; i < items.length; i++) {
items[i].invoke("Hello World");
}
}
}

Java doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates:
1. reflection;
2. inner class
Reflections are slooooow! Inner class does not cover the simplest use-case: sort function. Do not want to go into details, but the solution with inner class basically is to create a wrapper class for an array of integers to be sorted in ascending order and an class for an array of integers to be sorted in descending order.

Related

How should i implement an interface in Java? [Code-Correctness]

First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.

Delegate vs Callback in Java

I have some misunderstanding about terms of delegates and callbacks in Java.
class MyDriver {
public static void main(String[] argv){
MyObject myObj = new MyObject();
// definition of HelpCallback omitted for brevity
myObj.getHelp(new HelpCallback () {
#Override
public void call(int result) {
System.out.println("Help Callback: "+result);
}
});
}
}
class MyObject {
public void getHelp(HelpCallback callback){
//do something
callback.call(OK);
}
}
Is it callback or delegate (Are delegates and callbacks the same or similar?)?
How to implement then another one?
This is a callback. According to Wikipedia:
In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.
So let's look at the executable code:
public void getHelp(HelpCallback callback){
//do something
callback.call(OK);
}
Here, the callback argument is a reference to an object of type HelpCallback. Since that reference is passed in as an argument, it is a callback.
An example of delegation
Delegation is done internally by the object - independent of how the method is invoked. If, for example, the callback variable wasn't an argument, but rather an instance variable:
class MyDriver {
public static void main(String[] argv){
// definition of HelpStrategy omitted for brevity
MyObject myObj = new MyObject(new HelpStrategy() {
#Override
public void getHelp() {
System.out.println("Getting help!");
}
});
myObj.getHelp();
}
}
class MyObject {
private final HelpStrategy helpStrategy;
public MyObject(HelpStrategy helpStrategy) {
this.helpStrategy = helpStrategy;
}
public void getHelp(){
helpStrategy.getHelp();
}
}
... then it would be delegation.
Here, MyObject uses the strategy pattern. There are two things to note:
The invocation of getHelp() doesn't involve passing a reference to executable code. i.e. this is not a callback.
The fact that MyObject.getHelp() invokes helpStrategy.getHelp() is not evident from the public interface of the MyObject object or from the getHelp() invocation. This kind of information hiding is somewhat characteristic of delegation.
Also of note is the lack of a // do something section in the getHelp() method. When using a callback, the callback does not do anything relevant to the object's behavior: it just notifies the caller in some way, which is why a // do something section was necessary. However, when using delegation the actual behavior of the method depends on the delegate - so really we could end up needing both since they serve distinct purposes:
public void getHelp(HelpCallback callback){
helpStrategy.getHelp(); // perform logic / behavior; "do something" as some might say
if(callback != null) {
callback.call(); // invoke the callback, to notify the caller of something
}
}
I'd argue that "callback" is a name for a generic pattern where you provide the module you're calling with a a way for said module to call your code. A C# delegate, or an ObjC delegate object, (these two being entirely different beasts) or a Java class-implementing-the-callback-interface are different, platform-specific ways of implementing the callback pattern. (They can also themselves be considered patterns.) Other languages have more or less subtly different ways of doing so.
The above concept of "delegate" is also similar to the Strategy pattern, where the delegate can be thought of as one. Similarly, a Visitor is also a type of callback. (A visitor is also a strategy for processing each visited item.)
All this is using definitions that are intuitive to me, and might not be to anyone else, because neither "callback" or "delegate" are formal terms and it makes little sense to discuss them without referring to a previous definition thereof that's valid in your context. Consequently it makes little sense to ask what the definition is since, to the best of my knowledge, there isn't an authoritative one. To wit, the fact that other answers to this question are likely to say something entirely different.
My recommendation would be to focus on the merits of your design – whether it achieves what you need, doesn't introduce tight coupling, etc. – rather than on minutiae of semantics. When two design patterns appear similar, they probably can be used to achieve similar goals equally well.
What you want to achieve is bidirectional communication between the original caller and a service while avoiding the service to depend on the client. The pattern you use for that goal often depends on the restrictions of your language. You use function pointers, closures or, if you have none of these, callback objects (which might also be seen as closures).
And then there are often lots of different names for the same or a very similar pattern.

Generic writer/outputter. What Reader is to Iterator, what is Writer to X?

In Java the abstract version of a Reader that works with pulling Objects (instead of characters) is an Iterator.
The question is there an abstract version of Appendable or Writer where I can push objects (ie an interface)?
In the past I just make my own interface like:
public interface Pusher<T> {
public void push(T o);
}
Is there a generic interface that is available in most environments that someone knows about that makes sense so I don't have to keep creating the above interface?
Update:
Here is an example of where it would be useful:
public void findBadCategories(final Appendable a) {
String q = sql.getSql("product-category-bad");
jdbcTemplate.query(q, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {
String id = rs.getString("product_category_id");
String name = rs.getString("category_name");
if (! categoryMap.containsKey(id)) {
try {
a.append(id + "\t" + name + "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
I'm using an Appendable here but I would much rather have my Pusher callback. Believe me once Java 8 comes out I would just use closure but that closure still needs an interface.
Finally the other option I have chosen before is to completely violate Guava's Predicate or Function (although that seems even worse). Its violation of the contract because these aim to be idempotent (although I suppose if you return true all the time... ).
What Guava does provide though is sort of analagous to Python's generators thanks to its AbstractIterator.
I added an enhancement issue to Guava but I agree with them that its not really their job to add something fundamental like that.
On several projects now, I've defined for this purpose what I call a sink:
interface Sink<T> {
void put(T contribution);
}
With that, methods that produce objects of type T would demand a parameter of type Sink<? super T>.
Several design questions arise:
As declared, Sink#put() throws no checked exceptions. That doesn't play well with I/O operations that usually throw IOException. To address this, you can add a type parameter that extends Exception and advertise that put() throws this type, but at that point, if you know that much about the nature of value consumption, you're probably better off defining a custom interface for it.
As declared, Sink#put() does not return a value. It's not possible to indicate to the caller whether the value was accepted or not.
With a generic interface like this, you're forced to box contributions of primitive types like int and char, which also means they can be null. Consider annotating the contribution parameter with #NonNull.
To go along with this type, related to the generator concept that Petr Pudlák mentions in his answer, I've defined a source interface:
interface Source<T> {
T get();
}
Methods looking to draw items of type T from such a source demand a parameter of type Source<? extends T>.
For coordination with channels among concurrent processes, I've defined both Sink#put() and Source#get() to throw InterruptedException:
interface Sink<T> {
void put(T contribution) throws InterruptedException;
}
interface Source<T> {
T get() throws InterruptedException;
}
These are analogous to Doug Lea's original Puttable and Takable interfaces that didn't make it into the java.util.concurrent package, though lacking in an equivalent to the timed wait Puttable#offer() and Takable#poll() methods.
All sorts of implementations then arise that can be composed easily, such as exchangers, filters, and transformers.
Beyond my own library, I've seen the Guava library provide the PrimitiveSink and Funnel types for hashing-related purposes. You may find those to be useful abstractions as well.
There can be several views on the subject:
The dual of an iterator is a generator. Iterators "consume" values from a collection, generator "provide" them. But generators are a bit different than writers. For a writer, you decide when you push an element into it. On the other hand, generators provide you with a sequence of values, one by one. Java doesn't have any specific language support for generators. See also What is the difference between an Iterator and a Generator?
The opposite to iterators is something you could push values into. I don't think Java has any abstraction for that. The closes I have seen is Scala's Growable (neglecting the clear() method).
The closest is Observable but it isn't used so much.
public update(Observable o, Object arg)
I would not use Iterable instead of Reader and I would create a consumer of your choice.
A common pattern is to not use an interface but rather an annotation.
e.g.
#Subscriber
public void onUpdate(Update update) { }
#Subscriber
public void onInsert(Insert insert) { }
#Subscriber
public void onDelete(Delete delete) { }
When this class is added as a listener it subscribes to Update, Insert and Delete objects, and ignores any others. This allows one object to subscribe to different type of message in a Type safe way.
Here is what I decided to do (and I think its the best option out of what others gave :P ).
I'm going to backport Java 8's Lambda classes (java.util.functions.*). Particularly this one:
/**
* Performs operations upon an input object which may modify that object and/or
* external state (other objects).
*
* <p>All block implementations are expected to:
* <ul>
* <li>When used for aggregate operations upon many elements blocks
* should not assume that the {#code apply} operation will be called upon
* elements in any specific order.</li>
* </ul>
*
* #param <T> The type of input objects to {#code apply}.
*/
public interface Block<T> {
/**
* Performs operations upon the provided object which may modify that object
* and/or external state.
*
* #param t an input object
*/
void apply(T t);
// Some extension methods that I'll have to do with below.
}
Basically I'll make a new namespace like com.snaphop.backport.java.util.functions.* and move over the interfaces and make them work with Guava. Obviously I won't have the lambda syntax or the extension methods but those I can work around. Then in theory when Java 8 comes out it all I would have to do is a namespace switch.

Java - is this an idiom or pattern, behavior classes with no state

I am trying to incorporate more functional programming idioms into my java development. One pattern that I like the most and avoids side effects is building classes that have behavior but they don't necessarily have any state. The behavior is locked into the methods but they only act on the parameters passed in.
The code below is code I am trying to avoid:
public class BadObject {
private Map<String, String> data = new HashMap<String, String>();
public BadObject() {
data.put("data", "data");
}
/**
* Act on the data class. But this is bad because we can't
* rely on the integrity of the object's state.
*/
public void execute() {
data.get("data").toString();
}
}
The code below is nothing special but I am acting on the parameters and state is contained within that class. We still may run into issues with this class but that is an issue with the method and the state of the data, we can address issues in the routine as opposed to not trusting the entire object.
Is this some form of idiom? Is this similar to any pattern that you use?
public class SemiStatefulOOP {
/**
* Private class implies that I can access the members of the <code>Data</code> class
* within the <code>SemiStatefulOOP</code> class and I can also access
* the getData method from some other class.
*
* #see Test1
*
*/
class Data {
private int counter = 0;
public int getData() {
return counter;
}
public String toString() { return Integer.toString(counter); }
}
/**
* Act on the data class.
*/
public void execute(final Data data) {
data.counter++;
}
/**
* Act on the data class.
*/
public void updateStateWithCallToService(final Data data) {
data.counter++;
}
/**
* Similar to CLOS (Common Lisp Object System) make instance.
*/
public Data makeInstance() {
return new Data();
}
} // End of Class //
Issues with the code above:
I wanted to declare the Data class private, but then I can't really reference it outside of the class:
I can't override the SemiStateful class and access the private members.
Usage:
final SemiStatefulOOP someObject = new SemiStatefulOOP();
final SemiStatefulOOP.Data data = someObject.makeInstance();
someObject.execute(data);
someObject.updateStateWithCallToService(data);
Edit-1: This is a good comment. My response: "As soon as you make the Data class accessible outside the main class you are exposing implementation details, " -- comment.
My Response: The Data class is a simple POJO and will work like other pojos with setters and getters. What I was doing in the class above was trying to only manipulate the Data class from the behavior class, SemiStatefulOOP. I do intend to have stateless classes but I wanted to have a clear separation from the state classes and the behavior classes.
Related:
Stateless Design Pattern
http://guides.brucejmack.biz/Pattern%20Documents/Stateless%20Design%20Pattern.htm
There's an interesting OO architectural style that aims to separate the data and the behavior of a system, so that they can evolve independently: the DCI Architecture.
In practice, you create data objects for your domain concepts (possibly only with simple behavior related to the data itself); and behavior objects that work with the data objects and that realize the use cases of the system. These behavior objects are seen as roles that the domain objects can play, and are materialized with the OO concept of a trait (pdf).
Scala has traits, but Java doesn't. You can try to use the Qi4J framework in Java for that.
One of the key points of OO programming is that you hide implementation details. Your approach doesn't seem to be doing that - as soon as you make the Data class accessible outside the main class you are exposing implemntation details, and effectively exposing data representation.
It is of course impossible to make all classes stateless - something has to hold the state, and it's not clear to me why holding it in Data is preferable to holding it in the main class.
Finally a principle of OO programming is to keep data and functionality related to it in the same place, i.e. the same class. In short, while your proposal is interesting, I think the problems it creates are worse than the problems it solves.
building classes that have behavior
but they don't necessarily have any
state
See wiki
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
// The context class uses this to call the concrete strategy
interface Strategy {
int execute(int a, int b);
}
// Implements the algorithm using the strategy interface
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
System.out.println("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}
I'm not sure I understand quite what you're asking here. As an alternative to BadObject's statefulness, could you not simply declare the method as
public void execute(Map<String, String> data) {
...
}
or similar?
In general, when I think of functional and/or stateless idioms, the overwhelming code pattern that crops up is to have methods take parameters for everything they depend on (instead of getting them from fields or static methods or train wrecks (getFoo().getCustomer().getAddress().getHouseName())). That and return the result, rather than modifying the state of other objects.
At this point, all the data classes can be immutable since there's nothing to modify, which makes the code much easier to understand and reason about.
This wouldn't be one of the original GoF patterns, but I believe Josh Bloch has a paragraph on this in Effective Java entitled something like "Prefer immutability", which is catchy enough.
I think that the best solution to incorporate more functional programming into your projects is to use a functional programming language, like Scala. Scala is fully interoperable with Java and compatible with JVM. Scala classes is Java classes and vise versa. Why not to try it... :)
Java is full OOP language and my opinion is that functional paradigms just doesn`t fit nicely into it.
It looks like you have utility classes.
public class Data {
private static final Map<String, String> data = new HashMap<String, String>();
static {
data.put("data", "data");
}
private Data() { }
/**
* Act on the data class.
*/
public static void execute() {
data.get("data").toString();
}
}
You don't need to create an object.
Data.execute();

Closure and Callbacks

Is there any other way in java to implement call backs apart from inner classes? What is the difference between callbacks and closures?
Closure is how you build it, callback is how you use it.
A callback can be implemented as a closure (in languages that have them) or an implementation of an interface (in Java, as an anonymous inner class or a regular class).
Callback means that you pass a piece of code to a function, so that the function can call that piece of code later. It is a special kind of parameter.
The piece of code can be a function pointer or a closure or an object with well-known methods, depending on what the language offers.
Both closures and anonymous inner classes (and others) can be used as callbacks. A callback is just some code which is passed as an argument to other code.
A big difference of closures, compared to Java's anonymous inner classes, is that (in imperative languages) a closure can modify the variables of the surrounding scope. Wikipedia gives the following example:
var f, g;
function foo() {
var x = 0;
f = function() { return ++x; };
g = function() { return --x; };
x = 1;
alert('inside foo, call to f(): ' + f()); // "2"
}
foo();
alert('call to g(): ' + g()); // "1"
alert('call to f(): ' + f()); // "2"
A callback is just any executable code that is passed as a parameter to other code. In frequent usage, that executable code is a closure, but it's not necessarily.
The word closure is somewhat abused and many people just use it as a synonym for "anonymous function", but at least according to Wikipedia, that's a misuse of the term. The Wikipedia article explains this better than I can do quickly.
If you need closures in java you could try lambdaj. Here you can see how it allows to define closures through a very straightforward DSL.
I don't think so.
If there is, then it is probably inferior in some way, otherwise anonymous inner classes wouldn't be widely used.
There is no difference.
Closures can be defined as a block of code holding parent context that can be executed with ease.
In fact, the only difference I know between those is the ease of writing. A typical groovy/ruby closure is indeed smaller to write than a Java anonymous class.
However, considering Java framworks like guava and there liberal use of anonymous classes/interfaces, particularly for typical closures use cases like filter (comparing with groovy's implementation), I can say there is absolutely no design difference.
Sadly the only reasonable way is inner/anonymous classes.
You can also do it with reflection, but that usually is slower and harder in maintenance (no syntax highlighting, hard to find references in IDE etc.). An example:
myButton.addActionListener(EventHandler.create(ActionListener.class, handlerObject, "onClick"));
For now anonymous classes are the best way of handling callbacks in Java. However this is likely to change come Java 7 which will implement closures. http://en.wikipedia.org/wiki/Closure_(computer_science)
Here it is two implementations that uses closures and callbacks.
http://www.caglargonul.com/2013/04/05/playing-with-closures-in-java-7/
http://www.caglargonul.com/2013/04/05/java7-callback-implementation/
And here is a better example (can be found here http://www.caglargonul.com/2013/04/10/is-it-really-a-closure-yes-it-is/ ) for understanding what closure is. The key is that
a closure comes with a referencing environment not just a function code.
The best way to implement a closure in Java 7 and below is using an interface. In this example a callback is implemented as closure.
You first declare your interface which will hold your closure.
public interface CallBack {
void m(int e);
}
And lets add a class responsible for holding an array of closures, two public methods for adding and removing closures and a public function which will call the functions inside the closures when an event occurs.
public class CCallBack {
List<CallBack> cbs = new ArrayList<>();
public void registerCallBack(CallBack f){
cbs.add(f);
}
public void removeCallBack(CallBack f){
if(cbs.contains(f)){
cbs.remove(f);
}
}
public void onAction(int i){
for (CallBack callBack : cbs) {
callBack.m(i);
}
}
}
And here is the magical part. See the referencing environment in action.
public class CallBackTester {
CCallBack cb = new CCallBack();
#Test
public void test_callback(){
CallBack cb1 = new CallBack() {
int x = 1;
#Override
public void m(int e) {
if(e==1){
System.out.println("You register this callback " + x + " time/times");
x++;
}
}
};
cb.registerCallBack(cb1);
cb.registerCallBack(cb1);
cb.registerCallBack(cb1);
cb.removeCallBack(cb1);
cb.onAction(1);
}
}
Above when we declare cb1 we are adding a referencing environment which consists of the variable x. When we call the function inside this closure we are incrementing this variable by one. If it was a normal function, x would have been declared as 1 when we call the function. BUT IT IS NOT A NORMAL FUNCTION. IT IS A CLOSURE. So x is not declared every time we call the function in the closure. As you can see from the output every time we call it, x is incrementing.
You register this callback 1 time/times
You register this callback 2 time/times

Categories

Resources