Wednesday, August 6, 2014

Effective Java, Chapter-2 Creating and Destroying Objects: Summary

Item 1 (Consider Static factory methods instead of constructors)

  • Static factory methods have names unlike constructors.
  • Unlike constructors they are not required to create a new object every time they are invoked.
  • Unlike constructors they can return an object of any sub type of their return type.
  • Immutable class:-Immutable class is the one whose object can't be modified once created.
  • Any modification in the object results in new immutable object.
  • Immutable objects are thread safe.i.e can be shared without synchronization in concurrent environment.
Service provider framework  of JDBC
  1. service interface:-It provides implement.  ex:Connection
  2. provider registration API:-system uses it to register implementation.   ex.:DriverManager.registerDriver()
  3. service access API:-client use to obtain an instance of the service.  ex.:DriverManager.getConnection()
  4. service provider interface:-providers implement it to create instances of their service implementation.  
ex.:Driver
  • The main disadvantage of providing only static factory methods is that classes without public or protected
  • constructors cannot be sub-classed.
  • For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework.

Item 2 (Consider builder when faced with many constructor parameters)


  • traditional programmers have used telescoping constructor pattern which does not scale well.
  • A second alternative when you are faced with many constructor parameters is the Java-beans pattern, in which you call a parameter less constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest
  • A Java-Bean may be in an inconsistent state partway through its construction.
  • build patters are more safer than java beans.
  • Inner class in java are associated with an outer class while nested static class is not associated with any outer class object, so it's instance can be created independently.

Item 3 (Enforce the singleton property with a private constructor or an enum type)


  • Singleton class can be instantiated exactly once. Implemented by making the constructor private.
  • In serialization aspect, to maintain the singleton property of a class you have to declare all instance field transient and provide a readResolve() method. Otherwise, each time a serialized object is deserialized a new instance will be created.
  • A single element enum type is the best way to implement a singleton.

Item 4 (Enforce noninstantiability with a private constructor)


  • A class having private constructor can't be extended or subclassed.
  • Attempting to enforce non-instantiability by making a class absract does not work.

Item 5 (Avoid creating unnecessary objects)


  • String s = new String("Ashish"); //this is not desirable
  • String s = "Ashish"; //this should be adopted instead
  • It is possible to avoid unnecessary initialization by lazy initialization.

Item 6 (Eliminate obsolete object references)


  • If a stack grows and shrinks the popped off objects will not be garbage collected even if stack has no references to it, this is because a stack maintains obsolete references to these objects.
  • An obsolete reference is simply a reference that will never be dereferenced again.
  • Memory leaks in garbage collected languages are harmful. If an object reference is unintentionally retained, not only is that object excluded from garbage collection, but so too are any objects referenced by that object. So, even if few objects references are unintentionally retained, many, many objects references may be prevented from garbage collection , with potentially large impact on performance.
  • Null out the references once they become obsolete.
  • Whenever a class manages its own memory, the programmer should be aware of memory leaks. 
  • Whenever an element is freed, any object reference contained in that element should be manually nulled out.
  • Another sources of memory leaks are caches and callbacks and listeners.

Item 7 (Aviod Finalizers)


  • Finalizers are often unpredictable, often dangerous, and generally unnecessary.
  • You should not do anything time critical in finalizers because it can arbitrarily takes long between the time that an object becomes unreachable and the time that its finalizer is executed.
  • Creating and Destroying an object in Finalizer severely slows down the perfomances.
  • So, instead of finalizers you should provide explicit termination method.
  • Typical example is close method on InputStream, OutputStream, and java.sql.Connection. Another is cancel method on java.util.Timer.
  • Explicit termination methods are typically used in combination with the try-finally construct to ensure termination.
  • Finalizers can act as a 'safety net' in case the owner of an object fails to call its explicit termination method.
  • A second legitimate use of finalizers concerns objects with native peers.

Tuesday, July 22, 2014

Can you dare to answer these questions?

If swimming is a good exercise to stay FIT,
Why are whales FAT ??


Why is the place in a stadium where people SIT,
called a STAND ?


Why is that everyone wants to go to HEAVEN,
but nobody wants to DIE..


Shall I say that there is racial discrimination even in chess...
As the WHITE piece is moved FIRST...


In our country,
We have FREEDOM of SPEECH,
Then why do we have TELEPHONE BILLS ?


If money doesn't grow on TREES,
then why do banks have BRANCHES ?


Why doesn't GLUE
stick to its BOTTLE ?


Why do you still call it a BUILDING,
when its already BUILT ?


If its true that we are here to HELP others,
What are others HERE for ?
 

If you aren't supposed to DRINK and DRIVE...
Why do bars have PARKING lots ?


If All The Nations In The World Are In Debt,
Where Did All The Money Go..?


When Dog Food Is New With Improved Taste,
Who Tests It..?


If The "Black Box" Flight Recorder Is Never Damaged During A Plane Crash,
Why Isn't The Whole Airplane Made Out Of That Stuff..?


Who Copyrighted
The Copyright Symbol..?


Can You Cry Under Water.?


Why Do People Say "You've Been Working Like A Dog",
When Dogs Just Sit Around All Day..??


We all are Living in a seriously funny world....
So Enjoy 

Wednesday, July 16, 2014

Google and Udacity introducing a course in Android Development

Here is an influencing program for those who aspire about developing android apps. This is an opportunity to learn about from basic, for instance, application layer, application framework, C/C++ libs, Android runtime, Linux kernel. The name of the course is Developing Android Apps: Android Fundamentals.

The course will be demonstrated by Google developers namely, Reto Meier, Dan Galpin and Katherine Kuan. Udacity is an educational organization that offers massive open online courses. By the end of the course you will have created your first real android app.

So undoubtedly, by this step Google wants more developers for its platform. Android is so far prevailing in more than 75 percentage of the smartphones. For more information about this course get in touch with https://www.udacity.com/lp/google.

You can watch the trailer of the course below

















Monday, July 14, 2014

What are static factory methods in java

In java we often have to deal with creating and destroying the objects. Public constructors have been widely used for creating an instance of the class. But for writing programs that are clear, correct, usable, robust, flexible and maintainable static factory method is another technique that every java programmer should know.
Having static factory method does not mean eliminating the constructor. A programmer can use static factory method in addition to public constructors.

Advantages of static factory method

  • Static factory methods have well chosen names.
A static factory method with a name is comfortable for use compared to many public constructors that have variable parameters. If such multiple constructors exist in class then we may end up calling a wrong one by mistake so static factory method eliminates this restriction.
For example, myClass(int a, int b, int c) constructor returns date, month and year then instead of that we could have a static factory method as myClass.retriveDate().

  • Static factory methods improves performance.
If equivalent objects are requested often to the class then a pubic constructor produces a new duplicate object on every request. Static factory methods comes over this drawback. It relieves immutable class from creating unnecessary objects.
It improves performance if repeatedly object creation requests are expensive. So in this way static factory method open up a way for instance-controlled classes (classes that maintain control over what instance exist at any time).


  • Unlike Constructors static factory method returns an object any subtype of their return type.
This flexibility allows classes to return objects without being public. So in this way it hides implementation.

  • Another Advantage is that they decrease the verbosity of creating parameterized type constructors.
 For example, following declaration requires you to provide type parameters two times in quick succession.
Map<String, List<String>> m = new HashMap<String, List<String>>();

 Now using static factory methods we can deploy it easily as follows
 private static <K, V> HashMap<K, V> newInstance()
{
            return new HashMap<K, V>();
}
and u can replace above declaration in a compact way like this
Map<String, List<String>> m = HashMap.newInstance();

Disadvantages of  static factory methods

  • Classes without public or protected constructors cannot be subclassed.
  • Static factory methods are easily distinguishable from other static factory methods.
     In order to overcome this disadvantage you should adhere to some common and unique static factory method naming. For instance, valueOf(), of(), getInstance(), newInstane(), getType(), newType().