Tuesday, June 30, 2020

Spring Framework Quiz

Take this quiz on Spring framework and evaluate yourself

Question #1: What is the annotation equivalent of the setter-based injection in XML?

Question #2: What’s the default scope of all the beans in a web application?

Question #3: How do you access a property version=1.0 present in a properties file?

Question #4: What annotation is used to defer the instantiation of beans?

Question #5: How do you get the reference of a @Component on a class MyAppCode?

Question #6: How do you wire a properties collection to a property?

Question #7: What is the central convenient class used for JDBC operations in Spring?

Question #8: What’s the root unchecked Exception that’s thrown by the Database Template classes?

Friday, June 19, 2020

10 Dos and Don’ts for getting started with Microservices

Too much noise about Microservices but still scratching your head where and how you can start? Here are the 10 Dos and Dont's.

  • Choose a simple/non-critical feature in your application, that you can afford to burn your fingers several times. Choose something like a Change Password functionality. You can develop the complete change password behaviour that involves validating the old password, accepting the new password, encrypting using BCrypt and Salt and storing them in the Database.
  • Don’t bother too much about the presentation layer. Concentrate on the core functionality and talk to the service using HTTP and exchange simple JSON data. Worry about WebComponents, Virtual DOM and the like later on.
  • Don’t develop it using the mothership technology of your project. If your project is implemented using RoR or .NET or Java implement the service using a technology other than these. For example, if your main application is built on Rails, use Spring Boot to implement the services. You can also use NodeJS.
  • Do not write more than 100 hundred lines of code to begin with. Remember it’s a microservice. Don’t make it a macro service and grow to be a giant. And that’s why we have chosen a small feature in first place.
  • Use a simple IDE like TextMate or Sublime Text or just Notepad++. Why do you need a mammoth editor that takes 5 minutes to open? In that 5 minutes you could easily complete half the service. 
  • Don’t worry about the Message Queues like RabbitMQ, Kafka etc., Do not complicate your service in the beginning itself. Keep it Simple, Stupid.
  • Learn Docker. Period. 
  • Throw away your Windows machine. Now, that’s very harsh!!! But if you want to jumpstart developing a service and quickly deploying to the cloud, please move away from the comfortable territory of Windows. Pick up a Mac or buy an Ubuntu or any Linux machine and start working.
  • Stop reading too many articles in this topic after some point. Just go ahead and implement it.

Tuesday, June 16, 2020

Kotlin - Decompiling Null safety operators - Part I (Using Java Decompilers to understand null safety operators in Kotlin)

We were recently writing some code using Kotlin programming language. After finishing the task, one of our friends glanced at the code and quipped, "Is question mark a first class citizen in Kotlin?". We took a step back and looked at the code dispassionately for a second and couldn't stop smiling. Please take a look at this code snippet in Kotlin.


	var tower = resultMap[code.trim()]
	tower?.occurences = value
	var weight:Int? = resultMap[code.trim()]?.weight
	nestedTower?.subTowers?.add(Tower(code.trim()))
						

You will notice a number of question mark (?) operators used here. Kotlin, the new language on the JVM, is getting popular with null safety operators being one of the reasons. The question-mark(?) operator also known as the safe navigation operator is not entirely new to programming languages. It's a commonly used one in languages like GroovyC# etc., for a long time. Kotlin introduces this safety operator and extends it with a couple of more operators in the safety front. 

Kotlin

To being with, let's understand the difference between the two types of declarations in Kotlin as shown below.


	var anInt:Int = 10
	var anotherInt:Int? = 20						
					

For the Java-only eyes, the declaration of anotherInt is bound to bring your brows together. anInt is a normal integer variable. anotherInt is also an integer variable declared using Int?Int? means, an integer value or null. So you can now assign null to anotherInt like this.


     anotherInt = null
							

anInt cannot be assigned to null, however. So Int? can be read as either integer or null. 

Decompiler speaks

Let's take the following Kotlin code written in Types.kt file and compile it


	fun main(arg:Array){
		var anInt:Int = 10
		var anotherInt:Int? = 20
		println(anotherInt)
		anotherInt = null
		println(anotherInt)
	}
	

We get TypesKt.class that you want to decompile. Let's use  JDPro in http://www.javadecompilers.com/. Here's what the decompiler gives us.


public final class TypesKt { 
   public static final void main(@org.jetbrains.annotations.NotNull 
   String[] arg) {
     int anInt = 10;
     Integer anotherInt = Integer.valueOf(20);
     System.out.println(anInt);
     System.out.println(anotherInt);
     anotherInt = (Integer)null;
     System.out.println(anotherInt);
  }
}				
				

So, the Kotlin compiler merely treates anotherInt? as a reference data-type, by using the wrapper class, Integer. Hmm! That's interesting. You will also notice that, since Kotlin is very strict about null-safety it injects @NotNullannotation to the command-line arguments arg. How about a safety operator on a reference data type like say a String?. Let's add these lines to the mainfunction in Kotlin and see what we get.

	
	var normalString:String = null
	var safeString:String? = null
	println(normalString)
	println(safeString)
	

Compiling this code will report an error that says, 

error: null can not be a value of a non-null type String
var normalString:String = null

Kotlin, just doesn't allow null values even on reference types declared in the normal fashion. Remember, in Java the following line of code compiles without any error

String normalString = null;

Decompiler speaks

Let's decompile the following code in Kotlin and see what it has to say.


	var normalString:String = "Normal string"
	var safeString:String? = "Safe string"
	println(normalString)
	println(safeString)
							

The decompiled code looks like this


	public final class TypesKt { 
		public static final void main(String[] arg) {
		 //...
	     String normalString = "Normal string";
	     String safeString = "Safe string";
	     System.out.println(normalString);
	     System.out.println(safeString);
	   }
	}
								

Since the Kotlin compiler performs the null checks, the decompiled code looks very similar to a regular Java piece. 

In the next part we'll take a look at accessing methods in a safe way and get introduced to couple of other operators.

Two services talking using NodeJS and Ruby, Sinatra.

There are a number of ways to make services or applications talk to each other. You can make one service access another service synchronously or asynchronously.

Usually two services can talk to each other each other using databases, or plain HTTP or using message queues. Message queues are used for asynchronous communication. 

Here's a short video that shows two services, one created using NodeJS and the other created using Ruby, Sinatra. NodeJS service uses axios HTTP library to access the Ruby Service.



Friday, June 12, 2020

Learn Go Language - Basics to Advanced Videos


Go lang

  • Language from Google
  • Natively compiled to machine language
  • The design is to restrict the language to have not more than 25 keywords
  • Not object-oriented
  • Docker, Kubernetes, Consul are built and based on Go
  • Statically typed, garbage collected
  • Open source
  • Has pointers, but no pointer arithmetic like C
  • Built-in concurrency model with Goroutines, channels
  • Concurrency is managed by the Go runtime unlike other programming languages where the OS kernel takes care





























Learn Java 13 and 14

1) Multi-line strings as Text Blocks:

2) Improved instanceOf (Pattern matching)

3) Enter Record (Data Class or Tuple)

4) Sealed Interfaces in Java

Multi-line strings as Text Blocks:

Multi-line strings in Java are finally here in the form of Text blocks. It’s available as a preview feature. So you need to use the switches ––enable-preview and ––release 13 or –release 14 while compiling and executing this code.

public class TextBlocks  {
     
public static void main(String[] args) {
       
String message = """
             Corona Alert!!!
                               
             Lockdown for 21 days!
             Stay calm!
        """
;    
       
       
System.out.println(message);
   
}
}

Compile it using

javac ––enable-preview ––release 13 TextBlocks.java

And when you run it java –enable-preview TextBlocks, you get the following output with the formatting preserved. The compiler also works towards removing trailing whitespaces and meaningless indentations.

Improved instanceOf (Pattern matching)

Let’s look at the use of instanceOf keyword in checking for the type of an object during runtime.

class Vehicle {}
       
class Car extends Vehicle {
 
public void drive() {
       
System.out.println("Driving car");
 
}
}

class Bicycle extends Vehicle {
 
public void ride() {}
}

public class InstanceOfKeyword {
 
public static void main(String[] args) {
       
Vehicle vObj = new Car();
       
if(vObj instanceof Car) {
           
Car car = (Car) vObj;
           car
.drive();
       
}
       
else if(vObj instanceOf Bicycle) {
         
Bicycle bike = (Bicycle)vObj;
          bike
.ride();
       
}
 
}
}

What’s frustrating with the above code is the type-cast of the vehicle object to Car or Bicycle after identifying it’s type using instanceof!

Java 14 changes that, by imparting some pattern matching power to instanceOf like this

       Vehicle vObj = new Car();
       
if(vObj instanceof Car car) {
          car
.drive();
       
}
       
else if(vObj instanceOf Bicycle bike) {
          bike
.ride();
       
}

In the new version, instanceOf tests for the type and binds to a variable of the type. In our case car and bike variables are automatically bound to the corresponding Car and Bicycleobjects respectively, eliminating the need to type-cast. Cool. Isn’t it?

The scope of the variables are limited to the if-else blocks

Enter Record (Data Class or Tuple)

Let’s continue with our lessons during this corona lockdown. In the last two posts we discussed textblocks and instanceof in Java 13 and 14.

Say, you have a shopping cart that is a collection of ShoppingItem with id, name, price and quantity members. Building this will involve writing so many lines of code as shown below.

class ShoppingItem {
   
private int id;      
   
private String name;
   
private double price;
   
private int quantity;
       
   
public ShoppingItem(int id, String name, double price, int quantity) {
       
this.id = id;
       
this.name = name;
       
this.price = price;
       
this.quantity = quantity;
   
}
       
   
public int getId() {
       
return id;
   
}
   
public void setId(int id) {
       
this.id = id;
   
}
   
public String getName() {
       
return name;
   
}
   
public void setName(String name) {
       
this.name = name;
   
}
   
public double getPrice() {
       
return price;
   
}
   
public void setPrice(double price) {
       
this.price = price;
   
}
   
public int getQuantity() {
       
return quantity;
   
}
   
public void setQuantity(int quantity) {
       
this.quantity = quantity;
   
}
       
   
public int hashCode() {
       
return id;
   
}
       
   
public boolean equals(Object obj) {
       
if(obj instanceof ShoppingItem item) {
               
return item.id == this.id;
       
}
       
return false;
   
}
   
   
public String toString() {
       
return name;
   
}
}

public class RecordsExample {
   
public static void main(String[] args) {
       
ShoppingItem book = new ShoppingItem(21321, "Programming Java", 12.34, 1);
       
ShoppingItem mobile = new ShoppingItem(21233, "iPhone 11 pro", 999, 1);
       
List<ShoppingItem> cart = Arrays.asList(book, mobile);
        cart
.forEach(System.out::println);
   
}
}

Phew! That’s lot of code for just storing some data

Code-Monkey-Computing-ReadabilityImage source: https://blog.submain.com/evaluate-code-readability/


Enter record

ShoppingItem class can be replaced with just one line code using a record. If you define a class as record with the members, the hashCode(), equals(), toString(), getters/setters are automatically generated for you by the compiler. So the code using record is as shown below.

public class RecordsExample {
   record
ShoppingItem(int id, String name, double price, int quantity) {}
   
public static void main(String[] args) {
       
ShoppingItem book = new ShoppingItem(21321, "Programming Java", 12.34, 1);
       
ShoppingItem mobile = new ShoppingItem(21233, "iPhone 11 pro", 999, 1);
       
List<ShoppingItem> cart = Arrays.asList(book, mobile);
        cart
.forEach(System.out::println);
 
}
}

This one line 
record ShoppingItem(int id, String name, double price, int quantity) {}
does the trick

Record in Java, in short is a data class or a tuple that’s a simple data structure.

Please remember to compile using –enable-preview and –release 14 switches

Sealed Interfaces in Java

In the last three posts we discussed textblocks, instanceof and record types in Java 13 and 14.

In languages like C#, sealed types are equivalent to final classes in Java. The problem with final classes in Java is no other class present in any other library can extend it. It’s tightly packed.
Now, Java is about to introduce a new sealed keyword, for creating sealed interfaces. We can create sealed interfaces and specify the types that can implement the interfaces. So sealed interfaces unlike final types, specify restricted implementations.

sealed interface Animal permits Dog, Cat {}
class Dog implements Animal {}
class Cat implements Animal {}
class Ant implement Animal {} //ERROR

In the code above, Animal is a sealed interface and only Dog and Cat classes can implement it. Ant will not be allowed to implement. So naturally even an anonymous/lambda implementation of Animal is also not possible. 

Therefore the compiler as well as the JVM enforce the implementation of sealed types.