The most successful people in any walks of lives may not be the most talented ones but are definately the most passionate & dedicated ones.

Thursday, September 16, 2010

Factory design pattern [with sample implementation in java]

Definition -- Factory design pattern
Provides an abstraction (usually via an interface) and lets subclass / implementing classes decide which class / method should be instantiated / called, based on the conditions or parameters given.

Intent :-
Factory Method lets a class defer instantiation to subclasses.
To delegate responsibility among different objects and this kind of partitioning is good since it encourages Encapsulation and Delegation.

Discussion :-
Lets leave aside java concepts for a moment and think what a factory in general does? Yes, ask this question to yourself that what any typical factory [say a Toy factory which makes different kind of toys some in shape of aeroplane, some in shape of a racing car] functions?

Now what a factory owner will do to maximize his profit and allow new toys to be build seamlessly is exactly the same what we are going to do in our java classes.

What the toy factory owner will do is that in one chamber of the factory, he will have molten plaster-of-paris (or other material) and then bring it to another chamber where he has kept different toy structures like in the shape of aeroplane / jeep etc and then pour the molten plaster-of-paris into those structures and when it solidifies, he gets the toy of that shape. So the molten plaster-of-paris doesn't know until at the end moment that which structure it would be poured in and what toy would come out but then for sure it would be a toy.

Now lets see how we utilize this concept in java. The molten plaster-of-paris is equivalent to a interface i.e. a standard agreement that it can be converted into any toy provided its poured into a shape/structure.
The structures of aeroplane/jeep are the concrete subclasses which implement the contract with the molten P-o-P. Now what toy would turn out is not known until its poured is similar to getting the objects at runtime.

This we can say that...
Factory Method is to creating objects <==is similar to==> Template to implementing an algorithm/rule [molten P-o-P into structures].
In technical terms, A superclass specifies all standard and generic behavior and then delegates the creation details to subclasses that are supplied by the client.

Why to use Factory design pattern?
We would use a pattern only if its benefits us/our solution in some way or the other. So benefits of Factory pattern are:-
  • A family of objects is separated by using shared interface.
  • Hide concrete classes from the client.
  • The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
  • The "new" operator is considered harmful. There is a difference between requesting an object and creating one. The "new" operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.
Where to use a Factory pattern?
  • A class cannot anticipate its subclasses, which must be created.
  • A sample scenario:- One typical use of the Factory Pattern in an Enterprise JavaBean (EJB) Application: An entity bean is an object representation of persistent data that are maintained in a permanent data store, such as a database. A primary key identifies each instance of an entity bean. Entity beans can be created by creating an object using an object factory Create method. Similarly, Session beans can be created by creating an object using an object factory Create method.
Sample implementation of Factory pattern [in java programming language] :-
  • Here, I have used 6 [classes and interfaces] to provide a sample implementation.
  • The purpose of each class and interface is explained at the beginning of the source code along with other important points.
  • Here you can begin looking at FactoryPatternDemo.java class which has the main() method as a starting point.

(1) ************ start of Constants.java ************
/**
* Purpose:- Class to accomodate constants at one place.
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class Constants {

public static final String CONSOLE_LOG = "consoleWriter";
public static final String FILE_LOG = "fileWriter";

public static final String logFileName = "TestLogFile.log";
public static final String logFileLocation = "/home/vm234069/Desktop/";
}
************ end of Constants.java ************


(2) ************ start of ConsoleLogWriter.java ************
/**
* Purpose:- The usage of this class is to implement the console logging functionality
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class ConsoleLogWriter implements ILogWriter {

private boolean isDebugModeOn = false;

public void setDebugMode(boolean value) {
this.isDebugModeOn = value;
}

public void printErrorStatement(String errMsg) {
if (isDebugModeOn)
System.out.println("Printing error message on console.");
}

public void printDebugStatement(String debugMsg) {
if (isDebugModeOn)
System.out.println("Printing debug message on console.");
}

}
************ end of ConsoleLogWriter.java ************

(3) ************ start of FactoryPatternDemo.java ************
/**
* Purpose:- To demonstrate factory pattern.
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class FactoryPatternDemo {

public static void main(String[] args) {

//First lets write to a console.
ConsoleLogWriter clg = (ConsoleLogWriter) LogFactory.getLogWriter(Constants.CONSOLE_LOG);
clg.setDebugMode(true);
clg.printDebugStatement("debug message");
clg.printErrorStatement("error message");

//now lets write to a log file.
FileLogWriter flw = (FileLogWriter) LogFactory.getLogWriter(Constants.FILE_LOG);
flw.setDebugMode(true);
flw.openLogFile();
flw.printDebugStatement("debug message");
flw.printErrorStatement("error message");
flw.closeLogFile();

}

}
************ end of FactoryPatternDemo.java ************


(4) ************ start of FileLogWriter.java************
/**
* Purpose:- The usage of this class is to implement the console logging functionality
*/
package factoryPattern;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
* @author Vinay K Mudgil
*
*/
public class FileLogWriter extends Constants implements ILogWriter{

private boolean isDebugModeOn = false;
private BufferedWriter bw = null;


public void openLogFile() {
try {
bw = new BufferedWriter(new FileWriter(logFileLocation+logFileName));
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}


public void setDebugMode(boolean value) {
this.isDebugModeOn = value;
}


public void printErrorStatement(String errMsg) {
try {
if(bw != null) {
bw.write(errMsg+" -- Printing error message in log file.\n");
bw.flush();
}
} catch (IOException ioe) {
System.out.println("IOException via writing error Message");
} catch (Exception e) {
System.out.println("Exception via writing error Message");
}
}

public void printDebugStatement(String debugMsg) {
try {
if(bw != null) {
bw.write(debugMsg +" -- Printing debug message in log file.\n");
bw.flush();
}
} catch (IOException ioe) {
System.out.println("IOException via writing debug Message");
} catch (Exception e) {
System.out.println("Exception via writing debug Message");
}

}

public void closeLogFile() {

try {
if(bw != null) {
bw.close();
}
} catch (IOException ioe) {
System.out.println("IOException while closing the file.");
}
}

}

************ end of FileLogWriter.java ************


(5) ************ start of ILogWriter.java ************
/**
* Purpose:- The purpose of this interface is to provide an agreement of some basic functionalities which any generic
* LogWriter should provide
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public interface ILogWriter {

//turn on/off the debug mode
public void setDebugMode(boolean value);

//write an error statement
public void printErrorStatement(String errMsg);

//write an debug statement
public void printDebugStatement(String debugMsg);

} //enf of Interface definition
************ end of ILogWriter.java ************


(6) ************ start of LogFactory.java ************
/**
* Purpose:- This is the factory class which actually creates the concrete class type depending on which is required by the client.
*/
package factoryPattern;

/**
* @author Vinay K Mudgil
*
*/
public class LogFactory extends Constants {

// method returning appropriate class object
public static ILogWriter getLogWriter(String writerType) {
if (writerType.equals(Constants.CONSOLE_LOG)) {
return new ConsoleLogWriter();
} else if (writerType.equals(Constants.FILE_LOG)) {
return new FileLogWriter();
}

System.out.println("illegal logging selection...");
return null;
}
}

************ end of LogFactory.java ************

Please feel free to comment on concepts 'n' sample code snippet provided above & spare me for any typo's. Happy to learn !!!

Thanks !!!

Tuesday, September 14, 2010

kiss - Prototype design pattern

Before I start let me make kiss very clear. Its an acronym for "keep it short & simple". I found this pattern fairly interesting and in fact got into the realm of "cloning" in java due to this, so thought to share my learning and experiences on this design pattern.

What is a prototype design pattern?
In this point we should be exploring the intent of the prototype design pattern, which is :-
  • It specifies the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • This pattern co-opt one instance of a class for use as a breeder of all future instances.
  • This pattern sees the java "new" operator as cumbersome.
Okayy, the jist is, we create an object of a class once & then clone the object another instance is required.


Why to use prototype design pattern?
We would use a pattern only if its benefits us/our solution in some way or the other. So benifits of prototype pattern are:-
  • Whenever object initialization is expensive [of-course to the compiler in terms of time 'n' resources] and you anticipate few variations on the initialization parameters, there this pattern could be used.
  • It allows a developer to add / remove attributes at runtime.
  • It allows a developer to specify new objects in terms of varying values.

Where to use a prototype pattern?
  1. When there are many subclasses that differ only in the kind of objects.
  2. A sample scenario:- "There are two class instance(say) that need to be populated with some values, retrieved from the database.The first instance contains values sorted on some key value,while the other is sorted base on some other key(but containing the same data). Now there can be two mechanism for fulfilling the above requirement:- a) Sort the values from the database and then populate in the class,hence the database retrieval is performed 2 times(or n times for n instances). Or b) get the values from the database(one time), populate a single instance, override the clone() method,and then perform cloning."

Sample implementation of prototype pattern [in java programming language] :-
  • Here I have used 8 [classes and interfaces] to provide a sample implementation.
  • The purpose of each class and interface is explained at the beginning of the source code along with other important points.
  • Here you can be starting at PrototypeDemo.java class which has the main() method as a starting point.

(1) ************ start of Constants.java ************
/**
* Purpose:- To place constants used through-ouot the example for Prototype pattern at one place.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class Constants {

public static final String SQUARE = "Square";
public static final String TRIANGLE = "Triangle";
public static final String RECTANGLE = "Rectangle";

public static final int numOfMasterObjects = 10;

}
************ end of Constants.java ************


(2) ************ start of Prototype.java ************
/**
* Purpose:- The purpose of this class is to provide an agreement (thereby abstraction also) so that the class which implement this
* interface have to override the declared methods.
*
* Notes:- (1) By default (implictly) interface members are public, static and final i.e. they are constants and coan't be modified.
* (2) They support the concept of multiple inheritence.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*/

public interface Prototype {

//The purpose is to get the name which is to be cloned.
public String getName();

//The purpose is that class implementing this interface should override the clone method.
public Object clone() throws CloneNotSupportedException;
}

************ end of Prototype.java ************


(3) ************ start of PrototypeDemo.java ************
/**
* Purpose:- Class which is used to show the "prototype" pattern in java works :)
* i.e. its a client application which uses a prototype design pattern
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class PrototypeDemo {

//used to load the
public static void loadMasterObjectsAtBegining() {
ProtoTypeMaster.addPrototype(new Triangle());
ProtoTypeMaster.addPrototype(new Square());
ProtoTypeMaster.addPrototype(new Rectangle());
}

public static void main(String[] args) throws CloneNotSupportedException {
System.out.println("starting execution now.....");
Object [] clonedObjectArray = new Object[args.length];
int count=0;

//intialize
PrototypeDemo.loadMasterObjectsAtBegining();

//For each command-line argument, lets see if we can create a clone.
for(int i=0;i if( (ProtoTypeMaster.findAndClone(args[i]) ) != null) {
clonedObjectArray[count] = ProtoTypeMaster.findAndClone(args[i]);
count++;
}

}

//now, just for sample, lets execute draw method to show that we created cloned objects.
for(int i=0; i if (clonedObjectArray[i] != null)
((UtilityFunctions) clonedObjectArray[i] ).draw();
}

} //end of main method

}//end of class
************ end of ************


(4) ************ start of ProtoTypeMaster.java************
/**
* Purpose:- To hold objects of class which are to be cloned.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/

public class ProtoTypeMaster extends Constants{

private static Prototype [] masterObjectHolder = new Prototype [Constants.numOfMasterObjects];

//variable which holds the current count of
private static int currentCount = 0;

/*
* Purpose:- Add relevant object to the masterObjectHolder
*/
public static void addPrototype(Prototype pObj) {

if(currentCount < Constants.numOfMasterObjects)
masterObjectHolder[currentCount++] = pObj;
else
System.out.println("This Addition would exceedes max. number of allowed objects which can be Prototyped and hence rejecting this addition");
} //end of addPrototype() method


/*
* Purpose:- To search for the relevant class to be cloned and then clone that class and return the cloned instance.
*/
public static Object findAndClone (String classNameToBeCloned) throws CloneNotSupportedException {

//first search in the masterObjectHolder that which relevant class is to be cloned
for(int i=0; i < currentCount; i++) {

if ( masterObjectHolder[i].getName().equals(classNameToBeCloned) ) {
//now that our search is successful, lets clone the object and return it.
return masterObjectHolder[i].clone();
}
}

System.out.println("class name which you supplied at \"runtime\" couldn't be found in the masterObjectHolder and hence can't be cloned");
return null;
}


} //end of class
************ end of ProtoTypeMaster.java ************


(5) ************ start of Rectangle.java ************
/**
* Purpose:- To provide a class (for testing) which can be cloned.
*/
package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class Rectangle extends Constants implements Prototype, UtilityFunctions, Cloneable {

public String getName() {
return Constants.RECTANGLE;
}

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

public Object clone() throws CloneNotSupportedException {
return (Rectangle) super.clone();
}

}//end-of-class
************ end of Rectangle.java ************


(6) ************ start of Square.java ************
/**
* Purpose:- To provide a class (for testing) which can be cloned.
*/
package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/
public class Square extends Constants implements Prototype, UtilityFunctions, Cloneable {
public String getName() {
return Constants.SQUARE;
}

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

public Object clone() throws CloneNotSupportedException {
return (Square) super.clone();
}

}//end-of-class
************ end of Square.java ************


(7) ************ start of Triangle.java************
/**
* Purpose:- To provide a class (for testing) which can be cloned.
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/

public class Triangle extends Constants implements Prototype, UtilityFunctions, Cloneable {
public String getName() {
return Constants.TRIANGLE;
}

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

public Object clone() throws CloneNotSupportedException {
return (Triangle) super.clone();
}

}//end-of-class
************ end of Triangle.java ************


(8) ************ start of UtilityFunctions.java ************
/**
* Purpose:- This interface is created to give you an idea that in real world scenerio's this interface is overridden by class
* to provide their own implementation of a methods
*/

package prototypePattern;

/**
* @author Vinay K Mudgil
*
*/

public interface UtilityFunctions {

//sample method which every first concrete sub-class would provide an implementation for.
public void draw();
}
************ end of UtilityFunctions.java ************


Please feel free to comment on concepts &
sample code snippet provided above. Happy to learn from you.

Thanks !!!

Monday, September 13, 2010

At times Idioms leave you perplexed !!!

Here are a few idioms that I learned today...
  • Tongue in Cheek :- Saying something in an amusing / ironical way or tone, not to be taken seriously.
  • Bury in Hatchet :- Settle one's differences, make peace.
  • Out of frying pan and into the fire :- From a bad situation to worse.
  • To make a clean breast of :- to tell the truth about esp. something wrong you have done , to confess your wrong doing.
Here are a few with [M]eanings and [U]sage:-

(1) A pocket of resistance :-
[M] A few people resisting, only a few people on the other side
[U] Their is a pocket of resistance in one district, a few disagree

(2) A poker face :-
[M] A face with no expression, showing no emotion
[U] Most of the times in the field, M S Dhoni shows a poker face

(3) A red letter day :-
[M] A memorable day, a special day
[U] This is going to be a red letter day, I found my lost keys.

(4) A redneck :-
[M] A person who is intolerant of other opinions and cultures, a bigot
[U] Well if you ask a redneck he will say, "Find a job or starve-- and if you don't like it, too bad !!!"

(5) A raw deal :-
[M] An unfair deal/contract
[U] If he's charging too much rent, then believe me that you are getting a raw deal.

(6) A run for your money :-
[M] Tough competition, strong opponent
[U] I would enter this election and give him a run for his money

(7) A rolling stone gathers no moss
[M] A person who is always moving has few possessions
[U] It seems that you have always been a rolling stone

(8) A roll in a hay :-
[M] making love, having sex
[U] I asked her if she wanted to have a roll in a hay, and she said, "Sure. Do you have a condom?"

(9) A riot / A hoot :-
[M] lots of fun, having a good time
[U] You should have gone to Rooney's party. It was a riot.

(10) A scandal is brewing :-
[M] rumors of a scandal, an evil/false story being told
[U] A scandal is brewing in pacific ocean. A shark and a whale are living together without a license.

(11) A score to settle / A bone to pick
[M] An argument to finish
[U] He owes me a month's rent. I have a score to settle with him.

(12) A screw loose / one brick short of a full load :-
[M] a little bit /crazy
[U] At times I think that he has a screw loose, like when he eats paper
[U] I am ok but you might be one brick short of full load. ha ha ha


* the more you know, your hunger for knowledge intensifies !!!

Basics of Indexes in Database Systems

(A) What is an index ?

1. An index is a physical list of values [tuple to be specific in
R-DBMS] that a table contains.
2. It occupies physical space in the database and is as real as the
table and is different from the table [ though a user can't
directly can't reach the index (which could be a table/tree in
itself) ]
3. Hence if you create an index on table1.create_date, for example,
then a file will be created that consists of one row for every
row in table1. Each row contains the create_date and a pointer
back to the row in table1 that the index's row belongs to.
4. Every time you update, delete from, or insert into table1, the
index is also updated, deleted from, or inserted into.

Optimizing our Indexes

1. Creating indexes on char and text fields is not really a good
idea; they work best on fixed length number fields.
2. Every index increases the time in takes to perform INSERTS,
UPDATES and DELETES, so the number of indexes should not be very
much. Try to use maximum 4-5 indexes on one table, not more. If
you have read-only table, then the number of indexes may be
increased.
3. Keep your indexes as narrow as possible. This reduces the size
of the index and reduces the number of reads required to read
the index.
4. If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns
in the key as to enhance selectivity, with the most selective
columns to the leftmost of the key.
5. If your application will be performing the same query over and
over on the same table, consider creating a covering index on
the table.
6. Clustered indexes are more preferable than non-clustered, if you
need to select by a range of values or you need to sort results
set with GROUP BY or ORDER BY.

(B) What is a clustered index ?

1. A clustered index is a type of index that re-orders the way
records in the table are physically stored.
2. A table can have only one clustered index.
3. The leaf nodes of a clustered index (almost all the times)
contains actual data pages.
4. By default a clustered index a created with a primary key.

(C) What is a non-clustered index ?

1. A non-clustered index is a type of index in which the logical
order of the index doesn't matches the physical stored order of
the rows in the disk.
2. A table can have more than one non-clustered index.
3. The leaf nodes of a clustered index doesn't contain actual data
pages
4. By default a non-clustered index a created on a unique key

Wish you a happy learning.

Thanks !!!

Differenc between Primary Key and Unique key

The differences between Primary Key and Unique key are as follows.

1) Primary Key is a combination of Unique and not--null constraints, so it can’t have duplicate values or any NULL whereas Unique key can contain null value.

2) A table can have only one PK whereas it can have any number of UNIQUE Key[s].

3) (a) For Oracle UNIQUE Key can have any number of null (because in oracle one null value can't be compared another null value)
(b) For Sybase, I have tested myself that it would not allow null at all in Unique keys
(c) For SQL Server it can have only one NULL (I couldn't get a chance to test this myself)

4) By default Primary Key will generate Clustered Index whereas Unique Key will Generate Non-Clustered Index.


Wish you a happy learning.

Thanks !!!