Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣

Wednesday, May 20, 2020

Abstract Data Type

What is the data type?

A data type is an attribute in a programming language which define the domain of values and operations on that domain.

  • Define a certain domain of value. 
  • Define operations allowed on those values. 

Example 

int type
  • Take only integer values
  • Operations supported: addition, subtraction, multiplication, bitwise operation etc.  
float type 
  • Take only floating values 
  • Operations supported: addition, subtraction, multiplication, etc.  (it does not support operations like bitwise and modulus). 


Now, what is the user-defined data type? 

A user data type is NOT an attribute in a programming language but defines by the user which define the domain of values.

In below example, we define the user-defined data type using class. Here Person class is the type which is consist of bunch of String, LocalDate and Address fields. Person class have a user define a data type of Address.

Example

public class Person {
    private String firstName;
    private String lastName;
    private LocalDate dateOfBirth;
    private Address address;
   .....
}

public class Address {
   private String firstLine;
   private String lastLine,
   private State state;
  ....
}


Abstract Data Types (ADT)

Abstract Data Types (ADT) are like user define types which define values and operations on that user define type without specifying how the operation will happen.

Example

In this example, we will define an ADT where will create a data type named MyString class and define operations like addition, subtraction, multiplication and division. 

User Define Data Type 

  • MyString is a wrapper object of string. 
Let's define the operations of MyString data type.

User Define Operations 

  • The addition will concatenation two MyString. Example: "Hello" + " world" will result in "Hello world".
  • The subtraction will substring the difference of length. If the difference of length is zero or negative then it will have an empty string. Example: 
    • "Hello" - "world" will result in an empty string
    • "Hello" - "hi" will result in "Hel
    • "hi" - "Hello" will also result in an empty string. 
  • The division will remove common character(s) from MyString. Example: "Hello" / "world" will result in "He".
  • The multiplication will concatenate characters alternatively. Example: "Hello" * "world" will result in "Hweolrllod".

Actual Implementation 

Sample Unit Test of the Implementation 


Monday, April 27, 2020

One Time Password Generator

Simple code to generate One Time Password.
We are using java.util.SplittableRandom which was introduced in Java 8.

Output

Saturday, January 18, 2020

Exception flow control could be expensive.

As a developer sometimes we use exceptions as flow control. It could be expensive. I am going to show you how a simple change could help you to save a lot of time by simply not accepting exception as your code flow controller.
In this example, I will throw an exception if required data is not available during execution I will throw an IllegalArgumentException and in another case, I simply return a value using which call is going to take the decision based on the value then we will see how different it will be.




Code Output


In case of exception, it will take around a minute for execution and in another case it is insignificant. Both methods are invoked one million times to determine the impact.
Code Output
I request you to think again if you are using exception as your flow controller in a code which will be invoked many times.

Then what if I have to address an exception scenario 

If I need to address an exception scenario then for optimization I could pre-allocate the exception object so that I can use them multiple times.

Code Output


In this case, you can see the result is much better but still high than return statement.

Let me know your thoughts about it. 

Monday, July 15, 2019

JDK 12 switch statement... No expression

In Java language, there are lots of improvement and new paradigm changes like lambda expression, streams, etc.
In JDK 12 you can use switch statement as an expression instead of a statement. Okay, what is the difference?

Let's write code a code to understand the difference.


In the above code, you can clearly see these switch statement with fall through structure and irritating 😠 break statement. Expressing switch as a statement is error-prone, repetitive and roundabout.
In JDK 12 switch expression will come in non-fall through it means no break statement anymore.

So what does switch expression means?

static void howMany(int k) {
    System.out.println(
        switch (k) {
            case  1 -> "one"
            case  2 -> "two"
            default -> "many"
        }
    );
}

Let's rewrite the above come in JDK 12 using the latest switch expression and see how many lines of code we could reduce it and how readable our code it will be.

Keep it simple.

Oh ! please do remember that as this language enhancement not present in JDK 12 while compiling and running the JDK 12 code you need to add few arguments.



javac --enable-preview -source 12 -Xlint:preview Jdk12Switch.java 



java --enable-preview -source 12 Jdk12Switch 



 Please do share this with others and ask/discuss questions if you have.
Happy learning!

Wednesday, January 16, 2019

How to support multiple types of multi-tenancy database?

In this proposed solution, we are going to support multiple tenants with different types of multi-tenancy database models in one application.
To achieve this we need to have tenant identifier columns in all tables, and all query should have the association of tenant identifier as criteria.
We will be adding another column to have database identifier along with tenant identifier.
In this example, we have five tenants but T1 & T2 tenants have their own database implementation named D1 & D2 respectively, and T3, T4 & T5 tenant has the common database named ‘CD’/Common Database.


 

We going to have three databases named D1, D2 and CD, three data sources for these three databases. In application, we going to have the map of tenant identifier and the database identifier.  In the persistent layer of the application, we are going to retrieve the tenant identifier from the tenant context and get the data source with respect to it. We will be populating the tenant identifier in each persistence call and all the update, delete and retrieve call will have tenant identifier as criteria along with other criteria.
By this way, we can support multiple multiple types of multitenancy database implementation models.

Business Impact 

We can efficiently able to manage different categories of clients like we can group up small clients into a common database. As a result, these small clients will be benefited from shared storage cost and low database maintenance cost. On the other side, big clients could have their own database and it will make sure they can scale well in the future. 

Looking forward to your questions & suggestions.





Friday, January 26, 2018

Java Unit Testing of POJO class

I have created a tool to help the developer to do test coverage of their POJO Bean classes.

Java POJO classes are supposed to be tested while testing any business logic but in the real world, it does not happen. So I created this framework which will help developers while showing coverage to reviewers & auditors, and also help to discover silly mistakes which happen mostly during field name refactoring.

 I personally recommend developers that try to get these POJO tested while testing business logic if you somehow could not do it then this tool comes second.

This is a very simple to use the framework with lots of features which developers required in the real world.





Here is Wiki to learn this framework.


I am open to your feedback, please try it and let me know your feedback.

Monday, December 25, 2017

Spring Dependency Injection

Overview 
As a developer, we trend to create modular and loosely coupled applications. To accomplish modularity developer divided the application into multiple classes and each class depends on one or more other classes to accomplish desired functionality in an application. Spring is the most popular dependency injection framework for Java. 

Let take an example to understand the dependency. A person has a name. It also means 'Person' has a dependency on 'Name'. 

public class Person { 
       private Name personName; 

To accomplish independence from other dependent classes Spring framework provides Inversion of Control (IoC) which is basically inverting the dependency injection flow. In IoC, Spring container inject those dependencies when it creates the beans. We will now see how to define this bean and inject the dependent object in it. 


Type of dependency injection 
Primarily there are two types of dependency injection 
1.     Constructor-based dependency injection 
2.     Setter-based dependency injection 

Constructor-based dependency injection 
Constructor-based dependency injection is accomplished by constructor arguments where each argument represents the dependency. 

package example; 

public class Person { 
   private Name personName; 

// Dependency injected via argument by Spring 
   public Person(Name personName){ 
     this.personName = personName; 
   } 
Spring Bean Definition 
<bean id="personName" class="example.Name" /> 

<bean id="constructorExample" class="example.Person"> 
        <constructor-arg type="example.Name" ref="personName" /> 
</bean> 

Constructor based injection using static factory method 
package example;  

public class PersonFactory { 
public static Person createPerson(Name personName){ 
return new Person(personName); 

Spring Bean Definition 
<bean id="personName" class="example.Name" /> 

<bean id="person" class="example.PersonFactory"  
         factory-method="createPerson"> 
    <constructor-arg ref="personName" /> 
</bean> 
 


Setter-Based Dependency injection 
Setter-based dependency injection is accomplished by calling the Java bean write method (i.e. setter) on object which is created using no-argument constructor or no-argument static factory method.

public class Person { 
private Name personName; 
// Setter method so that Spring can inject the dependency  
public void setPersonName(Name personName){ 
this.personName = personName; 
Spring Bean Definition 
<bean id="personName" class="example.Name" /> 

<bean id="setterExample" class="example.Person"> 
        <property name="personName" ref="personName" /> 
</bean> 

Setter based injection using static factory method 
package example;  

public class Person {  
private Name personName;  

private Person(){ 


// Factory method 
public static Person createPerson(){ 
return new Person(); 

private void setPerson(Name personName){  
this.personName = personName;  
}  
Spring Bean Definition 
<bean id="personName" class="example.Name" />  

<bean id="person" class="example.Person"  
        factory-method="createPerson">  
<property name="personName" ref="personName" /> 
</bean> 




So, where to use constructor-based and when to use setter-based ?
Constructor based injection is recommended when we want dependencies to be injected during creation of object. In other words if dependency is absolutely mandatory then we will use constructor, and if dependency is option then we could use setter based injection. 
Now what if during first phase of development, dependency was optional so we used setter based injection but now due to change in requirement dependency is mandatory. To deal with this kind of scenario Spring provide an annotation @Required which actually enforce that setter based dependency must be populated during bean creation otherwise it will raise BeanInitializationException exception. 

public class Person {  
private Name personName;  
// Setter method so that Spring can inject the dependency  
 @Required 
 public void setPersonName(Name personName){  
    this.personName = personName;  
 }  


Spring Bean Definition 
<bean id="personName" class="example.Name" /> 

<bean id="setterExample" class="example.Person"> 
        <!-- Not injecting setter based dependency -->  
        <!--property name="personName" ref="personName" / --> 
</bean> 

Exception message will be printed as "Property 'personName' is required for bean 'setterExample'". 
So technically developers need to take decision based on their business requirement which type need to use.