Java8 Lambda Functions – anti-side effect programming

In some coding recently, I thought I saw an opportunity to explore Java8’s support for lambda expressions. I basically had a function I needed to call, once with one set of data, and once with another. I could repeat the logic (hey, it’s only 2 calls), I could write a method, or, maybe this is a candidate for a lambda expression.

In the below code, pre method or lambdas, the basic logic is that I’m examining a string to see if it’s wrapped in ‘/*’ ‘*/’. If it is, I’m stripping those off and returning that it was wrapped.

boolean isWrapped1 = false, isWrapped2 = false;
    
// first, strip off any comment wrappers, so we can appropriately parse
if (response2.endsWith("*/")) {
  response2 = response2.substring(0, response2.length() - 2);
  if (response2.startsWith("/*")) {
    response2 = response2.substring(2);
  }
  isWrapped2 = true;
}
  
if (response1.endsWith("*/")) {
  response1 = response1.substring(0, response1.length() - 2);
  if (response1.startsWith("/*")) {
    response1 = response1.substring(2);
  }
  isWrapped1 = true;
}


Written in lambda style…
boolean isWrapped1 = false, isWrapped2 = false;

Function<String, Boolean> isWrapped = s -> {
 if (s.endsWith("*/")) {
    s = s.substring(0, s.length() - 2);
    if (s.startsWith("/*")) {
      s = s.substring(2);
      return true;
    }
 }
 return false;
};

isWrapped1 = isWrapped.apply(response1);
isWrapped2 = isWrapped.apply(response2);


Now, the rub… and one which I realize would bite me in a method implementation, as well… I’m relying in my first implementation on the side effect that the string gets stripped of the ‘/*’. There’s no side-effects for strings when dealt with in a function. The original string goes in, you can muck with it all you want inside, and the original string is _still_ the one there on the outside.

Thinking it through, what I need to do is consider writing a 2nd lambda, so the code would look something more like this:

Function isWrapped {..
};

Function unwrap {..
};

isWrapped1 = isWrapped.apply(response1);
if (isWrapped1) {
  response1 = unwrap(response1);
}
isWrapped2 = isWrapped.apply(response2);
if (isWrapped2) {
  response2 = unwrap(response2);
}

Using strings clearly helped enforce no side-effect programming here… which, practically, makes for a better functional approach, at least per my understanding. Since I don’t intend to make those functions visible in any other place than within the invoking method, it appears to be a decently good pattern for DRY, without necessarily adding to the interface footprint of my class. Almost creates an approach of something even more private than private…

Leave a Reply

Your email address will not be published. Required fields are marked *