Above, Below, and Beyond Tech Talk

by Rahel Lüthy

March 22, 2015

JavaFX 3D Line

I have no experience in 3D programming whatsoever. Last week, I took my first steps in JavaFX 3D, but hit a wall when I wanted to draw a line between two points: There is no Line shape! The only out-of-the-box Shape3D classes are Box, Cylinder, Sphere, and MeshView – wow…

Well, it shouldn’t be too difficult to connect the points with a slender cylinder, right?

I was wrong, it took me an embarrassingly long time to get the trigonometry right :-)

Here’s my magic crutch:

public Cylinder createConnection(Point3D origin, Point3D target) {
    Point3D yAxis = new Point3D(0, 1, 0);
    Point3D diff = target.subtract(origin);
    double height = diff.magnitude();

    Point3D mid = target.midpoint(origin);
    Translate moveToMidpoint = new Translate(mid.getX(), mid.getY(), mid.getZ());

    Point3D axisOfRotation = diff.crossProduct(yAxis);
    double angle = Math.acos(diff.normalize().dotProduct(yAxis));
    Rotate rotateAroundCenter = new Rotate(-Math.toDegrees(angle), axisOfRotation);

    Cylinder line = new Cylinder(1, height);

    line.getTransforms().addAll(moveToMidpoint, rotateAroundCenter);

    return line;
}

To illustrate what’s going on, I created a 2D representation of all individual steps, starting off with the creation of the cylinder. By default, its center is placed at the origin:

The moveToMidpoint transformation moves its center to the final location (the yellow midpoint in the above image):

And finally, the rotateAroundCenter transformation corrects the cylinder’s direction:

Obviously, the tricky part is finding the proper axis and angle of rotation. Both are calculated relative to the yAxis because of the cylinder’s initial direction. The axisOfRotation must be perpendicular to the plane defined by the yAxis and the diff vector. To find such a perpendicular vector, we can (by definition) calculate the cross product of the two vectors. In the 2D case, the result is equivalent to the z-axis, but in 3D it may be tilted.

The angle is calculated based on the dot product (aka scalar product) of the two vectors, which is defined by

A • B = |A| |B| cos(alpha)

If A and B are both unit vectors, this becomes

A • B = cos(alpha)

which we can resolve to

alpha = acos(A • B)

That’s it!


February 27, 2015

Scala Gems #9: Regex Extractors

Suppose you have a simple date string: "2015-02-27"

Regular expressions allow to parse the date and extract parts thereof[^1]: (\d\d\d\d)-(\d\d)-(\d\d) defines a pattern which matches the digits and defines capturing groups for the year, month, and day parts.

In Java, a simple example usage would look like this:

Pattern pattern = Pattern.compile("(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)");
Matcher matcher = pattern.matcher("2015-02-27");
while (matcher.find()) {
    System.out.println("Year: " + matcher.group(1));
    System.out.println("Month: " + matcher.group(2));
    System.out.println("Day: " + matcher.group(3));
}

Accessing the groups by index is rather awkward and error prone. Luckily, Java 7 introduced support for named groups:

Pattern pattern = Pattern.compile("(?<year>\\d\\d\\d\\d)-(?<month>\\d\\d)-(?<day>\\d\\d)");
Matcher matcher = pattern.matcher("2015-02-27");
while (matcher.find()) {
    System.out.println("Year: " + matcher.group("year"));
    System.out.println("Month: " + matcher.group("month"));
    System.out.println("Day: " + matcher.group("day"));
}

That’s better, but I personally don’t like how the group names pollute the pattern. Regular expressions are hard to read already, the Java escape characters add yet more clutter, and the additional ?<group> constructs are a kiss of death.

Let’s look at how the same problem can be tackled in Scala:

According to the docs, the canonical way to create a Regex is by using the method r, which is provided implicitly for strings:

val Date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r

Note the triple quotes, which allow to use the backslashes without further escaping. While this is nice, the true advantage of Scala is that regular expressions can be used as extractors in a pattern match. The pattern stays plain and simple, and yet we have all the freedom to name groups as we please:

"2015-02-27" match {
  case Date(year, month, day) =>
    println(s"Year: $year")
    println(s"Month: $month")
    println(s"Day: $day")
}

Look ma, no clutter! [^1]:Yes, using java.time.format.DateTimeFormatter would be easier in this simple case.


February 11, 2015

Java 8 Optional

Tony Hoare, inventor of the null reference, apologetically called it “the billion dollar mistake”.

The problem with null is not that it was invented back in 1965, but that we are still struggling with it 50 years later. Any Java developer has probably seen and written code like this:

String result = service.find("id");
String value;
if (result != null) {
    value = result.trim();
} else {
    value = "<absent>";
}
System.out.println("Value: " + value);

In fact, most Java monoglots have probably seen and written code like this so many times, that they don’t even see the problem anymore. And yet, with Java 8, they have to deal with a solution: the Optional type.

I recently came across this popular article: Embracing the Void: 6 Refined Tricks for Dealing with Nulls in Java. It gives a nice rundown of strategies around the null reference. Sadly, it discourages the use of Java 8’s Optional. In this post I will explain why the argumentation is flawed.

Types to the rescue

One way to re-write the above snippet using Optional could look like this:

Optional<String> result = service.find("id");
String value;
if (result.isPresent()) {
    value = result.get().trim();
} else {
    value = "<absent>";
}
System.out.println("Value: " + value);

The service returns an Optional<String> and the caller is working her way around it. From a complexity point of view, the change is argueably not much of an improvement: We still need a mutable value variable, and the overall logic is roughly the same. And yet, the expressiveness has improved. The signature of the service has clearer semantics now. Originally, the caller of the service could not distinguish between “the implementor of the service made a programming error” and “the value has not been found” – both were resulting in null. This is possible now and – even better – the type system forces the caller to deal with absents values.

But wait, there’s more

Now that the semantics are straight, let’s make the value variable immutable and eliminate the if .. else construct:

Optional<String> result = service.find("id");
final String value = result.orElseGet(() -> "<absent>").trim();

This code is safer, more expressive, and more concise than the original version, but the () -> "..." clutter makes my Scala heart cringe, so I’m offering yet another variant:

Optional<String> result = service.find("id");
String value = result.map(String::trim).orElse("<absent>");

We are taking advantage of the fact that Optional behaves like a collection: If it is absent, it behaves like an empty list, the call to map is never executed, and the result is an empty Optional (which we handle via orElse). If the result is present, it behaves like a list with one element, which we trim and return.

Wrapping legacy code

Imagine that our original service interface is actually coming from a 3rd party library. You can’t simply change all the signatures to properly return Option<T>. But you can wrap the service calls and create yourself a null-safe world:

Optional<String> result = Optional.ofNullable(legacyService.find("id"));

Unboxing a cat in a box in a box

And finally: The holy grail of functional programming, flatMap.

Let’s start with a simple User which has an optional middle name:

interface User {
    String getName();
    Option<String> getMiddleName();
}

Looking up the user via service is straightforward, but look at all those types:

Optional<User> result = service.find("id");
Optional<Optional<String>> middleName = result.map(User::getMiddleName);

The outer Optional is the result of the map call (presence/absence of User), while the inner Optional is wrapping the middle name value.

flatMap is our power tool to unwrap the value from nested Optionals:

String middleName = result.flatMap(User::getMiddleName).orElse("Ada");

So next time you can’t remember the semantics of flatMap, just think of all those cats stuck in their nested boxes:

(via [@channingwalton](https://twitter.com/channingwalton/status/447778554114502657))

I highly recommend The Neophyte’s Guide to Scala - Part 5: The Option Type for anyone interested in further details.


Older Posts » Archive