Tuesday, November 21, 2017

Template method design pattern

This is another very important design pattern in Java and another core design pattern which is used in Spring framework.Template method design pattern is a behavioral design pattern. This is used to define a the flow of execution of the application.

Just think you need to build a building. Then you should begin it with foundation. You can't begin it with the roof. Likewise you can define the flow using this design pattern. 

Look at the following example. 

package com.app.designPatterns;

abstract class Building {

    abstract void makeFoundation();
    abstract void makeWalls();
    abstract void makeRoof();

    public final void build(){

class OfficeBuiding extends Building{

    void makeFoundation() {
        System.out.println("Make foundation");

    void makeWalls() {
        System.out.println("Make walls");

    void makeRoof() {
        System.out.println("Make roof");

public class TemplateDemo{

    public static void main(String args[]){
        Building building = new OfficeBuiding();

Here you can see three classes. If you going to build a office building, it will be done in certain way. This flow cannot be changed. So if you want to create another building, you can do the same way. 

As you can see, the template method is final. That is why it cannot be changed. Look at the following class diagram for two buildings.

When it uses ?
  • javax.servlet.http.HttpServlet doGet() and doPost() methods.
  • In Spring framework - In Spring framework, it uses so many templates. These templates are created based on template method design pattern. 
  • All non abstract methods of followings
    1. java.io.InputStream
    2. java.io.OutputStream
    3. java.io.Reader
    4. java.io.Writer 
  • All non abstract methods in followings too.
    1. java.util.AbstractList
    2. java.util.AbstractSet
    3. java.util.AbstractMap
  • JDBC template uses this design pattern - In JDBC template we don't need to care about the open, close connections and so on. This is automatically done by the template itself. It executes the core workflow, we don't need to manage it. 

Compile-time polymorphism vs Run-time polymorphism

This is very important interview question. Simply Compile-time polymorphism is known as overriding and Run-time polymorphism is known as overloading. I think you may know about the differences between both of overloading and overriding. (OOP concepts)

But question is this, If someone asked why it is called compile-time polymorphism and run-time polymorphism ? Lets try to find out the answers by examples.

Overriding is called run-time polymorphism. WHY ???

Look at the following example.

//Parent class
class Parent {
    public void eat(){
        System.out.println("Parent - eat()");

//Child class
class Child extends Parent {

    public void eat() {
        System.out.println("Child - eat()");

public class OOPDemo {

    public static void main(String args[]){
        Parent obj = new Child();

In this example I've created a parent class, child class and the main class. Then I've created a Child object by Parent reference. 

Compile time
  • In compile time it takes care about the Parent reference. Because objects are created in the run time
  • First it checks is there any eat() method in Parent class. 
  • In this example Parent class has eat() method. 
  • So it doesn't give any exception in the compile time and compilation will be success.
Run time
  • In run time it takes care about the Child reference and it creates new Child object.
  • Then it checks is there any eat() method in Child class. 
  • There is a eat() methods in Child also. Then this method will be called in the run time. 
  • It means object creation is happen at the run time by JVM and Run time is responsible to call which eat() method to call.
  • That is why it is called run-time polymorphism (Dynamic polymorphism)

Overloading is called compile-time polymorphism. WHY ???

Look at the following example.

class Animal{

    public void eat(){
        System.out.println("Eat method");

    public void eat(int quantity){
        System.out.println("Eat method with quantity");

public class ReferenceDemo {
    public static void main(String args[]){
        Animal animal = new Animal();

In this case single class has same methods with two different parameters. As you know it is called method overloading. 

Compile time
  • In compile time it checks animal.eat() method in Animal class. 
  • No arg eat() method is there in the animal class.
  • According to the parameter list it will call which method should be called.
  • Then compilation is OK.

Run time
  • In run time it creates same Animal type object.
  • Then it checks the same thing what is did in the compile time.
  • It means compile time is enough to check which method should be called.
  • That is why it is called Compile time polymorphism ( Static polymorphism).


Overriding    = run-time polymorphism         = dynamic polymorphism
Overloading  = compile-time polymorphism  = static polymorphism

Wednesday, November 15, 2017

Monolithic architecture vs Microservices architecture

If you need to create an enterprise application according to your needs, first of all you should think about the architecture which your application depends. Mainly there are two approaches to begin.

  1. Monolithic architecture
  2. Micro services architecture

Monolithic architecture

  • It is just like a laptop. All things are packed as a single unit.
  • Monolithic architecture means, it makes your application as a single unit. 
  • It looks just create a single jar or war.
  • This is the easiest way to create an application. 
  • If the process goes with waterfall model, this can be the best choice.
  • But if you have a heavy project, application code base will be huge.
  • Still if you want to go with it, you should have a proper coding standards with comments. Otherwise it won't be easy to for future developments. 

Advantages of Monolithic architecture
  • Easy to develop
  • Easy to deploy
Disadvantages of Monolithic architecture
  • Not easy to expand services (Continuous development is difficult).
  • It is really hard to go with Agile method.
  • Huge code base. It is really hard to understand for new developers in future.
  • In this architecture all of the services are connected to one single database. So it will make huge server load.
  • Sometimes it will take a long time to start the web application because of the overloaded web container. 

Microservice architecture

  • It is just like a desktop computer. Several units work together. 
  • I described about Microservices in my previous post. 
  • Microservice architecture makes your application as a set of loosely coupled services.
  • There are a small set of services connecting each other as a one application. 
  • Simply it is not a one single project which is connected to one single database.

Advantages of Microservices
  • It is easy to handle errors. Because services are independent.
  • Easy understanding curve for developers for future developments.
  • Each services can be developed independently.
  • One of the best option for Agile development.
  • Application starts fast and runs smoothly.

Disadvantages of Microservices

  • Creating a microservice based application is really complex.
  • Testing is more difficult.
  • It should have a better communication between developers. Because several services will hit only one front end.
When to use Microservices ?

This is totally depend on the organizational requirements. Microservices produce a pack of services and enables fast delivery with easy testable units. If your company needs to go faster than ever, it may be a reason to change system with microservices. 

Other reason is, if your system is still growing with adding new functionalities, it is better to use microservices. Because microservices are small components of services, You can add new components according to your requirements. 

Tuesday, November 14, 2017

Maintain server logs

Maintain logs in very important thing. There are lot of ways to do this. Here I'm not going to do hard things. This is just a simple example of maintain server logs using a shell script.

Here I'm planing to do some tasks.
  1. Delete old log files
  2. Save last log file 
  3. Zip it and save in another place.
This can be used in your local server to maintain logs and it will be very easy because you need not to delete logs every time and save logs.

# Delete files

#file path for logs

#file path for eventspace default log

#files to be deleted

#Get the yesterday
yesterday=$(date -d '-1 day' '+%Y-%m-%d');

#get the full file name of last day server.log

cd $file_path;

#remove files in file_path

rm $file1
rm $file2
rm $file3
rm $file4

cd $file_path_eventspace;

if [ -s $lastLogFile ]
 #backup the last log file as zip
 tar -zcvf $lastLogFile.tar.gz $lastLogFile;

 #move file to var/logs/myAppLogs
 mv $lastLogFile.tar.gz /var/log/myAppLogs/
 #remove last log file
 rm $lastLogFile;
 echo "Last log file canot be found";


Sometimes it will be not easy to understand if you are a beginner. Let me explain.

There are two file paths.

  • file_path - Location of default log file located.
  • file_path_myApp - Location of application log file located

Then I've defined four file types that needs to be deleted. 

  • file1='catalina.2017-*';
  • file2='host-*';
  • file3='localhost*';
  • file4='manager*';

Then I get the date of yesterday because I need to to zip yesterday log file with the date as a file name (lastLogFile).

Then I remove files using rm command in Linux. 

  • rm $file1

Then I zip the yesterday file using tar -zcvf command.

  • tar -zcvf $lastLogFile.tar.gz $lastLogFile;

Then I move file to another location using mv command. 

  • mv $lastLogFile.tar.gz  /var/log/myAppLogs/

There are many file paths, you need to change all those file names with your locations. All commands are simple Linux commands. 

How to run a shell script file

Once you create your .sh file, you need to run it from terminal.
  • Go to your file location and right click and open terminal in same location( Otherwise you will need to change the path ).
  • Give file permission to the file.
                    chmod +x fileName.sh
  • Run your sh file.

Add a cronjob

Another special thing is you can add your script as a cronjob and it will run automatically according to the parameters which are given. For example if you need to run it in every minute, you can add following line to system crontab.

* * * * * /media/ravi/Data/Cronjob/deleteLogs.sh

Open you terminal and type crontab -e

Add your cronjob (Above mentioned line)

Save file.

  • Ctrl + X
  • Type y
  • Enter

You will be able to see like this.

You can change your cronjob with your requirements. 

Data access object design pattern

This is another very important design pattern. Before you learn about this design pattern, it is better to understand about following points. 

What is DAL (Data Access Layer) ?

  • Simply data access layer is used to handle database access in applications.
  • In Layered Architecture, it is a best practice to use a separate layer for data access.
  • Data access layer is being used to achieve this.
  • DAO design pattern and Repository design pattern can be used to implement that Data access layer.

What is DAO (Data Access Object) ?
  • Usually this is used to connect both service layer and database layer as I mentioned above.
  • The main purpose of using DAO is to hide implementation data with the usage of interfaces.
  • Normally we define DAOs for each and every entity. Eg: UserDao.java
  • DAOs return data as object state.

What is DTO (Data Transfer Object) ?
  • Simply this can be a JSON object that can be used to get request data and send response data. 
  • If you design APIs, JSON objects are being used as request and response objects. Eg: UserRegRequestJson.java, UserRegResponseJson.java

Look at the following UML diagram to understand about the way of using DAO design pattern. 

Advantages of using DAO 

  • Hide implementation data.
  • Reduce code complexity.
  • Centralized data access to separate layer called Data Access Layer.

Disadvantages of DAO

  • This is not the smartest way to achieve those advantages, if you are using a framework like Spring with Spring Data JPA, it can simplify everything than using DAO.