Arrange Act Assert Pattern

It’s a pattern for arranging and formatting unit test methods. The main benefit of this pattern is that it clearly separates what is being tested from setup and verification steps.

The below are the steps defined in this pattern.

1. Arrange all necessary preconditions and inputs.
2. Act on the object or method under test.
3. Assert that the expected results have occurred.

Example unit test method is given below.


@Test
 public void testAdd() {
    int a = 10;
    int b = 10;
    		
    int c = Calculate.add(a, b);
    
    assertEquals(20, c);
 }

The above method is used for testing the “add” method defined in Calculate.java. In the first 2 lines, the input parameters(Arrange) are defined and in the 3rd line, the add method is getting called with the given input parameters(Act) and in the 4th line, the result value is getting verified(Assert).

Scala Either Monad

Either is one of the most useful monads in Scala. Its similar like Scala Option.
In this post, we are going to see how we can use this with an example.

Scala.Either

  • Its an abstract class extends Product.
  • Its an alternative to Option Monad.
  • An instance of Either is either an instance of scala.util.Left or scala.util.Right.
  • Left is used for failure and Right is used for success.
  • Mainly used in error handling.
  • The returned value is either an error or valid value.

Assume that we have a function and want to do some operation before doing that we want to do some validation and throw an error if the validation fails otherwise perform the operation and return the value.

Lets refer the below example to know how to do that with “Either” Monad.

ScalaEitherExample

The output is given below,

ScalaEitherExampleOutput

In the above example, we have a function “divide” which takes two values and perform divide operation and then return a result.

If the divisor is zero, then it will throw an error. So we first validate it and if the divisor is zero, then we will wrap the error in a case class “CalculationError” and return an instance of Left which represents an error.

If there is no error, then we will perform the divide operation and return the result as an instance of “Right” which represents success scenario

Scala String Interpolation

String interpolation is a feature of Scala and it enables us to embed variable references directly in processed string literals.

We have three kinds of Scala String interpolators. Let’s see them one by one.

s String interpolator
f String interpolator
raw String interpolator

s String interpolator:

When we prepend ‘s’ to any string, we can directly use variable in it with the use of $ character. But that variable should be in scope.


  val name = "John"
  println(s"My Name is $name")  // My Name is John

f string  interpolator
When we prepend ‘f’ to a processed string literal which allows  the creation of formatted strings, Its similar to “printf” in Java.


val height = 1.9d
val name = "John"
println(f"$name%s is $height%.2f meters tall")  // John is 1.90 meters tall

raw interpolator
It’s similar to ‘s’ interpolator except that it performs no escaping of literals within the string.

Refer the below example,


val name="John"
println(s"My name is \n$name")  //My name is
                                //John  

Here the s interpolator, replaced the character \n with a return character.  The “raw” interpolator will not do that.


val name="John"
println(raw"My name is \n$name") //My name is \n John

Scala App Trait

Scala contains a trait called “App” and its used to turn objects into executable programs.

We do not need to explicitly define “main” method in a Scala object, instead the whole class body becomes the main method.

Refer the below example,

ScalaMainApp

In the above code, we define an object “ScalaMain” and in the body of that object, we define a function “add” for adding two numbers. The whole code section becomes the main method.

Java 9: Immutable List, Set and Map

Java 9  provides a convenient way to create an immutable collections such as List, Set and Map. In this post, we are going to see that with few examples.

Prior to Java 9, To create an immutable collections, we have to follow the below approach. It works fine but its verbose.

ImmutableJava8

Now, in Java 9, we can easily, create an immutable list with the List.of() method.

The List.of method returns an instance of “java.util.ImmutableCollections.ListN” [extends AbstractImmutableList]. As this class extends AbstractImmutableList, the returned list is an immutable list, so trying to update it, will throw UnsupportedOperationException.

ImmutableList.JPG

We can follow the same way for creating an immutable Set and Map. Refer the below examples.

The Set.of method returns an instance of “java.util.ImmutableCollections.SetN” [extends AbstractImmutableSet]. Its immutable so trying to update it, will throw UnsupportedOperationException.

The Map.of method returns an instance of “java.util.ImmutableCollections.MapN” [extends AbstractImmutableMap]. Its immutable so trying to update it, will throw UnsupportedOperationException.

ImmutableSet.JPG

ImmutableMap.JPG

Scala Case Class

Scala class classes are like regular classes but with a few differences.  Those are given below.

Differences:

  • When we create a case class, it also creates a companion object implicitly with apply and unapply methods.
  • By default, Case classes are serializable.
  • Case class instances can be created without using the new keyword.  By default, the apply method of case class companion object will be called and it creates an instance of case classes.
  • Suitable for modeling immutable data.
  • Case classes automatically define the toString, equals and hashCode methods.
  • Case class constructor parameters are public val’s. So we can’t modify the values once it’s assigned. Because those parameters are immutable or constant.
  • Case classes automatically define the getter methods for constructor arguments.
  • It can be used in Pattern Matching operation.
  • It contains an implicit ‘copy’ which is used for creating a copy of a case class instance. We can also optionally change the constructor arguments.
  • Scala case classes can’t be extended by other case class.

CaseClass.JPG

Scala val, var and def

In this post, we are going to see the difference between var, val and def keywords of Scala.

Var –  If you want to create a mutable variable in Scala, then you have to use var keyword. For example, you want to create a variable and the value of that variable will be changed, then you need to use var keyword to define a mutable variable.

Val –  If you want  to create an immutable variable, then you have to use val keyword. Its like creating a constant value so once the value is assigned to a variable, then its never going to change. Even if you do, then you would get a compilation error.

def – To define a function, then you have to use this keyword.

Refer the below example, to know how to use these keywords.

val keyword usage:

In the below example, we use the ‘def’ keyword to define a function. We create a variable with ‘val’ keyword and then try to modify the value once its assigned. So when you do that, then you would get a compilation error.

ScalaExampleWithVal

var keyword usage:

ScalaExampleWithVar