Saturday, September 14, 2013
Some crimes deserve a thoughtful punishment
Monday, July 8, 2013
Upcoming Lok Sabha Elections 2014 (hopefully) and India's Principal Opposition Party
I wish Mr. NaMo could continue his earlier agenda about growth and believe in it. In my opinion, it would be a win in itself to loose on that agenda rather than winning it the other way round. It is high time the people of our country get the kind of governance they need, the kind of healthcare they require and the kind of education deserve!
I wish the GliMPse I saw some time back in Bihar where a bandh was called (I don't support it in any form) on economic affairs and not the one like it was called today to protest against the blasts which happened in bodhgaya.
I Wish if the upcoming elections henceforth are contested on growth and governance 'n' not of religion and rhetorism.
#Jai Hind
P.S.: View expressed here are personal.
Sunday, January 27, 2013
A mandatory wave of change in Indian IT Industry
Tuesday, May 29, 2012
Sunday, November 27, 2011
FDI in retail at this juncture -- complementary measures
This is, indeed, valuable.
And the journey called life continues…
Just when one feel that it can’t get better than this, at that very point god reminds us that he’s the supreme power with stamped authority and one needs to accept it rather than pondering over it.
Today I feel that I too learnt the similar lesson but then as one grows old [‘n’ hopefully wise :P too], I have the courage to accept it with a smile beneath which lies a big heart to reinforce
it.
Assimilate it, feel it ‘n’ move on is the name of the game in contemporary times.
And yeah its kindaa difficult but then when one’s mind decides to do something, half of the battle is already won & as I learnt from my father, its never too late to make a start and put in your best effort and I am up for it man.
Well if the above stuff is too much of an abstraction to you, I would say that I have deliberately kept it that way [without the background context] to keep certain feelings in check. If you didn’t understand every bit of it, let me affirm that the onus lied on me & not always “human beings” live up to expectations.
Keep exploring your potential.
Saturday, June 18, 2011
Expecting the unexpected
Without my usual harness,
Using only my hands and feet,
I climbed up and into darkness.
Scrabbling for a crack,
Or a foothold to stop and rest,
I dug my nails into the rock,
Heart hammering in my chest.
It was as if the rock gave way,
Dismayed I found twas true,
For as my feet began falling,
The rest of my body did too.
Grabbing for the safety line,
I knew instinctively wasn't there,
I plummeted at a sickening rate,
Through the rushing air.
My head hit the ground,
With a resounding crack,
I found that I was lying dazed,
............................................. "
Cheers to the uncertainity of life !!!
Tuesday, May 31, 2011
Taking Right Decisions @ The Right Time… My Experiences
Most of the times life moves at a brisk pace ‘n’ at the blink of the eye, each moment passes by. So it’s imperative for us to take some time out and look at the events in our lives that changed the course or have the potential of changing the course of our lives.
Since I am no exception of this phenomenon [yeps this is a deliberate choice of word], I too have taken decisions and have missed out on some or the others ‘n’ hence the aim of this write-up is to sum up those decisions and to keep a track that at which point the circle-of-life approximately is. [Again ‘approximately’ is a deliberate choice of word since if one knows the exact precision of the circle-of-life, the flavor of uncertainty from lives goes missingJ]
Always remember that life is full of choices but the important thing is to make the right choice at the right time.
Broadly I feel that we can classify decisions into two categories viz. conscious and un-conscious decisions
Decision not taken by myself...
When I look back at the last 10 years of my life, I reminisce the following checkpoints viz. trying for the SSB Interview at AFSB Dehradoon, joining engineering course, joining Satyam. The common pattern in all of these unconscious one’s were passion, lack of ground work / knowledge, lack of appropriate amount of openness to discuss things and to an extent lack of alternative choices.
An unsolicited suggestion to those “alike me” is that one need to be open to discuss things with peers, seniors ‘n’ even juniors and if you get this thing right, other will follow for sure.
Decision taken by myself...
The common pattern [in java, we term it as ‘design pattern’ and a manager would want to term it as correlationJ] is that there were some sort of planning ‘n’ informed decisions which were missing earlier all the way.
This also made me realize that careful planning coupled with passion, hard work and quest for learning not only makes one realize their potential professionally life but enriches personal life as well.
Another good thing that I realized is the power of reading. I felt some kindaa change in myself while reading good quality stuff which contributed to understanding of one’s own strength ‘n’ keeps you focused ‘n’ motivated and working northwards towards the goal.
I think the time doesn’t permit me to write further so I will wrap-it-up by mentioning a few lines….
In masks outrageous and austere, The years go by in single file;
But none has merited my fear, And none has quite escaped my smile.
Cheers to life !!!
Tuesday, March 22, 2011
Emotions
1) Primary emotions
2) Secondary emotions
Cheers !!!
Tuesday, March 15, 2011
Why to override HashCode and equals methods in java usually together?
public boolean equals(Object obj)
public int hashCode()
public boolean equals(Object obj)
This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in
Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison". However, the classes providing their own implementations of the equals method are supposed to perform a "deep comparison"; by actually comparing the relevant data members. Since Object class has no data members that define its state, it simply performs shallow comparison.The equals method implements an equivalence relation:
- It is reflexive: for any reference value x, x.equals(x) should return true.
- It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
- For any non-null reference value x, x.equals(null) should return false.
The meaning of each of the above statement is elaborated below:-
- Reflexive - It simply means that the object must be equal to itself, which it would be at any given instance; unless you intentionally override the
equalsmethod to behave otherwise. - Symmetric - It means that if object of one class is equal to another class object, the other class object must be equal to this class object. In other words, one object can not unilaterally decide whether it is equal to another object; two objects, and consequently the classes to which they belong, must bilaterally decide if they are equal or not. They BOTH must agree.
Hence, it is improper and incorrect to have your own class withequalsmethod that has comparison with an object ofjava.lang.Stringclass, or with any other built-in Java class for that matter. It is very important to understand this requirement properly, because it is quite likely that a naive implementation ofequalsmethod may violate this requirement which would result in undesired consequences. - Transitive - It means that if the first object is equal to the second object and the second object is equal to the third object; then the first object is equal to the third object. In other words, if two objects agree that they are equal, and follow the symmetry principle, one of them can not decide to have a similar contract with another object of different class. All three must agree and follow symmetry principle for various permutations of these three classes.
Consider this example - A, B and C are three classes. A and B both implement theequalsmethod in such a way that it provides comparison for objects of class A and class B. Now, if author of class B decides to modify itsequalsmethod such that it would also provide equality comparison with class C; he would be violating the transitivity principle. Because, no properequalscomparison mechanism would exist for class A and class C objects. - Consistent - It means that if two objects are equal, they must remain equal as long as they are not modified. Likewise, if they are not equal, they must remain non-equal as long as they are not modified. The modification may take place in any one of them or in both of them.
public int hashCode()This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet etc.
This method must be overridden in every class that overrides the
equals method.The general contract of
hashCode is:- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. This is the reason we override hasCode() method if we override equals() method.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
Implementation Example
1. public class Test
2. {
3. private int num;
4. private String data;
5.
6. public boolean equals(Object obj)
7. {
8. if(this == obj)
9. return true;
10. if((obj == null) || (obj.getClass() != this.getClass()))
11. return false;
12. // object must be Test at this point
13. Test test = (Test)obj;
14. return num == test.num &&
15. (data == test.data || (data != null && data.equals(test.data)));
16. }
17.
18. public int hashCode()
19. {
20. int hash = 7;
21. hash = 31 * hash + num;
22. hash = 31 * hash + (null == data ? 0 : data.hashCode());
23. return hash;
24. }
25.
26. // other methods
27. }
num and data. These two variables define state of the object and they also participate in the equals comparison for the objects of this class. Hence, they should also be involved in calculating the hash codes of this class objects.Consider the
equals method first. We can see that at line 8, the passed object reference is compared with this object itself, this approach usually saves time if both the object references are referring to the same object on the heap and if the equals comparison is expensive. Next, the if condition at line 10 first checks if the argument is null, if not, then (due to the short-circuit nature of the OR || operator) it checks if the argument is of type Test by comparing the classes of the argument and this object. This is done by invoking the getClass() method on both the references. If either of these conditions fails, then false is returned. This is done by the following code -if((obj == null) || (obj.getClass() != this.getClass())) return false; // preferThis conditional check should be preferred instead of the conditional check given by -
if(!(obj instanceof Test)) return false; // avoidThis is because, the first condition (code in blue) ensures that it will return
false if the argument is a subclass of the class Test. However, in case of the second condition (code in red) it fails. The instanceof operator condition fails to return false if the argument is a subclass of the class Test. Thus, it might violate the symmetry requirement of the contract. The instanceof check is correct only if the class is final, so that no subclass would exist.Useful guidelines for implementing the
equals method correctly.- Use the equality
==operator to check if the argument is the reference to this object, if yes. return true. This saves time when actual comparison is costly. - Use the following condition to check that the argument is not
nulland it is of the correct type, if not then returnfalse.if((obj == null) || (obj.getClass() != this.getClass())) return false;
Note that, correct type does not mean the same type or class as shown in the example above. It could be any class or interface that one or more classes agree to implement for providing the comparison. - Cast the method argument to the correct type. Again, the correct type may not be the same class. Also, since this step is done after the above type-check condition, it will not result in a
ClassCastException. - Compare significant variables of both, the argument object and this object and check if they are equal. If *all* of them are equal then return true, otherwise return false. Again, as mentioned earlier, while comparing these class members/variables; primitive variables can be compared directly with an equality operator (
==) after performing any necessary conversions (Such as float toFloat.floatToIntBitsor double toDouble.doubleToLongBits). Whereas, object references can be compared by invoking theirequalsmethod recursively. You also need to ensure that invokingequalsmethod on these object references does not result in aNullPointerException, as shown in the example above (Line 15).
It is neither necessary, nor advisable to include those class members in this comparison which can be calculated from other variables, hence the word "significant variables". This certainly improves the performance of theequalsmethod. Only you can decide which class members are significant and which are not. - Do not change the type of the argument of the
equalsmethod. It takes ajava.lang.Objectas an argument, do not use your own class instead. If you do that, you will not be overriding theequalsmethod, but you will be overloading it instead; which would cause problems. It is a very common mistake, and since it does not result in a compile time error, it becomes quite difficult to figure out why the code is not working properly. - Review your
equalsmethod to verify that it fulfills all the requirements stated by the general contract of theequalsmethod. - Lastly, do not forget to override the
hashCodemethod whenever you override theequalsmethod, that's unpardonable. ;)
Wednesday, February 23, 2011
Re-defining mistake !!!
Ok,yes,it's a mistake.I know it's a mistake.
But their r certain things in life where u knw it's a mistake but u don't really knw it's a mistake bcos the only way to really knw its a mistake is to make the mistake, and look back, and say, "Yep. That was a mistake."
going by this premise
Really,the bigger mistake would be to not make the mistake, bcos then u go ur whole life not really knwng if something is a mistake or not.
And Damm the whole thing... I never made a mistake -:)
Cheers !!!
Thursday, February 17, 2011
Difference between Padma Vibhushan, Padma Bhushan and Padma Shri
Padma Vibhushan
The Padma Vibhushan is India's second highest civilian honour. It consists of a medal and a citation and is awarded by the President of India.
It is awarded to recognize exceptional and distinguished service to the nation in any field, including government service. The award was suspended between 1977 and 1980. No award was made between 1992 and 1998 as well.
The award was established by Presidential decree on 2 January 1954. It comes after the Bharat Ratna and before the Padma Bhushan. Padma Vibhushan was originally established as the Pahela Varg (First Class) of a three-class "Padma Vibhushan" awards. However the structure was changed in 1955 and there is no record of the award being presented to any of the recipients in the original structure.
Padma Bhushan
The Padma Bhushan award is an Indian civilian decoration established on January 2, 1954 by the President of India. It stands third in the hierarchy of civilian awards, after the Bharat Ratna and the Padma Vibhushan, but comes before the Padma Sri. It is awarded to recognize distinguished service of a high order to the nation, in any field.
Padma Shri
Padma Shri (also spelt Padma Shree, Padmashree, Padma Sree and Padma Sri) is an award given by the Government of India generally to Indian citizens to recognize their distinguished contribution in various spheres of activity including the Arts, Education, Industry, Literature, Science, Sports, Social Service and public life. (The word "Padma" (Sanskrit) means "Lotus".)
It stands fourth in the hierarchy of civilian awards after the Bharat Ratna, the Padma Vibhushan and the Padma Bhushan. On its obverse, the words "Padma" and "Shri", in Devanagari, appear above and below the lotus flower. The geometrical pattern on either side is in burnished bronze. All embossing is in white gold.
I felt enlighted to learn more about my country's hightest civilian honors. Hope you enjoyed it too !!!
Cheers !!!
Thursday, February 10, 2011
Why it is not advisable to declare a constructor in servlet?
Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Also, Java constructors cannot be declared in interfaces and javax.servlet.Servlet is an interface. Now the classes which implement this interface are GenericServlet and HttpServlet which don't do anything in these constructors [as per the API documentation].
So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.
This is what I think, please go ahead and pen down on what you think about this and if you differ from my opinion, I assure you that you won't be the first one.
Cheers !!!
Vinay
What happens if you call destroy() from init() in a servlet ?
destroy() gets executed and the initialization process continues.
Explanation:-In java servlet, destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy() method is not supposed to and will not destroy a java servlet. Don’t get confused by the name. It should have been better, if it was named onDestroy().
The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy() gets executed and then the servlet initialization gets completed.
If you still aren't clear, then please re-visit servlet life cycle once.
Cheers !!!
Vinay
ALL-IN-ONE (Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency)
These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.
Association
1) Association is a relationship between two objects. In other words, association defines the multiplicity between objects.
2) Different types of association between objects are:- one-to-one, one-to-many, many-to-one, many-to-many.
3) Example: A Student and a Faculty are having an association.
Aggregation
1) It is a specific case of association.
2) Aggregation is also called a “Has-a” relationship i.e. When an object ‘has-a’ another object, then you have got an aggregation between them.
Composition
1) Composition is a special case of aggregation.
2) When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Difference between aggregation and composition
1) When there is a composition between two objects, the composed object cannot exist without the other object. Composition is more restrictive. This restriction is not there in aggregation.
2) In aggregation, though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional.
3) In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
4) Example: - Let analyze Library, Student and Books.
Relationship between library and student is aggregation because a student can exist without a library and therefore it is aggregation.
Relationship between library and book is composition because A book cannot exist without a library and therefore its a composition.
In terms of coding snippet example of difference between aggregation and composition
Aggregation Example: the object exists outside the other, is created outside, so it is passed as an argument (for example) to the constructor. Ex: People – car. The car is created in a different context and then becomes a person’s property.
****************************************************************************
// WebServer is aggregated of a HttpListener and a RequestProcessor
public class WebServer
{
private HttpListener listener;
private RequestProcessor processor;
public WebServer(HttpListener listener, RequestProcessor processor)
{
this.listener = listener;
this.processor = processor;
}
}
****************************************************************************
Composition Example: the object only exists, or only makes sense inside the other, as a part of the other. Ex: People – heart. You don’t create a heart and then passes it to a person.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
// WebServer is an composition of HttpListener and RequestProcessor & controls their lifecycle
public class WebServer
{
private HttpListener listener;
private RequestProcessor processor;
public WebServer()
{
this.listener = new HttpListener(80);
this.processor = new RequestProcessor(“/www/root”);
}
}
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Here the key difference [wrt code snippet above] to note is that :-
In Aggregation we are passing the already instantiated objects [ HttpListener and RequestProcessor ] from outside the Webserver class so they exist independently of the Webserver class though Webserver class shares “has-a” relationship with them.
In Composition we are instantiating the classes [ HttpListener and RequestProcessor with in the Webserver class so they are dependent on Webserver class. Here also Webserver class shares “has-a” relationship with them.
Abstraction
1) Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction.
2) It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
3) Example: A wire frame model of a car.
Generalization
1) Generalization uses a “is-a” relationship from a specialization to the generalization class.
2) Example: (a) Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization. (b) Lets have specialization class [Triangle and Circle] and generalization class [shape] so the relationship b/w specialization to generalization class is that every Square “is-a” Shape.
Realization
1) Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class.
2) In other words, you can understand this as the relationship between the interface and the implementing class.
Dependency
Change in structure or behavior of a class affects the other related class, then there is a dependency between those two classes.
Please feel free to disagree (if you find anything wroing) on the above explanations and believe me you won't be the first one. Do spare me for any typo's above (if any). Happy-to-learn !!!
Cheers,
Vinay
Thursday, September 16, 2010
Factory design pattern [with sample implementation in java]
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.
- 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.
- 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
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.
Why to use prototype design pattern?
- 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?
- When there are many subclasses that differ only in the kind of objects.
- 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
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
((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 !!!
- 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.
(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
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 !!!
