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.

Reply

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is used to make sure you are a human visitor and to prevent spam submissions.