Thursday, 6 September 2018

Why an abstract class has a constructor?

Constructor do not create an object, they are used to initialize the object properties.

Constructor in abstract class is useful, while initializing the common properties of sub classes.

For example, I am going to build an employee management system with below requirements.
a.   Employee should have id, firstName and lastName.
b.   System should maintain the created date and modified date of the employee information.
c.   Address should have information about House Number, street, city and country.
d.   System should maintain the created date and modified date of the address information.

We can design the model classes like below.

public abstract class AbstractModel {
         private String id;
         private Date createdDate;
         private Date modifiedDate;
}


public class Employee extends AbstractModel {
         private String firstName;
         private String lastName;
}

public class Address {
         private String houseNum;
         private String street;
         private String city;
         private String country;
}




Since the fields id, createdDate and modifiedDate are common for models Employee and Address, we can use the abstract class constructor to define these common variables.

public abstract class AbstractModel {
         private String id;
         private Date createdDate;
         private Date modifiedDate;

         public AbstractModel() {
                  id = UUID.randomUUID().toString();
                  createdDate = new Date();
                  modifiedDate = new Date();
         }
        
}

Find the below working application.

AbstractModel.java
package com.sample.model;

import java.util.UUID;
import java.util.Date;

public abstract class AbstractModel {
 private String id;
 private Date createdDate;
 private Date modifiedDate;

 public AbstractModel() {
  id = UUID.randomUUID().toString();
  createdDate = new Date();
  modifiedDate = new Date();
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public Date getCreatedDate() {
  return createdDate;
 }

 public void setCreatedDate(Date createdDate) {
  this.createdDate = createdDate;
 }

 public Date getModifiedDate() {
  return modifiedDate;
 }

 public void setModifiedDate(Date modifiedDate) {
  this.modifiedDate = modifiedDate;
 }

 @Override
 public String toString() {
  return "AbstractEntity [id=" + id + ", createdDate=" + createdDate + ", modifiedDate=" + modifiedDate + "]";
 }

}


Employee.java
package com.sample.model;

public class Employee extends AbstractModel {
 private String firstName;
 private String lastName;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", getId()=" + getId()
    + ", getCreatedDate()=" + getCreatedDate() + ", getModifiedDate()=" + getModifiedDate()
    + ", toString()=" + super.toString() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
    + "]";
 }

}

Address.java
package com.sample.model;

public class Address {
 private String houseNum;
 private String street;
 private String city;
 private String country;

 public String getHouseNum() {
  return houseNum;
 }

 public void setHouseNum(String houseNum) {
  this.houseNum = houseNum;
 }

 public String getStreet() {
  return street;
 }

 public void setStreet(String street) {
  this.street = street;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  return "Address [houseNum=" + houseNum + ", street=" + street + ", city=" + city + ", country=" + country
    + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString()
    + "]";
 }

}

Application.java

package com.sample.app;

import com.sample.model.Employee;

public class Application {
 public static void main(String args[]) {
  Employee emp = new Employee();
  emp.setFirstName("Krishna");
  emp.setLastName("Ponnam");

  System.out.println(emp);
 }
}


Output
Employee [firstName=Krishna, lastName=Ponnam, getId()=fd5f179a-f59b-4d38-be80-b789b0049b9e, getCreatedDate()=Thu Sep 06 09:10:54 IST 2018, getModifiedDate()=Thu Sep 06 09:10:54 IST 2018, toString()=AbstractEntity [id=fd5f179a-f59b-4d38-be80-b789b0049b9e, createdDate=Thu Sep 06 09:10:54 IST 2018, modifiedDate=Thu Sep 06 09:10:54 IST 2018], getClass()=class com.sample.model.Employee, hashCode()=1360875712]

You may like

Threads: print characters of a string simultaneously



As you see above image, two threads must simultaneously prints the data simultaneously.

Thread1 prints 1st character of string, thread2 print 2nd character of string, thread1 prints 3rd character and so on…

We can achieve this using wait and notify methods of object class.
Assume data = "Hello World";

In this example, procedure is like below.
a.   Initialize the counter to 0, set the flag to true
b.   For thread1, acquire the lock on ‘data’ object. If flag is true, then print the data[counter], increment the counter and release the lock and notify the threads before releasing. If flag is false, then release the lock by calling wait method on data object.
c.    For thread2, acquire the lock on ‘data’ object. If the flag is false, then print the data[counter], increment the counter and release the lock and notify the thread2 before releasing. If flag is tur, then release the local by calling wait method on data object.

Find the below working example.

Test.java
package com.sample.arrays;

public class Test {
 private static final String data = "Hello World";
 private static boolean flag = true;
 private static int count = 0;

 private static Thread t1 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (!flag) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread1 =>" + data.charAt(count++));
      flag = false;
      data.notify();
     }

    }
   }
  }
 };

 private static Thread t2 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (flag) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread2 =>" + data.charAt(count++));
      flag = true;
      data.notify();
     }

    }
   }
  }
 };

 public static void main(String args[]) {
  t1.start();
  t2.start();
 }
}


Enhancing above application. Since thread1 print the characters at even positions and thread2 print the characters at odd positions. We can use the counter variable itself to achieve this behavior.


Test.java
package com.sample.arrays;

public class Test {
 private static final String data = "Hello World";
 private static int count = 0;

 private static Thread t1 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (count % 2 != 0) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread1 =>" + data.charAt(count++));
      data.notify();
     }

    }
   }
  }
 };

 private static Thread t2 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (count % 2 == 0) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread2 =>" + data.charAt(count++));
      data.notify();
     }

    }
   }
  }
 };

 public static void main(String args[]) {
  t1.start();
  t2.start();
 }
}

Let’s enhance this by extending it for three threads.


Test.java

package com.sample.arrays;

public class Test {
 private static final String data = "Hello World";
 private static int count = 0;

 private static Thread t1 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (count % 3 != 0) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread1 =>" + data.charAt(count++));
      data.notifyAll();
     }

    }
   }
  }
 };

 private static Thread t2 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (count % 3 != 1) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread2 =>" + data.charAt(count++));
      data.notifyAll();
     }

    }
   }
  }
 };
 
 private static Thread t3 = new Thread() {
  int dataLength = data.length();

  public void run() {
   while (count < dataLength) {
    synchronized (data) {
     if (count % 3 != 2) {
      try {
       data.wait();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     } else {
      System.out.println("Thread3 =>" + data.charAt(count++));
      data.notifyAll();
     }

    }
   }
  }
 };

 public static void main(String args[]) {
  t1.start();
  t2.start();
  t3.start();
 }
}

Previous                                                 Next                                                 Home

Wednesday, 5 September 2018

Open-closed principle design problem

Suppose a drawing application is implemented like below.

Shape.java
package com.sample.model;

public enum Shape {
 CIRCLE("circle"), SQUARE("square"), RECTANGLE("rectangle");

 private Shape(String type) {
  this.type = type;
 }

 private String type;

 public String getType() {
  return type;
 }

}

Drawer.java
package com.sample.util;

import com.sample.model.Shape;

public class Drawer {
 private Shape shape;

 public Shape getShape() {
  return shape;
 }

 public void setShape(Shape shape) {
  this.shape = shape;
 }

 public void draw() {
  if (Shape.CIRCLE.getType().equals(shape.getType())) {
   System.out.println("Drawing Circle");
  } else if (Shape.RECTANGLE.getType().equals(shape.getType())) {
   System.out.println("Drawing Rectangle");
  } else if (Shape.SQUARE.getType().equals(shape.getType())) {
   System.out.println("Drawing Square");
  }
 }
}

Application.java

package com.smaple.app;

import com.sample.model.Shape;
import com.sample.util.Drawer;

public class Application {
 public static void main(String args[]) {
  Drawer drawer = new Drawer();
  
  drawer.setShape(Shape.SQUARE);
  drawer.draw();
  
 }
}

Above code breaks the design principle “Open to extension, closed to modification”.

As per Open-closed principle, software entities such as classes, methods should be open for extension and closed for modification. That is we can extend the behavior of software entity, without touching the source code of the entity.

For example, there is a class ‘ConnectionFactory’, it provides number of methods to connect to databases like MySQL, MongoDB, Elasticsearch etc., Assume there are number of classes using this ConnectionFactory. Even if you change single line in ConnectionFactory class, you need to retest all the modules that are using ConnectionFactory class. If you design your code like this, you will end up in testing all the dependent modules often.

Open-closed principle solved this problem in straightforward way.

Rule 1: Design a module such that, it never change.

Rule 2: When requirements change, extend (Inheritance) the behavior of an entity by adding new code.

Modules that follow above two rules are open for extension and closed for modification.

Let’s redesign the drawing application like below.


Shape.java
package com.sample.model;

public interface Shape {
 void draw();
}

Circle.java
package com.sample.model;

public class Circle implements Shape{

 public void draw() {
  System.out.println("Drawing Circle");
 }

}

Square.java

package com.sample.model;

public class Square implements Shape {

 public void draw() {
  System.out.println("Drawing Square");
 }

}


Rectangle.java

package com.sample.model;

public class Rectangle implements Shape {

 public void draw() {
  System.out.println("Drawing Rectangle");
 }

}

Drawer.java

package com.sample.util;

import com.sample.model.Shape;

public class Drawer {
 private Shape shape;

 public Shape getShape() {
  return shape;
 }

 public void setShape(Shape shape) {
  this.shape = shape;
 }

 public void draw() {
  if (shape == null) {
   return;
  }
  shape.draw();
 }
}


Application.java

package com.smaple.app;

import com.sample.model.Square;
import com.sample.util.Drawer;

public class Application {
 public static void main(String args[]) {
  Drawer drawer = new Drawer();
  
  drawer.setShape(new Square());
  drawer.draw();
  
 }
}




Monday, 3 September 2018

JavaScript: trim elements of array

You can trim the elements of array by calling the pop method on the array. There is another smart way also; using length property of array you can trim the array.

arr.length = 3;
Above statement keeps only 3 elements.

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        function printArr(arr) {
            document.write("<br /> Elements in array are <br />");
            for (i = 0; i < arr.length; i++) {
                document.write(arr[i] + " ");
            }
        }

        var arr1 = [2, 3, 5, 7, 11, 13, 17, 19, 23];
        printArr(arr1);

        document.write("<br /><br /> Trimming last 3 elements");
        arr1.length = arr1.length - 3;
        printArr(arr1);

        document.write("<br /><br /> Trimming last 4 elements");
        arr1.length = arr1.length - 4;
        printArr(arr1);
    </script>
</body>

</html>

Open above page in browser, you can able to see following data.

Elements in array are
2 3 5 7 11 13 17 19 23

Trimming last 3 elements
Elements in array are
2 3 5 7 11 13

Trimming last 4 elements
Elements in array are
2 3


Previous                                                 Next                                                 Home

JavaScript: split: get an array from string

split method is used to split the string by using given separator and retun an array of elements.

Example
string.split(separator);

array.html
<!DOCTYPE html>

<html>

<head>
    <title>Array</title>
</head>

<body>
    <script type="text/javascript">
        var str = "1:2:3:4:5:6:7"
        var arr = str.split(":");

        for (i = 0; i < arr.length; i++) {
            document.write(arr[i] + " ");
        }
    </script>
</body>

</html>


Open above page in browser, you can able to see following content.
1 2 3 4 5 6 7




Previous                                                 Next                                                 Home