Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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.

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().

Monday, July 7, 2014

The Chronicle of Computer Languages

Whether you are from IT sector or not, but one question must have popped up into your mind, what is a computer language? Why it was requited? Actually, I am too young to narrate all the past events and founder of computer languages. But, still I feel crucial to write this post. An answer to the question, why computer languages are requires lies in another question i.e. Why do we require English.? Why don't we speak binary language? Well, because binary language is well specified for computers having no common sense. Computer languages consists of instructions and these instructions participate in communication with computers. The computer languages were set in motion when Charles Babbage proposed the first analytical machine. And the major dominating languages are: BCPL led B, B led to C, C evolved into C++ and C++ set the platform for java and in turn C#. The famous hierarchy of computer languages is as follows.


BCPL

BCPL was developed by Martin Richard in 1966. And it is well known to have influenced B. Few have heard about BCPL because nowadays it seems to be vanished. Actually BCPL is successor to CPL programming language. BCPL system library provided I/O support and very simple memory management. BCPL included integers, reals, bit patterns, I/O streams, various kinds of references, and vectors. BCPL strongly influenced B which in turn influenced C.


B was developed at bell labs with the efforts from Ken Thompson and Dennis Ritchie primarily developed for system programming. It included processing of integers, characters and bit strings.  Code efficiency of this language was good compared to assembly level languages.
B is also extinct and take over by C.

C

C is a programmer's language. Invented and first implemented by Dennis Ritchie. It shook the computer world because it changes the programming approach. Earlier failures of assembly level languages gave C more popularity. The power of C is its structured principles. C is one of the widely used programming language of all the time. It was believed to be a language of modern age. Because of increasing the complexity in C programs led to invention of C++.

C++

C++ is a response to the increasing complexity of programs in C++. However even with a structured programming once a program reaches certain size its complexity exceeds what a programmer can manage. To solve this problem Bjarne Stroustrup invented this object oriented programming. It is a methodology that organize complex programs through the use of inheritance, encapsulation and polymorphism. It led to use of classes. C++ includes all of C's features, attributes, and benefits. so it is an enhancement to an already highly successful one.

JAVA

JAVA was created by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Microsystems, Inc. in 1991. The language was initially called 'oak' but was later renamed to 'JAVA' in 1995. It is an architecturally neutral language. It is portable and platform independent language that could be used to produce code that would run on a variety of CPUs under differing environments. Bytecode is JAVA's magic.

C#

Most important example of JAVA's influence is C#. Recently created by microsoft to support the .NET framework. .Net Framework, C# is closely related to JAVA. for example, both share the same general C++ style, support distributed programming and utilize the same object model. There are of course many difference between JAVA and C#, but the overall look and feel of these languages is very similar. 
This "cross-pollination" from JAVA to C# is the strongest testimonial to date that java redefined the way we think about and use a computer language