Tuesday, 28 April 2020

SOLID Principle

SOLID Priniciples - for code refactor and smells code means first identify wrost code, then apply SOLID principles to refactor.


S - Single Responsibility
O - Open for extension / Closed for Modification (Strategy Pattern )
L - Liskov Substutions
I  - Interface Segression
D - Dependency Inversion ( Template Method Pattern)

Here S-0 principle based on responsibilities and L - I based on split responsiblities.

S - Single Responsibility
    "A class should have only one reason to change"
Usecase: we need an object to keep an email message.
interface IEmail {
        public void setSender(String sender);
        public void setReceiver(String receiver);
        public void setContent(String content);
}

Email Responsibilites: setSender, setReceiver
Content Responsibilites: setContent (Currently supporting String content only)

Now we got new feature: we need to support html, pdf feature content. But our current Email supports String content type

Solution: Then we need to take more care String content convert it into interface like Below.
interface IContent {
      public String getAsString(); //used for serialize
}

Now our modified IEmail Interface:
interface IEmail {
        public void setSender(String sender);
        public void setReceiver(String receiver);
        public void setContent(IContent content);
}

class Email implments IEmail {
        public void setSender(String sender) {   //implment }
        public void setReceiver(String receiver) {   //implment }
        public void setContent(IContent content) {   //implment }
}



Open Close Principle : Open for extension but closed for modifications

Through bad coding to good coding we will demonstrate this example.

abstract class Shape {     class Rectangle extends Shape {        class Circle extends Shape {
    int m_type;                         Rectangle() {                                     Circle() {
}                                                    super.m_type = 1;                          super.m_type = 2;
                                         }  }                                                      }}

//Open-close priniciple bad example -
class GraphicEditor {
            public void drawShape(Shape s) {
                  if(s.m_type==1) {   drawRectangle() ; }
                  else if(s.m_type==2) { drawCircle(); }
              }
           
               //circle responsible behaviour
               public void drawCircle(Circle c) {       }
       
                //rectangle responsible behaviour
              public void drawRectangle(Rectangle r) {    }
}

In the bad code having rectangle and circle behaviours.
circle - behaviour - drawCircle();
rectangle - behaviour - drawRectangle();

Issue: if we add new shape then we need to change drawShape() and also add the new drawMehtod() into GraphicEditor.

Solution: In the new design we use abstract draw() method in GraphicEditor for drawing objects. draw() implmentation into the concrete shape objects.


abstract class Shape {     class Rectangle extends Shape {        class Circle extends Shape {
abstract void draw();       draw() {                                               draw() {
}                                                    //implment                                            //implment
                                         }  }                                                      }}


class GraphicEditor {
            public void drawShape(Shape s) {
                  s.draw();
            }
}


Now no changes required when a new shape is added (Good !!)

Please refer Strategy pattern which will suitable for this principle.







D - Dependency Inversion principle "Depend on Abstract/Interface not concrete classes"
I will explain 2 ways this principle

  • "High-level modules should not depend on low-level modules, both should depend on abstractions" style.

Class Manager {                                                                      Class Worker {
       Worker worker;                                                                          public void work() {
        public void setWorker(Worker worker) {                                      System.out.println("working");
              this.worker = worker;                                                          }
        }                                                                                        }
         public void manager() {
                  worker.work();
         }
}

Now company introduced new specialized worker then we need to change Manager class also
Class SuperWorker {
              public void work() {
                  System.out.println("super working");
              }
}

Solution: Now Design a new Abstraction Layer is added through the IWorker interface.

interface IWorker {   public void work() ; }

class Worker implements IWorker {     public void work() { System.out.println("working"); } }

class SuperWorker implements IWorker { public void work() { System.out.println("super working"); } }


Class Manager {
          IWorker worker;
          public void setWorker(IWorker worker) {
                   this.worker = worker;
          }
          public void manager() {
                  worker.work();
           }
}


  • "Concrete classes should depend on interfaces and abstract classes because they change less often and more higher level modules" style.

In this template method design pattern concrete classes depend on parent class House method buildHouse(), this parent method changes very less often.






   
     


     


Friday, 10 April 2020

Microservices

I am categorizing the microservices as two ways
1) Developing Microservices
2) Deploying Microservices

Small overview about the Docker:

Container like similar feature of Virtual Machine. Containers are not meant to host an operating system.

Let us start with a host with Docker installed on it.This host has a set of its own processes running such as a number of operating system processes,The docker daemon itself, the ssh server etc.

docker run ubuntu sleep 3600, We will now run an Ubuntu Docker container that runs a process that sleeps for an hour.

We have learned that unlike virtual machines containers are not completely isolated from their host.Containers and the host shared the same kernel.Containers are isolated using Namespaces in Linux. The host has a Namespace and the containers have their own Namespace.

Below Container with processes like process of db,analysis, computation etc.
Containers are meant to run a specific task or process such as to host an instance of a web server or application server or a database or simply to carry out some kind of computation or analysis.

Once the task is complete the container exits. The container only lives as long as the process inside it is alive.If the web service is inside the container is stopped or crashes, the container exits.

Microservices Logging Mechanism:
1st Style : Consolidated Logging Style.
2nd Style: Log Streaming

1st Style : Consolidated Logging Style:
Containers such as Docker are ephemeral (lasting for only a short time).This essentially means
that one cannot rely on the persistent state of the disk.Logs written to the disk are lost once the container is stopped and restarted.Therefore,we cannot rely on the local machine's disk to write
log files.

I will keep on update this topic when I will have time.

Sunday, 5 April 2020

Important Basic Concepts

1) what is encapsulation ?
Encapsulation JAVA's PIE (polymorphosim, Inheritance, Encapsulation) concept, to protect the data.

What is protection of data in encapsulation?
 Class person {
       int salary;
       // getters
       public void setSalary(int salary) {
             if(salary < 0) {
                  //throw exception
             }
       }
}
person p = new person();
p.setSalary(10000);

But you are creating the person p object, through p object you are setting the value of salary, But how are you protecting data here ?

While entering the salary data, in the setSalary method we had put some constraints of not allowing the < 0 values, we are protecting the salary allows only integer values > 0.

2) Inside enum class why can't declare abstract methods ?
enum Biryani {
    abstract void recipes() ;
}
1) if you declare any abstract method, then you will make class also abstract. these abstract method implemented by child class

*** Any child class can't extend enum class, because enum class is final.
       enum class final, final and abstract combination will not work.

*** Inside enum only instance and static methods not abstract methods.

3) Difference between enum, Enum, Enumeration ?
enum: enum type just like class type. defined group of named constants.
class ramesh {
},

enum ramesh {
}

Enum: It's a class present in java.lang package which act as a base class for all java enums

Enumeration: It's an interface in java.lang, which can be used for retrieving objects
from collection one by one

















Thursday, 2 April 2020

QuickSort Technique

My Quicksort technique will help students.
QuickSort:
   Divide and Conquer type. Sorting set is divided into sorting 2 smaller sets.
    Find final positon for each pivotal and give 2 sublists ( sublist1 < pivotal < sublist2) like this way.

Reduction step of the this algorithm finds the final position of the numbers
means
we are starting with 44 using quicksort technique we will find the final position of 44th in the list

This is simple, we will right to left scan and left to right scan

pivotal number: 44, we are finding final position for this number lets see ?
Current position of 44: 0, after quicksort we will find the correct position for this 44.
Final Position of 44: ?

Ex: Suppose A is the list of 12 numbers.
   44 33 11 55 77 90 40 60 99 22 88 66

-> right to left scan: ( search from right to check until number < 44), Start:66, Pivotal:44
First Number 44, last number 66, scan the list from right to left.
comparing each number with 44 and stopping at the number < 44
That is 22. Interchange 44 and 22 to obtain the list

 22 33 11 55 77 90 40 60 99 44 88 66

-> left to right scan: ( search from left to check until number > 44) , Start:22, Pivotal:44
Begin with 22, next scan the list opposite direction from left to right.
comparing each element with 44 and stopping at the first number> 44.
The number is 55. Swap 44 and 55 to obtain the List.

22 33 11 44 77 90 40 60 99 55 88 66

-> Right to Left: Start:55, Pivotal:44
Beginning with 55, Now scan from right to left until number < 44.
That is 40, interchange them 40 and 44.

22 33 11 40 77 90 44 60 99 55 88 66

-> Left to right: Start:40, Pivotal:44
Begin with 40, scan from left to right Until > 44, that 77.
Interchange 44 and 77.
22 33 11 40 44 90 77 60 99 55 88 66

-> Right to Left: Start:77, Pivotal:44
Start with 77, scan right to left until < 44, we don't meet such number.
so 44 is reached to its real position. Now all elements present before 44 are < 44 and after > 44.
so the list is divided into sub list having 44 in it's correct position.

22 33 11 40 44 90 77 60 99 55 88 66

first sublist: 22 33 11 40
second sublist: 90 77 60 99 55 88 66

Before Sort Pivotal 44 Position: 0
After Sort Final Position of Pivotal 44: 4

Like this way we will recursively check other numbers also.

My Analysis:
In Bubble Sort Every Pass (Every Outer loop)  , we will filter highest element put it in the last.
In Selection Sort Every Pass  (Every Outer loop), we will filter smallest element put in the first.
But in QuickSort For every pivotal pass, we will find and allocate exact location of that pivotal element and leftside < pivotal < rightside


public class Quicksort {

public static void main(String args[]) {
int[] ram = { 20, 30, 10, 9 };
sort(ram, 0, ram.length - 1);
for(int i=0; i < ram.length; i++) {
System.out.print(ram[i]);
System.out.print("  ");
}
}

public static void sort(int[] a, int beg, int end) {
if (beg >= end) {
return;
}
int loc = quick(a, beg, end);
sort(a, beg, loc - 1);
sort(a, loc + 1, end);
}

public static int quick(int[] a, int beg, int end) {

int left = beg;
int right = end;
int loc = beg;

while (left <= right) {

// scan from right to left
while (a[loc] <= a[right] && loc != right) {
right = right - 1;
}

if (loc == right) {
System.out.println("right location-->" + loc);
return loc;
}
if (a[loc] > a[right]) {
int temp = a[loc];
a[loc] = a[right];
a[right] = temp;
loc = right;
}

// scan from left to right
while (a[left] <= a[loc] && left != loc) {
left = left + 1;
}
if (loc == left) {
System.out.println("left location-->" + loc);
return loc;
}
if (a[left] > a[loc]) {
int temp = a[loc];
a[loc] = a[left];
a[left] = temp;
loc = left;
}
                }
return loc;
       }
}































































   

Wednesday, 1 April 2020

Tricky Programs

I am publishing my coding thing into git
https://github.com/rameshvanka/coding/tree/master/optumtest


I am publishing tricky java program questions for students. It will ongoing process.

Find the Duplicate Elements In a String
public class Unique {
public static void main(String args[]){
String ram = "ramesh";
boolean[] char_val = new boolean[256];
for(int i=0; i < ram.length();i++){
int val = ram.charAt(i);
if(char_val[val]){
System.out.println("Duplication Element:"+ram.charAt(i));
}
char_val[val] = true;
}
}

}

Here Tricky thing having the boolean array of 256 ( 8 - bits, 2 power 8 = 256) and make them true concerned array cell.

Palindromic Substrings:
i/p: mokkori,
palindrome substrings: m, o, k, i, r, kk, okko  

Main logic:  find the list of substrings and check each substring palindrome or not.
i=0, str[i] = m  --> m, mo, mok, mokk, mokko, mokkor, mokkori
i=1, str[i] = o   --> o, ok, okk, okko, okkor, okkori
i=2, str[i] = k   --> k, kk, kko, kkor, kkori
i=3, str[i] = k   --> k, ko, kor, kori
i=4, str[i] = o   --> o, or, ori
i=5, str[i] = r   -->  r, ri
i=6, str[i] = i   -->  i

Java Logic:
      split substring logic:  for (int i =0 ; i < str.length(); i++) {
                                           String temp = "";
                                           for(int j=i, j < str.length(); j++ ) {
                                                   temp += str.charAt(j);
                                                    //Check Palindrome of temp and get status.
public class PalindromSubString {
static Set<String> palSet = new HashSet<String>();
public static int countPalindrome(String str) {
for(int i=0; i < str.length(); i++) {
String temp = "";
for (int j=i; j < str.length(); j++) {
temp += str.charAt(j);
boolean status = checkBoolean(temp);
if(status) {
palSet.add(temp);
}
System.out.println(temp);
}
}
for(String s : palSet) {
System.out.print(s);
System.out.print(" ");
}
return palSet.size();

}

public static boolean checkBoolean(String str) {
char[] charStr = str.toCharArray();
int i = 0;
int j = str.length()-1;
System.out.println("String temp:"+str);
while(i < j) {
if(charStr[i] != charStr[j]) {
return false;
}
i++;
j--;
}
return true;

}
}
  
Valid BST Tree: Given Binary Tree is valid BST (Binary Search Tree) Tree or Not ?
In the BST Tree all elements are in sorted order. 
Main Logic: BST  Tree Inorder Traversal will go through sorted order means ( left, node, right). I am using inorder traversal checking leftnode value < node value < rightnode value, if condition fails it's not valid BST. I am using recursion inorder traversal, recursion means nothing but stack, in stack all things are local scope only. hence I am storing previous value in the instance variable.

//My simple technique, Inorder traversal gives sorted tree, then checking previous < root < right
int prevItemValue = 0;
public  boolean validBST(TreeNode root) {
if(root == null) {
return true;
}
return validBST(root.left) && checkMin(root) && validBST(root.right);
}

public  boolean checkMin(TreeNode root) {
System.out.println("prevItemValue :" + prevItemValue  + " CurrItemValue:" + root.item);
if(prevItemValue <= root.item) {
prevItemValue = root.item;
//System.out.println(root.item + "item:" + min);
} else {
return false;
}
return true;

}
return validBST(root.left) && checkMin(root) && validBST(root.right); Why I am returning like this means return true&&true&&true&&true&&true&&false&&true; here if any false will give false due to && condition.














Sorting Technics

I will update all the sorting technices which help for students.

All examples I am refer: 2 3 4 5 1

1) Try to understand swap the number: 5 1
int[] arr = { 5, 1 }; int temp = 0, j = 1; if(!(arr[j-1] < arr[j])){ // Needs 5 < 1 no then temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; }

Hope all people know this one.

Insertion Sort:

please refer: https://www.java2novice.com/java-sorting-algorithms/insertion-sort/

My Style: In the insertion sort every pass we are checking sorting from last to first in the inner loop

Ex:  2 3 4 5 1
i=0,  inner loop: for(int j = i ; j > 0 ; j--), here from last to first means j = 2 it will
loop until j > 0
in i = 0; j =0 condition fail here j > 0

i=1,j=1
2 3 4 5 1 3 < 2 if condition fail skip the swap

i=2,j=2
4 < 3 if condition fail skip the swap
3 < 2 if condition fail skip the swap
i=3,j=3,
5 < 4 if condition fail skip the swap
4 < 3 if condition fail skip the swap
3 < 2 if condition fail skip the swap
i=4,j=4
2 3 4 5 1 1 < 5 yes swap them
2 3 4 1 5 1 < 4 yes swap them
2 3 1 4 5 1 < 3 yes swap them
2 1 3 4 5 1 < 2 yes swap them
1 2 3 4 5

algorithm:
for (int i = 0; i < arr.length; i++) { for(int j = i ; j > 0 ; j--){ if(!(arr[j-1] < arr[j])){ temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } }

In the insertion sort we start from last to first style, remember this
for(int j = i ; j > 0 ; j--).


Time Complexity : Average case O(n2), Wrost Case O(n2)