Effective java second edition by joshua bloch pdf




















The argument "stringette" is itself one. This call in a loop would create many of them. Use static factory methods in preference to constructors Item 1. Prefer primitives to boxed primitives, and watch out for unintentional autoboxing. If the stack grows and shrinks the objects popped will not be garbage collected. The stack maintains obsolete references a reference that will never be dereferenced. Nulling out objects references should be the exception not the norm.

Do not overcompensate by nulling out every object. Using WeakHashMap is useful when if desired lifetime of cache entries is determined by external references to the key, not the value. Clean oldest entries in cache is a common practice. To accomplish this behaviors, it can be used: background threads, automatically delete older after a new insertion or the LinkedHashMap and its method removeEldestEntry.

To solve it store only weak references to them, for example storing them as keys in a WeakHashMap. Never depend on a finalizer to update critical persistent state. Provide an explicit termination method like the close on InputStream , OutputStream , java.

Explicit termination methods are typically used in combination with the try-finally construct to ensure termination. A class has a notion of logical equality that differs from mere object identity, and a superclass has not already overridden equals to implement the desired behavior. Providing a good toString implementation makes your class much more pleasant to read. When practical, the toString method return all of the interesting information contained in the object.

Always provide programmatic access to all of the information contained in the value returned by toString so the users of the object don't need to parse the output of the toString. Cloneable interface does not contain methods If a class implements Cloneable, Object's clone method returns a field-by-field copy of the object.

Otherwise it throws CloneNotSupportedException. If you override the clone method in a nonfinal class, you should return an object obtained by invoking super.

A class that implements Cloneable is expected to provide a properly functioning public clone method. Simple clone method if object does not contain fields that refer to mutable objects. If object contains fields that refer to mutable objects, we need another solution. Mutable fields will point to same objects in memory and the original and the cloned method will share these objects. Calling clone recursively in the mutable objects is the easiest way.

Mutable objects and finals: The clone architecture is incompatible with normal use of final fields referring to mutable objects. More complex objects would need specific approaches where recursively calling clone won't work.

A clone method should not invoke any nonfinal methods on the clone under construction Item Object's clone method is declared to throw CloneNotSupportedException , but overriding clone methods can omit this declaration. Public clone methods should omit it. Item If a class overrides clone, the overriding method should mimic the behavior of Object. Subclasses are free to implement Cloneable or not, just as if they extended Object directly.

Sorting an array of objects that implement Comparable is as simple as Arrays. The class will interoperate with many generic algorithms and collection implementations that depend on this interface.

You gain lot of power with small effort. If a package-private top level class is used by only one class make it a private nested class of the class that uses it. It is acceptable to make a private member of a public class package-private in order to test it. Instance fields should never be public Item 14 Class will not be thread-safe. Static fields can be public if contain primitive values or references to immutable objects.

A final field containing a reference to a mutable object has all the disadvantages of a non final field. They don't benefit from encapsulation Item Replace them with accessor methods getters and mutators setters. If a class is accessed outside its package , provide accesor methods.

If a class is package-private or is a private nested class , its ok to expose its data fields. In public classes it is a questionable option to expose immutable fields. All the information of the instance is provided when it is created. They are easier to design, implement and use. And they are less prone to errors and more secure.

The arithmetic operation create and return a new instance. Functional approach. Immutable objects are thread-safe. Synchronization is not required. They can be shared freely and can reuse existing instances. Using static factories can create constants of frequently requested instances and serve them in future requests.

The disadvantage is that a separate object is required for distinct values. In some cases it could create a performance problem.

Make all of its constructors private or package-private and add a public static factory. This technique allows flexibility of multiple implementations, it's possible to tune the performance and permit to create more factories with names that clarify its function. Some of the rules can be relaxed to improve performance caching, lazy initialization Inheritance in this case is when a class extends another implementation inheritance Not interface inheritance.

A subclass depends on the implementation details of its superclass. If the superclass change the subclass may break. The superclass can aquire new methods in new releases that might not be added in the subclass.

Instead of extending, give your new class a private field that references an instance of the existing class. Each instance method in the new class forwarding class invokes the corresponding method forwarding methods on the contained instance of the existing class and returns the results.

Methods and constructors should document which overridable methods or constructors nonfinal, and public or protected invokes. The description begins with the phrase "This implementation. To document a class so that it can be safely subclassed, you must describe implementations details. To allow programmers to write efficient subclasses without undue pain, a class may have to provide hooks into its internal working in the form of judiciously chosen protected methods.

Test the class for subclassing. The only way to test a class designed for inheritance is to write subclasses. Constructors must not invoke overridable methods. For Serializable and Cloneable implementations neither clone nor readObject may invoke overridable methods.

Prohibit subclassing in classes that are not designed and documented to be safely subclassed. Consider using Item 16 if what you want is to increase the functionality of your class instead of subclassing. Java permits only single Inheritance, this restriction on abstract classes severely contrains their use as type functions. Inteface is generally the best way to define a type that permits multiple implementations.

Interfaces are ideal for defining mixins a type that a class can implement in addition to its primary type to declare that it provides some optional bahaviour. Interfaces enable safe, powerful functionality enhancements Wrapper class. Combine the virtues of interfaces and abstract classes, by providing an abstract skeletal implementation class to go with each nontrivial interface that you export. Skeletal implementations are designed for inheritance so follow Item 17 guidelines.

Cons: It is far easier to evolve an abstract class than an interface. Once an interface is released and widely implemented, it is almost impossible to change. When a class implements an interface, the interface serves as a type that can be used to refer to instances of the class.

Better use an enum type Item 31 , or a noninstantiable utility class Item 4. They have lot of boilerplate, bad readability, increase memory footprint, and more shortcommings. Strategies are facilities that allow programs to store and transmit the ability to invoke a particular function.

Similar to function pointers , delegates or lambda expression. Concrete strategies are typically stateless threfore they should be singletons. To be able to pass different strategies, clients should invoke methods from a strategy interface instead of a concrete class.

Comparator interface. Generic Item An anonymous class will create a new instance each time the call is executed. Consider a private static final field and reusing it.

Concrete strategy class don't need to be public, because the strategy interface serve as a type. A host class can export the a public static field or factory, whose type is the interface and the concrete strategy class is a private nested class. Static , a member class that does not require access to an enclosing instance must be static. Storing references cost time, space and can cost not wanted behaviors of the garbage collector Item 6.

Common use of static member class is a public helper in conjuctions with its outer class. A nested class enum Operation in Calculator class. PLUS ;. Nonstatic member class instances are required to have an enclosing instance.

Anonymous classes are used to create function objects on the fly. Local class from the official docs: Use it if you need to create more than one instance of a class, access its constructor, or introduce a new, named type because, for example, you need to invoke additional methods later. Anonymous class, from the official docs: Use it if you need to declare fields or additional methods.

Generic classes and interfaces are the ones who have one or more type parameter as generic , i. Raw types is the generic type definition without type parameters.

There are subtyping rules for generics. Arrays are reified : Arrays know and enforce their element types at runtime. Generics are erasure : Enforce their type constrains only at compile time and discard or erase their element type information at runtime. Therefore it is illegal to create an array of a generic type, a parameterized type or a type parameter.

A cast will generate a warning. Beacuse E is a non-reifiable type, there is no way the compiler can check the cast at runtime. In generic constructors the type parameters have to be on both sides of the declaration.

Java 1. Generic Singleton Pattern Create an object that is immutable but applicable to many different types. Recursive Type Bound : When the type paremeter is bounded by some expression involving that type parameter itself.

Parameterized types are invariant. Comparable and Comparators are always consumers. If a type parameter appears only once in a method declaration, replace it with a wildcard. Enums are classes that export one instance for each enumeration constant via a public static final field. Clients can not create instances or extend them. They are a generalization of singletons Item 3 They are compile-time type safe. This books is best suited for programmers and learners who already know basic programming in Java and are willing to sharpen their Java programming skills.

This books scores high on quality, content and illustration. Download: Effective Java 2nd Edition. This books also covers some other libraries in brief, but it does not cover graphical user interface programming, mobile devices and enterprise APIs. There are 78 items in the book and they are grouped into 10 chapters.

Each of these chapters cover one aspect of software development and design in broad sense. All the items are thoroughly illustrated with program examples with design patterns and Java idioms.

And, one good feature of Effective Java is that it also points out some bad practices such as antipatterns to be avoided. Copyright issues : The pdf version of this book is made available here for download for academic purpose only, i.

As clarity and simplicity are given paramount importance in this book, anyone who knows a thing or two about Java may find it extremely useful. If you come to know about newer editions of the book, please mention them in the comments section. Look no further! This highly anticipated new edition of the classic, Jolt Award-winning work has been thoroughly updated to cover Java SE 5 and Java SE 6 features introduced since the first edition. Bloch explores new design patterns and language idioms, showing you how to make the most of features ranging from generics to enums, annotations to autoboxing.

The comprehensive descriptions and explanations for each item illuminate what to do, what not to do, and why. New coverage of generics, enums, annotations, autoboxing, the for-each loop, varargs, concurrency utilities, and much more.

Updated techniques and best practices on classic topics, including objects, classes, libraries, methods, and serialization. Effective Java 3rd Edition contains a lot of changes as compare to 2nd edition. Here is some idea about what is new in effective java 3rd edition. Effective Java 3rd Edition contains some new ideas for developers to know about java 7, java 8 and java 9.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website.



0コメント

  • 1000 / 1000