Cyclops: Functional data structures – Vector creation methods.

In the previous posts we have looked into immutability and persistence, now let’s have a look how to create a Vector with the static methods Vector.empty(), Vector.of(..), Vector.fill(..), Vector.generate(..) and Vector.range(..).

public class VectorCreationMethodsTest {
private String a = "Angel";
private String b = "Berta";
@Test
public void vectorEmpty_Then_AnEmptyVectorIsCreated() {
Vector<String> vector = Vector.empty();
assertThat(vector.size()).isEqualTo(0);
}
@Test
public void vectorOf_When_SomeElementsAreProvided_Then_AVectorWithTheElementsIsCreated() {
Vector<String> of = Vector.of(a, b);
assertThat(of).hasSize(2).containsOnly(a, b);
}
@Test
public void vectorFill_When_ObjectAndAMaxNumberIsProvided_Then_AVectorWithNumberOfObjectsIsCreated() {
Vector<String> fill = Vector.fill(a, 5);
assertThat(fill).hasSize(5).containsOnly(a);
}
@Test
public void vectorGenerate_When_SupplierAndAMaxNumberIsProvided_Then_AVectorWithNumberOfSupplierResultsIsCreated() {
Supplier<Employee> supplier = Employee::new;
Vector<Employee> generate = Vector.generate(supplier, 5);
assertThat(generate).hasSize(5).hasOnlyElementsOfType(Employee.class);
}
@Test
public void vectorRange_When_RangeIntegerValuesAreProvided_Then_AVectorWithIntegersInTheRangeIsCreated() {
Vector<Integer> range = Vector.range(1, 5);
assertThat(range).hasSize(4).containsOnly(1, 2, 3, 4);
}
}

Cyclops: Functional data structures – Persistence

In the previous post we have looked into immutability. Vector, VectorX and other data structures are also persistent.

Let’s see an example:

public class PersistenceTest {
private String a = "Angel";
private String b = "Marc";
private String c = "Lucy";
private String d = "Bert";
@Test
public void givenACyclopsVector_whenTheVectorIsModified_thenPreviousVersionIsNotChanged() {
Vector<String> vector = Vector.of(a, b, c);
vector.append(d);
assertThat(vector).contains(a, b, c).doesNotContain(d);
}
}

Cyclops: Functional data structures – Immutability

I’ve been looking for immutable collections later on and I came across Cyclops. Cyclops extend the JDK collections with immutable, persistent, eager and lazy data types.

In this post I’ll look into immutability.

In the example used data structures:

  • ListX extend List with functional operations and can be used as mutable and immutable list.
  • Vector can replace ArrayList when an immutable and persistent List is needed.
  • Vector is an eager and VectorX a lazy data structure.

public class ImmutabilityTest {
private String a = "Tom";
private String b = "Marc";
private String c = "Lucy";
private String d = "Bert";
@Test
public void givenUsingJava8List_whenListIsCreated_thenListIsMutable() {
List<String> java8MutableList = new ArrayList<>(Arrays.asList(a, b, c));
java8MutableList.add(d);
assertThat(java8MutableList).contains(d);
}
@Test
public void givenUsingListX_whenListIsCreated_thenListXIsMutable() {
ListX<String> list = ListX.of(a, b, c);
list.add(d);
assertThat(list).contains(d);
assertThat(list).isInstanceOf(List.class).isInstanceOf(LazyCollectionX.class);
}
@Test
public void givenUsingCyclopsVector_whenVectorIsCreated_thenVectorIsImmutable() {
Vector<String> vector = Vector.of(a, b, c);
assertThat(vector).isInstanceOf(ImmutableList.class);
}
@Test
public void givenUsingCyclopsVectorX_whenVectorIsCreated_thenVectorIsPersistentAndLazy() {
VectorX<String> vectorLazy = VectorX.of(a, b, c);
assertThat(vectorLazy).isInstanceOf(PersistentList.class).isInstanceOf(LazyCollectionX.class);
}
@Test
public void givenUsingJava8List_whenUnmodifiableListIsCreated_thenListIsImmutable() {
List<String> java8List = new ArrayList<>(Arrays.asList(a, b, c));
List<String> unmodifiableList = Collections.unmodifiableList(java8List);
ThrowingCallable throwingCallable = () -> unmodifiableList.add(d);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(throwingCallable);
}
@Test
public void givenUsingJava9List_whenListIsCreated_thenListIsImmutable() {
List<String> java9List = List.of(a, b, c);
ThrowingCallable throwingCallable = () -> java9List.add(d);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(throwingCallable);
}
}

Further Reading:

Digging into the EJB Specifications: Stateless Session Bean Identity with @EJB and @Inject

I have looked into the EJB specifications in the past weeks and the chapter about the Session Bean Identity captured my attention.

From the EJB 3.2 specification section 3.4.7.2 Stateless Session Beans Identity:

@EJB Cart cart1;
@EJB Cart cart2;
if (cart1.equals(cart1)) { // this test must return true
}
if (cart1.equals(cart2)) { // this test must also return true
}

I did some tests to confirm the above statements and then switched from @EJB to @Inject, just to be curious, as many posts are suggesting them being interchangeable.

cart1.equals(cart1)
The first statement’s result – true – may sound obvious and probably it is.
If the reference were managed in a standalone java application, using new to create a new instance, that would be the case.

Because in a Java EE application the EJB management is done from the container i.E. application server and we do not create an instance with new but we just inject one, leaving the container to decide whether to create or reuse an existing instance, that might not be the case.

(cart1.equals(cart2)
The second statement’s result – true– might not be so obvious.
The container manage to return for cart1 and cart2 the same reference for the same Session Bean Interface (in that case Cart).

The tests – guess what – confirmed the above assumptions, the interesting part is the next question:

Are in this case @Inject and @EJB interchangeble?
Well the answer  according to tests is NO, the statement (cart1.equals(cart2) returns always false using @Inject.

Resources:

JSR-000345 EJB 3.2 Final Release

Demo with @EJB

Demo with @Inject

Null Pointer Exception check with Java 8 – How to use Optional – Resources

In the past weeks we went throw the Java 8 Optional object, in this post; links to previous posts, source codes and useful links.

How to use Optional:
the Counter Class
the Counter Class Part 2

The Select-Some-Values-and-Do-Something Pattern:

Part 1:
Post Part 1
CounterJava7 – Code
CounterJava8 – Code

Part 2:
Post Part 2
Code 1
Code 2

Part 3:
Post Part 3
Code

TestCases:
Counter Tests

Useful Links:
Tired of Null Pointer exceptions?
Java 8: Removing null checks with Optional
Java 8 Optional In Depth
Working With Java 8 Optionals
10 examples of optional

Null Pointer Exception check with Java 8 – How to use Optional – the Select-Some-Values-and-Do-Something Pattern: Part 3

In the Part 1 and Part 2 we have refined the Java 8 version of the pattern, in this post, we will continue to explore how Optional methods improves the code.

In the Part 2 we have seen that one test case failed because the result of filter() can be an Optional.empty() object.
Instead of solving the problem with a classic if-statement pattern, we could use the orElse() method. The orElse() method returns a default object when the Optional object is empty.

Do you think the following code will work?

public void increment(Optional incrementValue) {
        if (endValue.isPresent() && incrementValue.isPresent()) {
            currentValue =
                    currentValue.filter(a -> (a  a + incrementValue.get())
                                .orElse(currentValue);
        }
    }

unfortunately no, the orElse() breaks the statement and the code do not compile.

Let’s illustrate the problem with the help of the following simplified unit test:

@Test
    public void result_is_not_empty_with_orElse_Test() {

        Optional currentValue = Optional.of(20);
        Optional result = currentValue.filter(a -> a  a+1);
        Integer orElse = result.orElse(555);
        assertEquals((Integer) 21, orElse);
    }

The Field result’s type is Optional, orElse() returns the (wrapped) Integer value and not the required Optional assignable to currentValue (that’s the reason the code do not compile).
One way to solve the problem is to wrap result itself – with Optional.of() – in a Optional object, something like: Optional<Optional>.
That’s exactly what the following modified code is doing:

public class CounterJava8WithFilterMapAndOrElse extends CounterJava8{

    @Override
    public void increment(Optional incrementValue) {
        if (endValue.isPresent() && incrementValue.isPresent()) {
            currentValue =
                    currentValue.filter(a -> (a  Optional.of(a + incrementValue.get()))
                                .orElse(currentValue);
        }
    }
}

the code compile and the unit tests looks fine.

Maybe there are further nicer versions of the above pattern but for the time being, we will stick with this one.
I hope you enjoyed the tutorial so far, in the next post my favorite list of Optional resources.

Null Pointer Exception check with Java 8 – How to use Optional – the Select-Some-Values-and-Do-Something Pattern: Part 2

In the previous post we made an attempt to rewrite the Select-Some-Values-and-Do-Something pattern, the attempt was not so satisfactory.

In this post, we want to explore how the Optional methods – expecially the ones using optional values avoiding explicit if-not-null tests – can make the code neat.

The code expressing the Select-some-values pattern: currentValue.isPresent() && currentValue.get() < (endValue.get() - incrementValue.get() can be rewritten using filter().

The code for the Do-Something, which in the example is more a trasforming-the-currentValue, pattern; currentValue = Optional.of(currentValue.get() + incrementValue.get()) can be rewritten using map().

Let’s see how the new version of the Counter class is looking like:

public class CounterJava8WithFilterAndMap extends CounterJava8{

    @Override
    public void increment(Optional incrementValue) {
        if (endValue.isPresent() && incrementValue.isPresent()) {
            currentValue =
                    currentValue
                    .filter(a -> (a  a + incrementValue.get());
        }
    }
}

Is the code above working as expected? Let’s see the unit tests:
Screenshot - 21.06.2017 , 10_14_25

ouch, one test failed!

Do you see already where is the problem?

The filter() is returning – for the failed testcase – an Optional.empty() object and this is assigned to currentValue.

You could change the logic as follows:

public class CounterJava8AndIsPresent extends CounterJava8{
    @Override
    public void increment(Optional incrementValue) {
        if (endValue.isPresent() && incrementValue.isPresent()) {

            Optional map = currentValue.filter(a -> (a  a + incrementValue.get());
            if (map.isPresent()) {
                currentValue = map;
            }
        }
    }
}

and this will make the failed unit test working, but perhaps we can do something better as we will see in the next post.

Links:

CounterJava8.java
CounterJava8AndIsPresent.java

Null Pointer Exception check with Java 8 – How to use Optional – the Select-Some-Values-and-Do-Something Pattern: Part 1

Let’s add a simple increment(Integer value) function to the Java 7 Counter Class  to prove the pattern:

public void increment(Integer incrementValue) {
   if (currentValue != null && endValue != null
       && incrementValue !=null     // if-not-equal-null
       && currentValue < (endValue - incrementValue)  // Select-some-values
       ) {
          currentValue+=incrementValue;  // do-something
         }
}

Using an Optional object, you can rewrite the code as follows:

public void increment(Optional incrementValue) {
   if (currentValue.isPresent() && endValue.isPresent() && incrementValue.isPresent()
       && currentValue.get() < (endValue.get() - incrementValue.get()))
      {
       currentValue = Optional.of(currentValue.get() + incrementValue.get());
      }
}

By comparing the two codes, we notice that:

  1. The if-not-null pattern was rewritten with isPresent() and looks cleaner than the Java 7 code
  2. To use the values wrapped in the  Optional object, we need the get() method, compared to the Java 7 code an overhead
  3. The Java 8 code also need Optional.Of to wrap the new calculated value back to the Optional object

Rewriting the Java 7 code as we did above is not the perfect way to use Optional, that will be the goal of the next post.

For the time being, the two codes should function the same way and to make this sure, let’s do some unit testing:

public class CounterTest {

    private CounterJava7 counterJava7;
    private CounterJava8 counterJava8;

    private Integer target;
    private Integer incrementValue;

    @Test
    public void currentValue_is_one_increment_is_two_test() {

        target = (Integer) 3;
        incrementValue = 2;
        counterJava7 = new CounterJava7(20, 1);
        counterJava7.increment(incrementValue);
        assertEquals(target, counterJava7.getCurrentValue());

        counterJava8 = new CounterJava8(20, 1);
        counterJava8.increment(Optional.of(incrementValue));
        assertEquals(target, counterJava8.getCurrentValue());
    }

    @Test
    public void currentValue_plus_incrementValue_is_above_endValue_test() {

        target = (Integer) 1;
        incrementValue = 20;
        counterJava7 = new CounterJava7(20, 1);
        counterJava7.increment(incrementValue);
        assertEquals(target, counterJava7.getCurrentValue());

        counterJava8 = new CounterJava8(20, 1);
        counterJava8.increment(Optional.of(incrementValue));
        assertEquals(target, counterJava8.getCurrentValue());
    }

    @Test
    public void currentValue_plus_incrementValue_is_below_endValue_test() {

        target = (Integer) 11;
        incrementValue = 10;
        counterJava7 = new CounterJava7(20, 1);
        counterJava7.increment(incrementValue);
        assertEquals(target, counterJava7.getCurrentValue());

        counterJava8 = new CounterJava8(20, 1);
        counterJava8.increment(Optional.of(incrementValue));
        assertEquals(target, counterJava8.getCurrentValue());
    }

    @Test
    public void currentValue_and_endValue_are_default_test() {

        target = (Integer) 5;
        incrementValue = 5;
        counterJava7 = new CounterJava7();
        counterJava7.increment(incrementValue);
        assertEquals(target, counterJava7.getCurrentValue());

        counterJava8 = new CounterJava8();
        counterJava8.increment(Optional.of(incrementValue));
        assertEquals(target, counterJava8.getCurrentValue());
    }

    @Test
    public void incrementValue_is_Null_test() {

        target = (Integer) 15;
        incrementValue = null;
        counterJava7 = new CounterJava7(10, 15);
        counterJava7.increment(incrementValue);
        assertEquals(target, counterJava7.getCurrentValue());

        counterJava8 = new CounterJava8(10, 15);
        counterJava8.increment(Optional.ofNullable(incrementValue));
        assertEquals(target, counterJava8.getCurrentValue());
    }

    @Test
    public void currentValue_is_null_test() {
        try {
            counterJava8 = new CounterJava8(Integer.MIN_VALUE, null);
            fail();
        } catch (NullPointerException e) {}

        try {
            counterJava7 = new CounterJava7(Integer.MIN_VALUE, null);
            fail();
        } catch (IllegalArgumentException e) {}
    }

    @Test
    public void currentValue_and_endValue_are_null_test() {
        try {
            counterJava8 = new CounterJava8(null, null);
            fail();
        } catch (NullPointerException e) {}
        try {
            counterJava7 = new CounterJava7(null, null);
            fail();
        } catch (IllegalArgumentException e) {}
    }
}

and the output:

Null Pointer Exception check with Java 8 – How to use Optional – the Counter Class Part 2

Elaborating on the earlier post, where we have introduced the Java 8 Counter Class as an example on how to model absent values and how to create an Optional object using Optional.of, we will see in this post how the Counter Class logic could be coded in Java 7 emphasizing differences and doing some tests.

Here the Java 7 Counter Class:

public class CounterJava7 {

private Integer endValue;
private Integer currentValue;

public CounterJava7(Integer endValue, Integer currentValue) {
   if (endValue == null | currentValue == null) {
      throw new IllegalArgumentException();
   }
   this.endValue = endValue;
   this.currentValue = currentValue;
   }
}

see the differences between the constructors?

Java 8 Optional.of throws implicitly and immediately a NullPointerException if the argument is null, the Java 7 code needs to do the checking explicitly.

Let’s see how the unit tests looks like:

@Test
public void currentValue_is_null_test() {
   try {
      counterJava8 = new CounterJava8(Integer.MIN_VALUE, null);
      fail();
      } catch (NullPointerException e) {}

  try {
      counterJava7 = new CounterJava7(Integer.MIN_VALUE, null);
      fail();
      } catch (IllegalArgumentException e) {}
}

@Test
public void currentValue_and_endValue_are_null_test() {
   try {
      counterJava8 = new CounterJava8(null, null);
      fail();
      } catch (NullPointerException e) {}
   try {
      counterJava7 = new CounterJava7(null, null);
      fail();
      } catch (IllegalArgumentException e) {}
}

Null Pointer Exception check with Java 8 – How to use Optional – the Counter Class

There are many good articles about Optional and Java 8 out there, Tired of Null Pointer Exceptions inspired me to do some tests, the results will be published in the next posts.

In this post: The Counter Class I’ve been using in my testing:

public class Counter {

private Optional endValue;
private Optional currentValue;

public Counter(Integer endValue, Integer currentValue) {
this.endValue = Optional.of(endValue);
this.currentValue = Optional.of(currentValue);
}
}

What’s new on the code above?

Well first that a Counter might or might not have a endValue and a currentValue, that’s what the Optional is telling us.

Second is the usage of Optional.of.

If endValue or/and currentValue were Null, a NullPointerException is thrown, as you can see in the following test:

@Test(expected = NullPointerException.class)
public void testConstructorWithOneNullValue() {
counter = new Counter(null, Integer.MIN_VALUE);
}

@Test(expected = NullPointerException.class)
public void testConstructorWithBothNullValues() {
counter = new Counter(null, null);
}

netbeans64 01.06.2017 , 16:26:35 Java8Examples - NetBeans IDE 8.2

By the way: if a Null Value is allowed, then you need to use Optional.OfNullable.