-
The Call of ChrismathuluR.J. LorimerFri, Nov 7 2008 @ 2:38 pm
-
Getting True Java Classes in JRubyR.J. LorimerThu, Sep 25 2008 @ 6:41 pm
-
JRuby 1.1.4 ReleasedR.J. LorimerFri, Aug 29 2008 @ 5:41 am
-
My XBoxR.J. LorimerMon, Aug 25 2008 @ 3:22 am
-
Why So Serious?R.J. LorimerSat, Aug 23 2008 @ 5:25 am
Functional Programming in Java/Javascript
One ability with modern Javascript I haven't explored too much yet is functional programming, or as the W3C calls it, higher order programming.
Whatever you call it, it is pretty cool stuff; basically implying that a function itself is a value. There really is no direct counterpart to functional programming in strict, statically typed object-oriented languages such as Java. Instead, it is really a different school of thought than OO.
Technically speaking, however, OO has design patterns (such as the command pattern) which mimic functional programming in some ways - Let me show this through an example from the Javascript page linked to above:
function wrap(tag) {
var stag='<'+tag+'>';
var etag='</'+tag.replace(/s.*/,'')+'>';
return function(x) {
return stag+x+etag;
}
}
This can be accomplished in Java like this:
// Define our 'function' interface
public interface Tag {
public String print(String innerVal);
}
// Define our wrap method on some class.
// ...
public static Tag wrap(String tagName) {
// notice the final declaration
// this allows for the anonymous
// inner class.
final String sTag = "<"+tag+">";
final String eTag = </"+tag.replace("/s.*/", "")+">";
return new Tag() {
public String print(String value) {
return sTag + value + eTag;
}
};
}
// ...
// use the new tag like this:
Tag b = wrap("B");
System.out.println(b.print("hello!"));
The Java solution is, no question, more verbose, but, it is effectively the same thing (it is also a contrived example, because it is rare that HTML generation is explicitly done in Java now-a-days).
You could also declare a convenience implementation of Tag that takes sTag and eTag as constructor arguments (rather than using an inner class):
public class StandardTag {
private String sTag;
private String eTag;
public StandardTag(String start, String end) {
sTag = start;
eTag = end;
}
public String print(String value) {
return sTag + value + eTag;
}
}
// ...
public static Tag wrap(String tagName) {
// no longer need to declare as final.
String sTag = "<"+tag+">";
String eTag = </"+tag.replace("/s.*/", "")+">";
return new StandardTag(sTag, eTag);
}
Interestingly enough, the interface (Tag) is not neccessary for this example as long as the Tag class is a public member. It makes the code more flexible however, and in general is a good practice.
