30 March 2016

Exploring Scala foldLeft and foldRight

Scala collections let you "fold" the data in the collection into a single result. In the Scaladoc, it says that it "Folds the elements of this traversable or iterator using the specified associative binary operator."

Let's play with this concept. Since fold() is the most flexible and powerful, let's warm up by looking at the simpler foldLeft and foldRight methods.

These fold* operations will apply to a collection, so let's create a simple one:
scala> val a = List(1,2,3)
a: List[Int] = List(1, 2, 3)
scala> a.foldLeft(7)(_+_)
res1: Int = 13

What just happened? We created a List of integers, and called foldLeft on the List. We provided two parameters. The first is the start value, in this case 7. The second is a binary operation, in this case an addition.

Since foldLeft applies the binary operation to the start value and each of the elements in the collection, going left to right, the steps to the result are:
7 + 1 = 8
8 + 2 = 10
10 + 3 = 13

22 March 2016

Scala Collections: A Group of groupBy() Examples

Scala provides a rich Collections API. Let's look at the useful groupBy() function.

What does groupBy() do? It takes a collection, assesses each item in that collection against a discriminator function, and returns a Map data structure. Each key in the returned map is a distinct result of the discriminator function, and the key's corresponding value is another collection which contains all elements of the original one that evaluate the same way against the discriminator function.

So, for example, here is a collection of Strings:
val sports = Seq("baseball", "ice hockey", "football", "basketball", "110m hurdles", "field hockey")

Running it through the Scala interpreter produces this output showing our value's definition:
sports: Seq[String] = List(baseball, ice hockey, football, basketball, 110m hurdles, field hockey)

We can group those sports names by, say, their first letter. To do so, we need a discriminator function that takes each element and returns the first character. For example:
sports.groupBy(_.charAt(0))

Running that in the interpreter shows the result:
res0: scala.collection.immutable.Map[Char,Seq[String]] = Map(b -> List(baseball, basketball), 1 -> List(110m hurdles), i -> List(ice hockey), f -> List(football, field hockey))

As you can see, the result is a Map with four key-value pairs. The keys are the letters b,i,f and the digit 1. All of the sports names that begin with "b" are grouped into a new List, and so on for the other sports.

15 March 2016

Moving a Collection Task to Java 8 Lambdas and Streams

On a recent project, I encountered a function that had been copy-pasted to a dozen places in the code base. That in itself is a classic Code Smell, and I determined to extract it to a common, reusable function.

The block of lines also repeated an action over several elements in a larger collection. Since this team had recently moved to Java 8, I decided to rewrite this code using Lambdas and the Stream API.

The project's code base used a class called DBRecord as a very flexible extended Collection, representing the data in a single row from a relational database. It was designed to contain one Collection of the various field values for the row of data, and another Collection of meta-data defining the traits of the fields themselves.

Another wrinkle was the state of denormalization of their underlying data model. The team has traditionally not been interested in following Third-Normal-Form design patterns, resulting in as much duplicated and repeated data in their table structures as there is in their code base.

As a result, one database table had multiple columns generically named "SortField1" through "SortField5". It was sometimes necessary to act when any one or more of the SortFields had data. But they were not guaranteed to be consecutive; any one of these fields could have data or not, independent of the others. So the code base had variations of the following code sprinkled throughout:
if ( record.getString(record.getField("sortfield1")).isEmpty()
&& record.getString(record.getField("sortfield2")).isEmpty()
&& record.getString(record.getField("sortfield3")).isEmpty()
&& record.getString(record.getField("sortfield4")).isEmpty()
&& record.getString(record.getField("sortfield5")).isEmpty() )
{
// no data so do something appropriate
}
else
{
// at least 1 piece of data, so do something else
}

9 March 2016

How to Disable Windows Rotate Screen Keyboard Shortcut

I love keyboard shortcuts and hot-keys. I learn and use as many of them as I can.
Sometimes, however, the same short-cut can get defined by multiple parts of a system and can create surprising results.

For example: when working in Eclipse IDE, a very useful one is CTRL-ALT-UP (or DOWN) arrow. It takes whatever line the cursor is currently on and duplicates it above or below the current line. It also works on highlighted blocks of lines.
I use it all the time to preserve the original form of a line or block. For example, when I am writing unit-tests that are all related, I take the one I just wrote and CTRL-ALT-DOWN to copy it, then I modify the duplicated code for my next test. Saves retying the boiler-plate.
I may also use it when modifying some code. I duplicate it with CTRL-ALT-DOWN keyboard short cut and then while the line(s) are highlighted still, I do a CTRL-ForwardSlash which in Eclipse comments out the line. This preserves the original line while I tinker and experiment.

7 March 2016

ScalaFX MenuBars: Can I Right-align one Menu?

A question arose recently: can we move the Help menu item to the right edge of the active window?
In an earlier post, I looked at some basics of Menu-related controls in ScalaFX, and wrote some simple code for ScalaFX to create a basic menu bar that looked like this:


Our three Menus are all left-aligned, which is pretty standard in the realm of desktop applications.
So: does ScalaFX give us the controls and hooks that we need in order to adjust the alignment and push the last menu to be Right-aligned?