Tuesday, 12 May 2015

Java: Class hierarchies over tagged classes

Tagged class is a class where we have multiple data types for multiple cases.
We should choose to discriminate such distinct cases by taking the advantage of abstract classes and inheritance.

Following example illustrates the point:
================================
//Tagged Class
class Figure {
enum Shape { RECTANGLE, CIRCLE };

// Tag field - the shape of this figure
final Shape shape;
// These fields are used only if shape is RECTANGLE
double length;
double width;

// This field is used only if shape is CIRCLE
double radius;

// Constructor for circle
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}

// Constructor for rectangle
Figure(double length, double width) {
shape = Shape.RECTANGLE;
this.length = length;
this.width = width;
}

double area() {
switch(shape) {
case RECTANGLE:
return length * width;
case CIRCLE:
return Math.PI * (radius * radius);
default:
throw new AssertionError();
}
}
}

Demerits of the above approach:
-------------------------------
1) Memory footprint increased as instances are burdened with irrelevant fields belonging to other flavors
2) Fields can’t be made final unless constructors initialize irrelevant fields

Resolution:
-----------
// Class hierarchy replacement for a tagged class
abstract class Figure {
abstract double area();
}

class Circle extends Figure {
final double radius;

Circle(double radius) { this.radius = radius; }

double area() { return Math.PI * (radius * radius); }
}


class Rectangle extends Figure {
final double length;
final double width;

Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

double area() { return length * width; }
}


=> The class hierarchy could be made to reflect the fact that a square is a special kind of rectangle (assuming both are immutable):
class Square extends Rectangle {
Square(double side) {
super(side, side);
}
}

Monday, 11 May 2015

Java: Abstract Classes vs Interfaces

Interfaces & abstract classes:
--------------------------------------

=> Major difference:
* Abstract class are permitted to implement some methods while interfaces are not
* Abstract class have an constructor  and hence hold state,but Interface doesn't have an constructor so it doesn't hold the state .
*One of the major benefits of abstract classes is that you can reuse code without having to retype it
* To implement the type in an abstract class, a class must be a subclass of the abstract class
  while any class that defines all of the required methods is permitted to implement an interface, regardless of where the class resides in the class hierarchy.

=> Because Java permits only single inheritance, this restriction on abstract classes severely constrains their use as type definitions.

Some advantages of interfaces over abstract classes:
-----------------------------------------------------------------
*  Existing classes can be modified to implement a new interface
but not for abstract classes
 = suppose class A & B extend some abstract class D
 - now, if class A and B are modified to extend the same abstract class C, then C should also have to be made to extend a class D which is A & B's common ancestor
 - this is an issue as now we'll have to modify all sub-classes of D to extend C which may be inappropriate

* Interfaces allow the construction of non-hierarchical type frameworks

* A class can implement multiple interfaces but can extend only one class


public interface MyInterface
{
  void Execute();
}

VS

public abstract class MyAbstractClass
{
  public abstract void Execute();
}


Some advantages of abstract classes over interfaces:
--------------------------------------------------------------------

* It's far easier to evolve an abstract class than an interface
(coz when a new method has to be added, we can add it in abstract class and it's all exisiting implementations will provide the new method
but if we add one in interface, all implementation classes will have to implement it)

=> Hence, once an interface is released and widely implemented, it is almost impossible to change
   but java 8 on-wards  interface can be modified and one can add default method.


Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
  • If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
  • If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  • If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  • If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
         

java 8 on-wards  interface can be modified and one can add default method.    

The interfaces in java supports the multiple inheritance , then oblivious  question is what about the  Diamond Problem  ?. How to deal with it ? -- Its programmers job to deal with it.

public class MyClass implements InterfaceA, InterfaceB {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

    @Override
    public void saySomething() {
        System.out.println("Hello World");   //Still need to provide the Implementation  for method 
    }

}

interface InterfaceA {

    public void saySomething();

    default public void sayHi() {
        System.out.println("Hi from InterfaceA");
    }

}

interface InterfaceB {
     default public void sayHi() {
        System.out.println("Hi from InterfaceB");
    }
}

 If we want to specifically invoke one of the sayHi() methods in either InterfaceA or InterfaceB, we can also do as follows:

  @Override
    public void sayHi() {
       InterfaceA.super.sayHi();
    }

Java: In superclass, constructors must not invoke overridable methods

N.B: The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will get invoked before the subclass constructor has run.
If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.

Let's do a case-study:

superclass:
-------------
public class Super {
// Broken - constructor invokes an overridable method
public Super() {
overrideMe();
}
public void overrideMe() {
}
}

subclass:
-----------
public final class Sub extends Super {
private final Date date; // Blank final, set by constructor
Sub() {
date = new Date();
}

// Overriding method invoked by superclass constructor
@Override public void overrideMe() {
System.out.println(date);
}

public static void main(String[] args) {
Sub sub = new Sub();
sub.overrideMe();
}
}


output: 
---------
prints out null the first time, because the overrideMe method is invoked by the Super constructor
before the Sub constructor has a chance to initialize the date field.

Java: Always override equals() and hashCode() in a class

Necessity of overriding equals():
========================

Case Study:
---------------

My class myCaseInsensitiveString implements equals(o) that does equalsIgnoreCase() and works if 'o' is either a myCaseInsensitiveString or a String instance

Now,
myCaseInsensitiveString cis = new myCaseInsensitiveString("Polish");
String s = "polish";

while cis.equals(s) => true as equals() in myCaseInsensitiveString does equalsIgnoreCase()
s.equals(cis)  => false as equals() in String will not do equalsIgnoreCase()
Hence, symmetric porperty is broken


workaround:
---------------
modify equals(o) in myCaseInsensitiveString so that it works if and only if 'o' is a myCaseInsensitiveString instance.


Necessity of overriding hashCode():
===========================
-- Implementing optimal hash function also boost  the performance
   Ref Link  http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml
Case Study:
---------------

Suppose a class PhoneNumber doesn't override the hashCode

Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>();
m.put(new PhoneNumber(707, 867, 5309), "Jenny");

Here, m.get(new PhoneNumber(707, 867, 5309)) may return null
bcause the insertion & retrieval instances of PhoneNumber may return different hash codes, although the instances are equal

Solution : override the hasCode() method in the PhoneNumber Class:

private volatile int hashCode;
@Override public int hashCode() {
          int result = hashCode;
          if (result == 0) {
          result = 17;
          result = 31 * result + areaCode;
          result = 31 * result + prefix;
          result = 31 * result + lineNumber;
          hashCode = result;
}
return result;
}

Java: HAS-A realtionship is better than IS-A relationship

For the duck simulation game Developer Designed following OO Design


HAS relationship comes from inheritance.
IS relationship comes from composition.

So the statement is equivalent to saying "Composition over inheritance".
Let's examine using the following case study:
=================================

Point class:
---------------
public class Point{
private int x;
private int y;

public Point(int x, int y){
this.x = x;
this.y = y;
}

@Override
public boolean equals(Object o){
if(!o instance of Point)
return false;
Point p = (Point)o;
return p.x == x && p.y == y;

}
}


ColorPoint class:
----------------------
public class ColorPoint extends Point {
private final Color color;
public ColorPoint(int x, int y, Color color) {
super(x, y);
this.color = color;
}
}

// Broken - violates symmetry!
@Override public boolean equals(Object o) {
if (!(o instanceof ColorPoint))
return false;
return super.equals(o) && ((ColorPoint) o).color == color;
}


Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(1, 2, Color.RED);

p.equals(cp) => true
cp.equals(p) => false.

Thus symmetry is broken. Lets deal the problem with choosing composition:

ColorPoint class:
----------------------
public class ColorPoint {
    private final Point point;
    private Color color;
    public ColorPoint1(int x, int y, Color color) {
        this.point = new Point(x,y);
        this.color = color;
    }
 
    public Point asPoint(){
    return this.point;
    }
 
    @Override
    public boolean equals(Object o){
        if(!(o instanceof ColorPoint))
            return false;
        ColorPoint1 cp = (ColorPoint1)o;
        return cp.point.equals(o) && cp.color==color;
    }
}


now since ColorPoint doesn't extend Point, it's instance is no longer an instance of Point
hence p.equals(cp) => false
also cp.equals(p)  => false
and thus symmetry is preserved.

The above example proves the power of composition over inheritance.

Oracle SQL : SQL Statement Processing Phase

In SQL Statement processing the four phase are important Parse,Bind,Execute,Fetch.
The reverse arrow indicates the processing flow Fetch-->Rebind-->Execute-->Fetch.
The Fetch phase applies to the quires and DML statement with return clause.

I.  Parse Phase.
=============

 * Checks the syntax
 * Checks the semantics and privileges.

 Hard Parse.

1. Merges view definitions and  sub-quires  and determine the execution plan for the query.
   Hard parse happens in two conditions
       ==> First time SQL statement submitted to execute
      ==> When no execution plan is found in the  shared pool.

Soft Parse .
1. Searches for the execution plan in the shared pool (Memory area where the Execution plans stored )for the SQL statement to execute. Soft parse will reduce the overhead of determining the
execution plan , and hence boost the performance , still it requires to check the syntax and security checking.

II. BIND Phase
===============

This phase intended to share the execution plan in the SQL statement by using the Bind Variable concept , so that soft parse will take place and boost the performance.

    Bind Phase:


  • The Oracle Database checks the statement for references to bind variables.
  •  The Oracle Database assigns or reassigns a value to each variable.





III. Execute Phase :
==============
    
 The execution plan is a series of steps that the server process uses to access and to identify the
required rows of data from the data buffers. Multiple users can share the same execution plan. The
Oracle Database performs physical reads or logical reads/writes for DML statements and also sorts
the data when needed.

Note: Physical reads are disk reads; logical reads are blocks already in memory in the database
buffer cache. Physical reads use more resources and time because they require I/O from disk
    
IV. FETCH Phase :
===============

The Oracle Database retrieves rows for a SELECT statement during the fetch phase. Each fetch
typically retrieves multiple rows, using an array fetch. Array fetches can improve performance by
reduce network round trips. Each Oracle tool offers its own ways of influencing the array size; For
example, in SQL*Plus, you can change the fetch size by using the ARRAYSIZE setting:
SQL> show arraysize
arraysize 15
SQL> set arraysize 50
SQL*Plus processes 15 rows at a time by default. Very high array sizes provide little or no advantage.


Uptake From this post As Developer:

==============================.

1. Use the bind variable in the application instead of constant so that the execution plan can share and hit the soft parse.
2. Use the API that leverage the bind variable e.g.  Prepared Statement in JDBC.
3.Set Appropriate Arraysize so that it will reduce the physical I/O ,network round-trip  .

Sunday, 10 May 2015

SQL: IN Vs EXIST in oracle SQL (Performance)

IN operator:
-----------------
 1. IN operator reads the all the records from the inner table.

EXIST
------------
1. EXIST does not read all the records from the inner table.

IN -  reads all the columns in the rows returned by the inner query
EXIST - just checks for the availability of rows returned by the inner query

Hence, if we don't need the data from the inner table then best choice is the EXIST operator , as it boosts the performance.


Similarly, count(0) is a performance booster over count(*)

SQL: NOT IN , NOT EXISTS and MINUS in Oracle SQL (Performance)

Lets drive directly to example.

Followings are the two tables with data

 Table  X                   Table Y
     a                                 b
--------------             --------------
    1                                  1
    NULL                         2

-----------------------------------------------------------------------

  1)  NOT IN
==========================================
Select  b from Y where b is NOT IN  (Select a from X);

Output
-----------------
0 rows

Why 0 Rows?  Any guess?

The target table X consists of the NULL records causing the the NOT IN implementation of SQL return false , hence NO rows selected.

What should  we do to get the correct result ?
The answer is use NOT EXIST.

2) NOT EXIST
==================================================
Select b from Y y where NOT EXISTS (Select 1 from X x where x.a=y.b );
output
---------------
2

The NOT EXISTS returns the intended  output.

3) MINUS (EXCEPT- sql server)
=====================================
select b from Y
 MINUS
select a from X

output
-----------------
2

Whats the difference between the EXCEPT and NOT-EXISTS  ?
 1. EXCEPT operator returns all distinct rows from left hand side table which does not exist in right hand side table.
 2.  EXCEPT adds the sorts and the records and removes the duplicates, however NOT EXIST does not removes duplicates.
3. The recommendation is to use the NOT EXIST as it doesn't add the performance overhead of buffer sort.