{"id":13392853,"url":"https://github.com/HugoMatilla/Effective-JAVA-Summary","last_synced_at":"2025-03-13T19:31:06.682Z","repository":{"id":41203423,"uuid":"46879221","full_name":"HugoMatilla/Effective-JAVA-Summary","owner":"HugoMatilla","description":"Summary of the book Effective Java 2nd Edition by Joshua Bloch","archived":false,"fork":false,"pushed_at":"2024-07-22T08:40:01.000Z","size":103,"stargazers_count":1481,"open_issues_count":1,"forks_count":412,"subscribers_count":46,"default_branch":"master","last_synced_at":"2025-01-28T23:49:26.549Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HugoMatilla.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-11-25T18:26:03.000Z","updated_at":"2025-01-27T09:26:07.000Z","dependencies_parsed_at":"2024-10-25T09:23:18.645Z","dependency_job_id":"e702d62f-b6c8-4dcb-9373-50d150db98ab","html_url":"https://github.com/HugoMatilla/Effective-JAVA-Summary","commit_stats":{"total_commits":116,"total_committers":19,"mean_commits":6.105263157894737,"dds":"0.22413793103448276","last_synced_commit":"fff99e56c5bff016664c06d95077b21c1bb100c9"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HugoMatilla%2FEffective-JAVA-Summary","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HugoMatilla%2FEffective-JAVA-Summary/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HugoMatilla%2FEffective-JAVA-Summary/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HugoMatilla%2FEffective-JAVA-Summary/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HugoMatilla","download_url":"https://codeload.github.com/HugoMatilla/Effective-JAVA-Summary/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243469122,"owners_count":20295691,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T17:00:38.147Z","updated_at":"2025-03-13T19:31:06.395Z","avatar_url":"https://github.com/HugoMatilla.png","language":null,"funding_links":[],"categories":["Programming Language Design Patterns","Language/Framework design patterns (mainly GoF)","Others","编程语言设计模式","Book summaries, notes and reviews"],"sub_categories":["**Java**"],"readme":"_This is my summary of the Effective Java 2nd Edition by Joshua Bloch. I use it while learning and as quick reference. It is not intended to be an standalone substitution of the book so if you really want to learn the concepts here presented, buy and read the book and use this repository as a reference and guide._\n\n_If you are the publisher and think this repository should not be public, just write me an email at hugomatilla \\[at\\] gmail \\[dot\\] com and I will make it private._\n\n**Contributions:** Issues, comments and pull requests are super welcome :smiley:\n\n# 1. TABLE OF CONTENTS\n\n- [1. TABLE OF CONTENTS](#1-table-of-contents)\n- [2. CREATING AND DESTROYING OBJECTS](#2-creating-and-destroying-objects)\n  - [1. Use STATIC FACTORY METHODS instead of constructors](#1-use-static-factory-methods-instead-of-constructors)\n  - [2. Use BUILDERS when faced with many constructors](#2-use-builders-when-faced-with-many-constructors)\n  - [3. Enforce the singleton property with a private constructor or an enum type](#3-enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type)\n  - [4. Enforce noninstantiability with a private constructor](#4-enforce-noninstantiability-with-a-private-constructor)\n  - [5. Avoid creating objects](#5-avoid-creating-objects)\n  - [6. Eliminate obsolete object references](#6-eliminate-obsolete-object-references)\n  - [7. Avoid finalizers](#7-avoid-finalizers)\n- [3. METHODS COMMON TO ALL OBJECTS](#3-methods-common-to-all-objects)\n  - [8. Obey the general contract when overriding _equals_](#8-obey-the-general-contract-when-overriding-equals)\n  - [9. Always override _hashCode_ when you override _equals_](#9-always-override-hashcode-when-you-override-equals)\n  - [10. Always override _toString_](#10-always-override-tostring)\n  - [11. Override _clone_ judiciously](#11-override-clone-judiciously)\n  - [12. Consider implementing _Comparable_](#12-consider-implementing-comparable)\n- [4. CLASSES AND INTERFACES](#4-classes-and-interfaces)\n  - [13. Minimize the accessibility of classes and members](#13-minimize-the-accessibility-of-classes-and-members)\n  - [14. In public classes, use accessor methods, not public fields](#14-in-public-classes-use-accessor-methods-not-public-fields)\n  - [15. Minimize Mutability](#15-minimize-mutability)\n  - [16. Favor composition over inheritance](#16-favor-composition-over-inheritance)\n  - [17. Design and document for inheritance or else prohibit it.](#17-design-and-document-for-inheritance-or-else-prohibit-it)\n  - [18. Prefer interfaces to abstract classes](#18-prefer-interfaces-to-abstract-classes)\n  - [19. Use interfaces only to define types](#19-use-interfaces-only-to-define-types)\n  - [20. Prefer class hierarchies to tagged classes](#20-prefer-class-hierarchies-to-tagged-classes)\n  - [21. Use function objects to represent strategies](#21-use-function-objects-to-represent-strategies)\n  - [22. Favor static member classes over nonstatic](#22-favor-static-member-classes-over-nonstatic)\n- [5. GENERICS](#5-generics)\n  - [23. Don't use raw types in new code](#23-dont-use-raw-types-in-new-code)\n  - [24. Eliminate unchecked warnings](#24-eliminate-unchecked-warnings)\n  - [25. Prefer lists to arrays](#25-prefer-lists-to-arrays)\n  - [26. Favor generic types](#26-favor-generic-types)\n  - [27. Favor generic Methods](#27-favor-generic-methods)\n  - [28. Use bounded wildcards to increase API flexibility](#28-use-bounded-wildcards-to-increase-api-flexibility)\n  - [29. Consider _typesafe heterogeneous containers_](#29-consider-typesafe-heterogeneous-containers)\n- [6. ENUMS AND ANNOTATIONS](#6-enums-and-annotations)\n  - [30. Use enums instead of _int_ constants](#30-use-enums-instead-of-int-constants)\n  - [31. Use instance fields instead of ordinals](#31-use-instance-fields-instead-of-ordinals)\n  - [32. Use EnumSet instead of bit fields](#32-use-enumset-instead-of-bit-fields)\n  - [33. Use EnumMap instead of ordinal indexing](#33-use-enummap-instead-of-ordinal-indexing)\n  - [34. Emulate extensible enums with interfaces](#34-emulate-extensible-enums-with-interfaces)\n  - [35. Prefer annotations to naming patterns](#35-prefer-annotations-to-naming-patterns)\n  - [36. Consistently use the _Override_ annotation](#36-consistently-use-the-override-annotation)\n  - [37. Use marker interfaces to define types](#37-use-marker-interfaces-to-define-types)\n- [7. METHODS](#7-methods)\n  - [38. Check parameters for validity](#38-check-parameters-for-validity)\n  - [39. Make defensive copies when needed.](#39-make-defensive-copies-when-needed)\n  - [40. Design method signatures carefully](#40-design-method-signatures-carefully)\n  - [41. Use overloading judiciously](#41-use-overloading-judiciously)\n  - [42. Use varargs judiciously](#42-use-varargs-judiciously)\n  - [43. Return empty arrays or collections, not nulls](#43-return-empty-arrays-or-collections-not-nulls)\n  - [44. Write _doc comments_ for all exposed API elements](#44-write-doc-comments-for-all-exposed-api-elemnts)\n- [8. GENERAL PROGRAMMING](#8-general-programming)\n  - [45. Minimize the scope of local variables.](#45-minimize-the-scope-of-local-variables)\n  - [46. Prefer for-each loops to traditional for loops.](#46-prefer-for-each-loops-to-traditional-for-loops)\n  - [47. Know and use libraries](#47-know-and-use-libraries)\n  - [48. Avoid float and double if exact answer are required](#48-avoid-float-and-double-if-exact-answer-are-required)\n  - [49. Prefer primitive types to boxed primitives](#49-prefer-primitive-types-to-boxed-primitives)\n  - [50. Avoid Strings where other types are more appropriate](#50-avoid-strings-where-other-types-are-more-appropriate)\n  - [51. Beware the performance of string concatenation](#51-beware-the-performance-of-string-concatenation)\n  - [52. Refer to objects by their interface](#52-refer-to-objects-by-their-interface)\n  - [53. Prefer interfaces to reflection](#53-prefer-interfaces-to-reflection)\n  - [54. Use native methods judiciously](#54-use-native-methods-judiciously)\n  - [55. Optimize judiciously](#55-optimize-judiciously)\n  - [56. Adhere to generally accepted naming conventions](#56-adhere-to-generally-accepted-naming-conventions)\n- [9. EXCEPTIONS](#9-exceptions)\n  - [57. Use exceptions only for exceptional conditions](#57-use-exceptions-only-for-exceptional-conditions)\n  - [58. Use checked exceptions for recoverable conditions and runtime exceptions for programming errors](#58-use-checked-exceptions-for-recoverable-conditions-and-runtime-exceptions-for-programming-errors)\n  - [59. Avoid unnecessary use of checked exceptions](#59-avoid-unnecessary-use-of-checked-exceptions)\n  - [60. Favor the use of standard exceptions](#60-favor-the-use-of-standard-exceptions)\n  - [61. Throw exceptions appropriate to the abstraction](#61-throw-exceptions-appropriate-to-the-abstraction)\n  - [62. Document all exceptions thrown by each method](#62-document-all-exceptions-thrown-by-each-method)\n  - [63. Include failure-capture information in detail messages](#63-include-failure-capture-information-in-detail-messages)\n  - [64. Strive for failure atomicity](#64-strive-for-failure-atomicity)\n  - [65. Don't ignore exceptions](#65-dont-ignore-exceptions)\n- [10. CONCURRENCY](#10-concurrency)\n  - [66. Synchronize access to shared mutable data](#66-synchronize-access-to-shared-mutable-data)\n  - [67. Avoid excessive synchronization](#67-avoid-excessive-synchronization)\n  - [68. Prefer executors and tasks to threads](#68-prefer-executors-and-tasks-to-threads)\n  - [69. Prefer concurrency utilities to _wait_ and _notify_](#69-prefer-concurrency-utilities-to-wait-and-notify)\n  - [70. Document thread safety](#70-document-thread-safety)\n  - [71. Use lazy initialization judiciously](#71-use-lazy-initialization-judiciously)\n  - [72. Don't depend on thread scheduler](#72-dont-depend-on-thread-scheduler)\n  - [73. Avoid thread groups](#73-avoid-thread-groups)\n- [11. SERIALIZATION](#11-serialization)\n  - [74. Implement _Serializable_ judiciously](#74-implement-serializable-judiciously)\n  - [75. Consider using a custom serialized form](#75-consider-using-a-custom-serialized-form)\n  - [76. Write _readObject_ methods defensively](#76-write-readobject-methods-defensively)\n  - [77. For instance control, prefer _enum_ types to _readResolve_](#77-for-instance-control-prefer-enum-types-to-readresolve)\n  - [78. Consider serialization proxies instead of serialized instances](#78-consider-serialization-proxies-instead-of-serialized-instances)\n\n# 2. CREATING AND DESTROYING OBJECTS\n\n## 1. Use STATIC FACTORY METHODS instead of constructors\n\n**_ADVANTAGES_**\n\n- Unlike constructors, they have names\n- Unlike constructors, they are not required to create a new object each time they're invoked\n- Unlike constructors, they can return an object of any subtype of their return type\n- They reduce verbosity of creating parameterized type instances\n\n**_DISADVANTAGES_**\n\n- If providing only static factory methods, classes without public or protected constructors cannot be subclassed (encourage to use composition instead inheritance).\n- They are not readily distinguishable from other static methods (Some common names (each with a different pourpose) are: valueOf, of, getInstance, newInstance, getType and newType)\n\n```java\n\n\tpublic static Boolean valueOf(boolean b){\n\t\treturn b ? Boolean.TRUE :  Boolean.FALSE;\n\t}\n```\n\n## 2. Use BUILDERS when faced with many constructors\n\nIs a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.\n\nBuilder pattern simulates named optional parameters as in ADA and Python.\n\n```java\n\n\tpublic class NutritionFacts {\n\t\tprivate final int servingSize;\n\t\tprivate final int servings;\n\t\tprivate final int calories;\n\t\tprivate final int fat;\n\t\tprivate final int sodium;\n\t\tprivate final int carbohydrate;\n\n\t\tpublic static class Builder {\n\t\t\t//Required parameters\n\t\t\tprivate final int servingSize:\n\t\t\tprivate final int servings;\n\n\t\t\t//Optional parameters - initialized to default values\n\t\t\tprivate int calories\t\t= 0;\n\t\t\tprivate int fat \t\t\t= 0;\n\t\t\tprivate int carbohydrate \t= 0;\n\t\t\tprivate int sodium \t\t\t= 0;\n\n\t\t\tpublic Builder (int servingSize, int servings) {\n\t\t\t\tthis.servingSize = servingSize;\n\t\t\t\tthis.servings = servings;\n\t\t\t}\n\n\t\t\tpublic Builder calories (int val) {\n\t\t\t\tcalories = val;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder fat (int val) {\n\t\t\t\tfat = val;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder carbohydrate (int val) {\n\t\t\t\tcarbohydrate = val;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic Builder sodium (int val) {\n\t\t\t\tsodium = val;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\t\tpublic NutritionFacts build(){\n\t\t\t\treturn new NutritionFacts(this);\n\t\t\t}\n\t\t}\n\n\t\tprivate NutritionFacts(Builder builder){\n\t\t\tservingSize\t\t= builder.servingSize;\n\t\t\tservings \t\t= builder.servings;\n\t\t\tcalories\t\t= builder.calories;\n\t\t\tfat \t\t\t= builder.fat;\n\t\t\tsodium \t\t\t= builder.sodium;\n\t\t\tcarbohydrate\t\t= builder.carbohydrate;\n\t\t}\n\t}\n```\n\n**_Calling the builder_**\n\n```java\n\n\tNutritionFacts cocaCola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();\n\n```\n\n## 3. Enforce the singleton property with a private constructor or an enum type\n\nThere are different ways to create singletons:\n\n**_Public final field_**\n\n```java\n\n\tpublic class Elvis{\n\t\tpublic static final Elvis INSTANCE = new Elvis();\n\t\tprivate Elvis(){...}\n\t\t...\n\t\tpublic void singASong(){...}\n\t}\n```\n\nOne problem is that a privileged client can invoke the private constructor reflectively. Against this attack the constructor needs to be modified to send an exception if it is asked to create a second instance.\n\n**_Singleton with static factory_**\n\n```java\n\n\tpublic class Elvis{\n\t\tprivate static final Elvis INSTANCE = new Elvis();\n\t\tprivate Elvis(){...}\n\t\tpublic static Elvis getInstance(){ return INSTANCE; }\n\t\t...\n\t\tpublic void singASong(){...}\n\t}\n```\n\nIn this approach it can be change to a non singleton class without changing the class API.\n\n**_Serialize a singleton_**\n\nIt is needed a _readResolve_ method and declare all the fields _transient_ in addition to the _implements Serializable_ to maintain the singleton guarantee.\n\n```java\n\n\tprivate Object readResolve(){\n\t\t//Return the one true Elvis and let the garbage collector take care of the Elvis impersonator\n\t\treturn INSTANCE;\n\t}\n```\n\n**_Enum Singleton, the preferred approach (JAVA 1.5)_**\n\n```java\n\n\tpublic enum Elvis(){\n\t\tINSTANCE;\n\t\t...\n\t\tpublic void singASong(){...}\n\t}\n```\n\nEquivalent to the public field, more concise, provides serialization machinery for free, and guarantee against multiple instantiation, even for reflection attacks and sophisticated serialization. _It is the best way to implement a singleton_.\n\n## 4. Enforce noninstantiability with a private constructor\n\nFor classes that group static methods and static fields.\n\nUsed for example to:\n\n- Group related methods on primitive values or arrays.\n- Group static methods, including factory methods, for objects that implement a particular interface.\n- Group methods on a final class instead of extending the class.\n\n**_Include a private constructor_**\n\n```java\n\n\tpublic class UtilityClass{\n\t\t// Suppress default constructor for noninstantiability\n\t\t// (Add comment to clarify why the constructor is expressly provided)\n\t\tprivate UtilityClass(){\n\t\t\tthrow new AssertionError();\n\t\t}\n\t\t...\n\t}\n```\n\n## 5. Avoid creating objects\n\n**REUSE IMMUTABLE OBJECTS**\n\n**_Don't do this_**\n\n```java\n\n\tString s = new String(\"stringette\");\n```\n\nEvery call creates a new String instance. The argument _\"stringette\"_ is itself one. This call in a loop would create many of them.\n\n**_Do this_**\n\n```java\n\n\tString s = \"stringette\";\n```\n\nThis one uses a single String instance rather than creating a new one.\n\n**_Use static factory methods in preference to constructors [Item 1](#1-use-static-factory-methods-instead-of-constructors)_**\n\n_Boolean.valueOf(String);_ Is preferable to the constructor _Boolean(String)_.\n\n**REUSE MUTABLE OBJECTS THAT WON'T BE MODIFIED**\n\n**_Don't do this_**\n\n```java\n\n\tpublic class Person {\n\tprivate final Date birthDate;\n\t...\n\t\tpublic boolean isBabyBoomer(){\n\t\t\t// Unnecessary allocation of expensive object.\n\t\t\tCalendar gmtCal= Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n\t\t\tgmtCal.set(1946,Calendar.JANUARY,1,0,0,0);\n\t\t\tDate boomStart = gmtCal.getTime();\n\t\t\tgmtCal.set(1965,Calendar.JANUARY,1,0,0,0);\n\t\t\tDate boomEnd = gmtCal.getTime();\n\t\t\treturn birthDate.compareTo(boomStart) \u003e= 0 \u0026\u0026birthDate.compareTo(boomEnd)\u003c0;\n\t\t}\n\t}\n```\n\nisBabyBoomer creates a new Calendar,TimeZone and two Date instances each time is invoked.\n\n```java\n\n\tpublic class Person {\n\tprivate final Date birthDate;\n\t...\n\tprivate static final Date BOOM_START;\n\tprivate static final Date BOOM_END;\n\n\tstatic {\n\t\t\tCalendar gmtCal= Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n\t\t\tgmtCal.set(1946,Calendar.JANUARY,1,0,0,0);\n\t\t\tBOOM_START = gmtCal.getTime();\n\t\t\tgmtCal.set(1965,Calendar.JANUARY,1,0,0,0);\n\t\t\tBOOM_END = gmtCal.getTime();\n\t}\n\t\tpublic boolean isBabyBoomer(){\n\t\t\treturn birthDate.compareTo(BOOM_START) \u003e= 0 \u0026\u0026birthDate.compareTo(BOOM_END)\u003c0;\n\t\t}\n\t}\n```\n\n**_Prefer primitives to boxed primitives, and watch out for unintentional autoboxing_**\n\n```java\n\n\t//Slow program. Where is the object creation?\n\tpublic static void main (String[] args){\n\t\tLong sum = 0L;\n\t\tfor (long i = 0 ; i\u003c= Integer.MAX_VALUE; i++){\n\t\t\tsum+=i;\n\t\t}\n\t\tSystem.out.println(sum);\n\t}\n```\n\n_sum_ is declared as _Long_ instead of _long_ that means that the programs constructs  \n Long instances.\n\n**_Object pools are normally bad ideas_**\n\nUnless objects in the pool are extremely heavyweight, like a database connections.\n\n## 6. Eliminate obsolete object references\n\n**_Can you spot the memory leak?_**\n\n```java\n\n\tpublic class Stack{\n\t\tprivate Object[] elements;\n\t\tprivate int size = 0;\n\t\tprivate static final int DEFAULT_INITIAL_CAPACITY = 16;\n\n\t\tpublic Stack(){\n\t\t\telements = new Object [DEFAULT_INITIAL_CAPACITY];\n\t\t}\n\n\t\tpublic void push(Object e){\n\t\t\tensureCapacity();\n\t\t\telements[size++] = e;\n\t\t}\n\n\t\tpublic Object pop(){\n\t\t\tif (size == 0)\n\t\t\t\tthrow new EmptyStackException();\n\t\t\treturn elements[--size];\n\t\t}\n\n\t\tprivate void ensureCapacity(){\n\t\t\tif(elements.length == size)\n\t\t\t\telements = Array.copyOf(elements, 2 * size + 1);\n\t\t}\n\t}\n```\n\nIf 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).\n\n**_Null out references_**\n\n```java\n\n\tpublic pop(){\n\t\tif (size == 0)\n\t\t\tthrow new EmptyStackException();\n\t\tObject result = elements[--size];\n\t\telements[size] = null; // Eliminate obsolete references.\n\t\treturn result;\n\t}\n```\n\nNulling out objects references should be the exception not the norm. Do not overcompensate by nulling out every object.\n\nNull out objects only in classes that manages its own memory.\n\n**_Memory leaks in cache_**\n\nUsing _WeakHashMap_ is useful when if desired lifetime of cache entries is determined by external references to the key, not the value.\n\nClean 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_.\n\n**_Memory leaks in listeners and callbacks_**\n\nIf clients register callbacks, but never deregister them explicitly.\n\nTo solve it store only _weak references_ to them, for example storing them as keys in a _WeakHashMap_.\n\n**Use a Heap Profiler from time to time to find unseen memory leaks**\n\n## 7. Avoid finalizers\n\nFinalizers are unpredictable, often dangerous and generally.\n\n**_Never do anything time-critical in a finalizer._**\n\n\u003e There is no guarantee they'll be executed promptly.\n\n**_Never depend on a finalizer to update critical persistent state._**\n\n\u003e There is no guarantee they'll be executed at all.\n\nUncaught exceptions inside a finalizer won't even print a warning.\n\nThere is a severe performance penalty for using finalizers.\n\n**_Possible Solution_**\n\nProvide an _explicit termination method_ like the _close_ on _InputStream_, _OutputStream_, _java.sql.Connection_...\n\nExplicit termination methods are typically used in combination with the _try-finally_ construct to ensure termination.\n\n```java\n\n\tFoo foo = new Foo(...);\n\ttry {\n\t    // Do what must be done with foo\n\t    ...\n\t} finally {\n\t    foo.terminate();  // Explicit termination method\n\t}\n```\n\n**They are good for this two cases**\n\n- As a safety net. Ask yourself if the extra protection is worth the extra cost.\n- Use in native peers. Garbage collector doesn't know about this objects.\n\nIn this cases always remember to invoke super.finalize.\n\n# 3. METHODS COMMON TO ALL OBJECTS\n\n## 8. Obey the general contract when overriding _equals_\n\n**_Don't override if:_**\n\n- Each instance of the class is inherently unique. I.e._Thread_\n- You don't care whether the class provides a \"logical equality\" test. I.e. _java.util.Random_\n- A superclass has already overridden _equals_, and the superclass behavior is appropriate for this class I.e. _Set_\n- The class is private or package-private, and you are certain that its _equals_ method will never be invoked\n\n**_Override if:_**\n\nA 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.\n\n**_Equals implements an \"equivalence relation\"_**\n\n- Reflexive: _x.equals(x)==true_\n- Symmetric: _x.equals(y)==y.equals(x)_\n- Transitive: _x.equals(y)==y.equals(z)==z.equals(x)_\n- Consistent: _x.equals(y)==x.equals(y)==x.equals(y)==..._\n- Non-nullity: _x.equals(null)-\u003efalse_\n\n**_The Recipe_**\n\n1. Use the == operator to check if the argument is a reference to this object (for performance)\n2. Use the _instanceof_ operator to check if the argument has the correct type\n3. Cast the argument to the correct type\n4. For each \"significant\" field in the class, check if that field of the argument matches the corresponding field of this object\n5. When you are finished writing your _equals_ method, ask yourself three questions: Is it Symmetric? Is it Transitive? Is it Consistent? (the other 2 usually take care of themselves)\n\n```java\n\n\t@Override\n\tpublic boolean equals (Object o){\n\t\tif(o == this)\n\t\t\treturn true;\n\n\t\tif (!(o instanceof PhoneNumber))\n\t\t\treturn false;\n\n\t\tPhoneNumber pn = (PhoneNumber)o;\n\t\treturn pn.lineNumber == lineNumber\n\t\t\t\u0026\u0026 pn.prefix == prefix\n\t\t\t\u0026\u0026 pn.areaCode == areaCode;\n\t}\n```\n\n**_Never Forget_**\n\n- Always override _hashCode_ when you override _equals_\n- Don't try to be too clever (simplicity is your friend)\n- Don't substitute another type for _Object_ in the _equals_ declaration\n\n## 9. Always override _hashCode_ when you override _equals_\n\n**_Contract of hashCode_**\n\n- Whenever _hashCode_ is invoked in the same object it should return the same integer.\n- If two objects are equals according to the _equals_, the should return the same integer calling _hashCode_.\n- Is not required (but recommended) that two non _equals_ objects return distinct _hashCode_.\n\nThe second condition is the one that is more often violated.\n\n**_The Recipe_**\n\n1. Store constant value i.e. 17 in an integer called _result_.\n2. For each field _f_ used in _equals_ do:\n\n- Compute _c_\n  - boolean: _(f ? 1 : 0)_\n  - byte, char, short or int: _(int) f_\n  - long: _(int) (f ^ (.f \u003e\u003e\u003e 32))_\n  - float: _Float.floatToIntBits(f)_\n  - double: _Double.doubleToLongBits(f)_ and compute as a long\n  - object reference: if _equals_ of the reference use recutsivity, use recursivity for the _hashCode_\n  - array: each element as a separate field.\n- Combine: _result = 31 \\* result + c_\n\n3. Return _result_\n4. Ask yourself if equal instances have equal hash codes.\n\n```java\n\n\tprivate volatile int hashCode; // Item 71 (Lazily initialized, cached hashCode)\n\n\t@Override public int hashCode(){\n\t\tint result = hashCode;\n\t\tif (result == 0){\n\t\t\tresult = 17;\n\t\t\tresult = 31 * result + areaCode;\n\t\t\tresult = 31 * result + prefix;\n\t\t\tresult = 31 * result + lineNumber;\n\t\t\thashCode = result;\n\t\t}\n\t\treturn result;\n\t}\n```\n\n## 10. Always override _toString_\n\nProviding a good _toString_ implementation makes your class much more pleasant to read.\n\nWhen practical, the _toString_ method return all of the interesting information contained in the object.\n\nIt is possible to specify the format of return value in the documentation.\n\nAlways 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_\n\n## 11. Override _clone_ judiciously\n\nCloneable interface does not contain methods\nIf a class implements Cloneable, Object's clone method returns a field-by-field copy of the object.\nOtherwise it throws CloneNotSupportedException.\n\nIf you override the clone method in a nonfinal class, you should return an object obtained by invoking _super.clone_.\nA class that implements _Cloneable_ is expected to provide a properly functioning public _clone_ method.\n\nSimple clone method if object does **not** contain fields that refer to mutable objects.\n\n```java\n\n\t@Override public PhoneNumber clone() {\n\t\ttry {\n\t\t\t//PhoneNumber.clone must cast the result of super.clone() before returning it.\n\t\t\treturn (PhoneNumber) super.clone();\n\t\t} catch(CloneNotSupportedException e) {\n\t\t\tthrow new AssertionError(); // Can't happen\n\t\t}\n\t}\n```\n\nIf 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.\n\n_clone_ is another constructor and therefore it must ensure not harming the original object and establishing invariants.  \nCalling _clone_ recursively in the mutable objects is the easiest way.\n\n```java\n\n\t@Override public Stack clone() {\n\t\ttry {\n\t\t\tStack result = (Stack) super.clone();\n\t\t\t// From Java 1.5, don't need casting when cloning arrays\n\t\t\tresult.elements = elements.clone();\n\t\t\treturn result;\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\tthrow new AssertionError();\n\t\t}\n\t}\n```\n\nMutable objects and finals: The _clone_ architecture is incompatible with normal use of final fields referring to mutable objects.\nMore complex objects would need specific approaches where recursively calling _clone_ won't work.\n\nA _clone_ method should not invoke any nonfinal methods on the clone under construction ([Item 17](#17-design-and-document-for-inheritance-or-else-prohibit-it)).\n\nObject's _clone_ method is declared to throw _CloneNotSupportedException_, but overriding clone methods can omit this declaration.  \nPublic _clone_ methods should omit it. ([Item 59](#59-avoid-unnecessary-use-of-checked-exceptions)).  \nIf a class overrides clone, the overriding method should mimic the behavior of _Object.clone_:\n\n- it should be declared protected,\n- it should be declared to throw CloneNotSupportedException,\n- it should not implement Cloneable.\n\nSubclasses are free to implement Cloneable or not, just as if they extended Object directly\n\n_clone_ method must be properly synchronized just like any other method ([Item 66](#66-synchronize-access-to-shared-mutable-data)).\n\nSummary: classes that implement Cloneable should create a method that:\n\n- override clone\n- return type is the class\n- call _super.clone_\n- fix fields that need to be fixed\n\nBetter provide an alternative of object copying, or don't provide it at all.\n\n**Copy Constructor**\n\n```java\n\n\tpublic Yum(Yum yum);\n```\n\n**Copy Factory**\n\n```java\n\n\tpublic static Yum newInstance(Yum yum);\n```\n\nThese alternatives:\n\n- don't rely on a risk-prone extra-linguistic object creation mechanism\n- don't demand adherence to thinly documented conventions\n- don't conflict with the proper use of final fields\n- don't throw unnecessary checked exceptions\n- don't require casts.\n\nFurthermore they can use its Interface-based copy constructors and factories, _conversion constructors_ and _conversion factories_ and allow clients to choose the implementation type `public HashSet(Set set) -\u003e TreeSet;`\n\n## 12. Consider implementing _Comparable_\n\n_Comparable_ is an interface. It is not declared in _Object_\n\nSorting an array of objects that implement _Comparable_ is as simple as `Arrays.sort(a);`\n\nThe class will interoperate with many generic algorithms and collection implementations that depend on this interface. You gain lot of power with small effort.\n\nFollow this provisions (Reflexive, Transitive, Symmetric):\n\n1. `if a \u003e b then b \u003c a` `if a == b then b == a` `if a \u003c b then b \u003e a`\n2. `if a \u003e b and b \u003e c then a \u003e c`\n3. `if a ==  b and b == c then a == c`\n4. Strong suggestion: `a.equals(b) == a.compareTo(b)`\n\nFor integral primitives use `\u003c` and `\u003e`operators.\n\nFor floating-point fields use _Float.compare_ or _Double.compare_\n\nFor arrays start with the most significant field and work your way down.\n\n# 4. CLASSES AND INTERFACES\n\n## 13. Minimize the accessibility of classes and members\n\n**Encapsulation**:\n\n- A well designed module hides all of its implementation details.\n- Separates its API from its implementation.\n- Decouples modules that comprise a system, allowing them to be isolated while:\n  - developed (can be developed in parallel)\n  - tested (individual modules may prove succesful even if the system does not)\n  - optimized and modified (no harm to other modules)\n  - understood (dont need other modules to be understood)\n  - used\n\n**Make each class or member as inaccesible as possible**\n\nIf a package-private top level class is used by only one class make it a private nested class of the class that uses it. ([Item 22](#22-favor-static-member-classes-over-nonstatic))\n\nIt is acceptable to make a private member of a public class package-private in order to test it.\n\n**Instance fields should never be public** ([Item 14](#14-in-public-classes-use-accessor-methods-not-public-fields)) Class will not be thread-safe.\n\nStatic 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.\n\nNonzero-length array is always mutable.\n\n```java\n\n\t//Potential security hole!\n\tpublic static final Thing[] VALUES = {...}\n```\n\nSolution:\n\n```java\n\n\tprivate static final Thing[] PRIVATE_VALUES ={...}\n\tpublic static final List\u003cThing\u003e VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));\n```\n\nOr:\n\n```java\n\n\tprivate static final Thing[] PRIVATE_VALUES ={...}\n\tpublic static final Thing[] values(){\n\t\treturn PRIVATE_VALUES.clone;\n\t}\n```\n\n## 14. In public classes, use accessor methods, not public fields\n\nDegenerate classes should not be public\n\n```java\n\n\tclass Point {\n\t\tpublic double x;\n\t\tpublic double y;\n\t}\n```\n\n- They don't benefit from _encapsulation_ ([Item 13](#13-minimize-the-accessibility-of-classes-and-members))\n\n- Can't change representation without changing the API.\n\n- Can't enforce invariants.\n\n- Can't take auxiliary actions when a field is accessed.\n\nReplace them with _accessor methods_ (getters) and _mutators_ (setters).\n\n```java\n\n\tclass Point {\n\t\tprivate double x;\n\t\tprivate double y;\n\n\t\tpublic Point(double x, double y){\n\t\t\tthis.x = x;\n\t\t\tthis.y = y;\n\t\t}\n\n\t\tpublic double getX() { return x; }\n\t\tpublic double getY() { return y; }\n\n\t\tpublic void setX(double x) { this.x = x; }\n\t\tpublic void setY(double y) { this.y = y; }\n\t}\n```\n\nIf a class is accessed **outside its package**, provide **accesor methods**.\n\nIf a class is **package-private or is a private nested class**, its **ok to expose** its data fields.\n\nIn **public classes** it is a questionable option to **expose immutable fields**.\n\n## 15. Minimize Mutability\n\nAll the information of the instance is provided when it is created.\nThey are easier to design, implement and use. And they are less prone to errors and more secure\n\n- Don't provide any methods that modify the object's state (no mutators)\n- Ensure that the class can't be extended\n- Make all fields final\n- Make all fields private\n- Ensure exclusive access to any mutable component\n\n```java\n\n\tpublic final class Complex {\n\t\tprivate final double re;\n\t\tprivate final double im;\n\n\t\tpublic Complex (double re, double im) {\n\t\t\tthis.re = re;\n\t\t\tthis.im = im;\n\t\t}\n\n\t\t// Accessors with no corresponding mutators\n\t\tpublic double realPart() { return re;}\n\t\tpublic double imaginaryPart() { return im;}\n\n\t\tpublic Complex add(Complex c){\n\t\t\treturn new Complex(re + c.re, im + c.im);\n\t\t}\n\n\t\tpublic Complex subtract(Complex c){\n\t\t\treturn new Complex(re - c.re, im - c.im);\n\t\t}\n\n\t\t...\n\n\t\t@Override public boolean equals (Object o){...}\n\t}\n\n```\n\nThe arithmetic operation **create and return a new instance**. (Functional approach)\n\nImmutable objects are simple. They only have one state for their lifetime.\n\nImmutable objects are thread-safe. Synchronization is not required. They can be shared freely and can reuse existing instances.\n\n```java\n\n\tpublic static final Complex ZERO = new Complex(0,0)\n\tpublic static final Complex ONE = new Complex(1,0)\n\tpublic static final Complex I = new Complex(0,1)\n```\n\nUsing static factories can create constants of frequently requested instances and serve them in future requests.\n\nInternals of the immutable objects can also be shared.\n\nThey make great building blocks for other objects.\n\nThe disadvantage is that a separate object is required for distinct values. In some cases it could create a performance problem.\n\n**How to deny subclassing in immutable objects**\n\n1. Making it final\n\n2. Make all of its constructors private or package-private and add a public static factory\n\n```java\n\n\tpublic class Complex {\n\t\tprivate final double re;\n\t\tprivate final double im;\n\n\t\tprivate Complex (double re, double im){\n\t\t\tthis.re = re;\n\t\t\tthis.im = im;\n\t\t}\n\n\t\tpublic static Complex valueOf(double re, double im){\n\t\t\treturn new Complex(re,im);\n\t\t}\n\n\t\t...\n\t}\n```\n\nThis 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.\n\n**Summary**\n\nClasses should be immutable unless there are good reasons to make them mutable.\n\nIf a class can not be immutable, limit its mutability as much as possible.\n\nMake every field final unless there is a good reason not to do it.\n\nSome of the rules can be relaxed to improve performance (caching, lazy initialization...).\n\n## 16. Favor composition over inheritance\n\nInheritance in this case is when a class extends another (_implementation inheritance_) Not interface inheritance.\n\n**Inheritance violates encapsulation**\n\nFragility causes\n\n1. A subclass depends on the implementation details of its superclass. If the superclass change the subclass may break.\n\n2. The superclass can aquire new methods in new releases that might not be added in the subclass.\n\n**Composition**\n\nInstead of extending, give your new class a private field that references an instance of the existing class.\n\nEach 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.\n\n**Wrapper (Decorator Pattern)**\n\n```java\n\n\t// Wrapper class - uses composition in place of inheritance\n\tpublic class InstrumentedSet\u003cE\u003e extends ForwardingSet\u003cE\u003e {\n\t\tprivate int addCount = 0;\n\t\t//It extends a class(inheritance),but it is a forwarding class that is actually a compositon of the Set\n\t\t(specifically a forwarding class), not the Set itself.\n\t\tpublic InstrumentedSet (Set\u003cE\u003e s){\n\t\t\tsuper(s)\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean add(E e){\n\t\t\taddCount++;\n\t\t\treturn super.add(e);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean addAll (Collection\u003c ? extends E\u003e c){\n\t\t\taddCount += c.size();\n\t\t\treturn super.addAll(c);\n\t\t}\n\n\t\tpublic int getAddCount() {\n\t\t\treturn addCount;\n\t\t}\n\t}\n```\n\n```java\n\n\t// Reusable forwarding class\n\tpublic class ForwardingSet\u003cE\u003e implements Set\u003cE\u003e {\n\t\tprivate final Set\u003cE\u003e s; // Here is the composition. It uses the Set but not extends it.\n\t\tpublic ForwardingSet(Set\u003cE\u003e s) { this.s = s ; }\n\n\t\t// It implemets the Set, using the interface, and create the forwarding methods.\n\t\tpublic void clear() {s.clear();}\n\t\tpublic boolean contains(Object o) { return s.contains(o)}\n\t\t...\n\t\tpublic boolean add(E e) { return s.add(e)}\n\t\tpublic boolean addAll (Collection\u003c ? extends E\u003e c){return s.addAll(c)}\n\t\t...\n\t}\n\n```\n\n## 17. Design and document for inheritance or else prohibit it.\n\nThe class must document its _self-use_ of overridable methods.\n\nMethods and constructors should document which _overridable_ methods or constructors (nonfinal, and public or protected ) invokes. The description begins with the phrase \"This implementation.\"\n\nTo document a class so that it can be safely subclassed, you must describe implementations details.\n\nTo 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.\n\n**Test the class for subclassing**. The only way to test a class designed for inheritance is to write subclasses.\n\nConstructors must not invoke overridable methods. For _Serializable_ and _Cloneable_ implementations neither _clone_ nor _readObject_ may invoke overridable methods.\n\nProhibit subclassing in classes that are not designed and documented to be safely subclassed. 2 options:\n\n- Declare the class final\n- Make all constructors private or package-private and add public static factories in place of the constructors.\n  ([Item 15](#15-minimize-mutability))\n\nConsider using [Item 16](#16-favor-composition-over-inheritance) if what you want is to increase the functionality of your class instead of subclassing.\n\n## 18. Prefer interfaces to abstract classes\n\nJava permits only single Inheritance, this restriction on abstract classes severely contrains their use as type functions.\n\nInteface is generally the best way to define a type that permits multiple implementations.\n\nExisting classes can be easily retro-fitted to implement a new interface.\n\nInterfaces 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)\n\nInterfaces allow the construction of nonhierarchical type frameworks.\n\nInterfaces enable safe, powerful functionality enhancements (Wrapper class. [Item 16](#16-favor-composition-over-inheritance))\n\nCombine the virtues of interfaces and abstract classes, by providing an abstract **skeletal implementation** class to go with each **nontrivial interface** that you export.\n\n```java\n\n\t//Concrete implementation built atop skeletal implementation\n\tstatic List\u003cInteger\u003e intArrayAsList(final int[] a) {\n\t\tif (a == null) throw new NullPointerException();\n\n\n\t\t// From the documentation\n\t\t//This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a \"random access\" data store (such as an array)\n\t\t//To implement an unmodifiable list, the programmer needs only to extend this class and provide implementations for the get(int) and size() methods.\n\t\t//To implement a modifiable list, the programmer must additionally override the set(int, E)\n\n\t\treturn new AbstractList\u003cInteger\u003e(){\n\t\t\tpublic Integer get (int i){\n\t\t\t\treturn a[i]; // Autoboxing (Item 5)\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Integer set(int i, Integer val){\n\t\t\t\tint oldVal = a[i];\n\t\t\t\ta[i] = val;\t\t// Auto-unboxing\n\t\t\t\treturn oldVal;\t// Autoboxing\n\t\t\t}\n\n\t\t\tpublic int size(){\n\t\t\t\treturn a.length;\n\t\t\t}\n\t\t}\n\t}\n```\n\nSkeletal implementations are designed for inheritance so follow [Item 17](#17-design-and-document-for-inheritance-or-else-prohibit-it) guidelines.\n\n_simple implementation_ is like a skeletal implementation in that it implements the simplest possible working implementation.\n\nCons: 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.\n\n## 19. Use interfaces only to define types\n\nWhen a class implements an interface, the interface serves as a _type_ that can be used to refer to instances of the class.\n\nAny other use, like the _constant interface_ should be avoided.\n\n```java\n\n\t// Constant interface antipattern\n\tpublic interface PhysicalConstants {\n\t\tstatic final double AVOGRADOS_NUMBER = 6.02214199e23;\n\t\tstatic final double BOLTZAN_CONSTANT = 1.3806503e-23;\n\t\tstatic final double ELECTRON_MASS = 9.10938188e-31;\n\t}\n```\n\nBetter use an enum type ([Item 31](#31-use-instance-fields-instead-of-ordinals)), or a noninstantiable _utility class_ ([Item 4](#4-enforce-noninstantiability-with-a-private-constructor))\n\n```java\n\n\t//Constant utility class\n\tpackage com.effectivejava.science\n\n\tpublic class PhysicalConstants{\n\t\tprivate PhysicalConstants(){} // Prevents instantiation\n\n\t\tpublic static final double AVOGRADOS_NUMBER = 6.02214199e23;\n\t\tpublic static final double BOLTZAN_CONSTANT = 1.3806503e-23;\n\t\tpublic static final double ELECTRON_MASS = 9.10938188e-31;\n\t}\n```\n\nTo avoid the need of qualifying use _static import_.\n\n```java\n\n\t//Use of static import to avoid qualifying constants\n\timport static com.effectivejava.science.PhysicalConstants.*\n\n\tpublic class Test {\n\t\tdouble atoms(double mols){\n\t\t\treturn AVOGRADOS_NUMBER * mols;\n\t\t}\n\t\t...\n\t\t// Many more uses of PhysicalConstants justify the static import\n\t}\n```\n\n## 20. Prefer class hierarchies to tagged classes\n\nTagged classes are verbose, error-prone and inefficient.\n\nThey have lot of boilerplate, bad readability, increase memory footprint, and more shortcommings.\n\n```java\n\n\t// Tagged Class\n\tclass Figure{\n\t\tenum Shaple {RECTANGLE, CIRCLE};\n\n\t\tfinal Shape shape;\n\n\t\t// Rectangle fields\n\t\tdouble length;\n\t\tdouble width;\n\n\t\t//Circle field\n\t\tdouble radius;\n\n\t\t// Circle Constructor\n\t\tFigure (double radius) {\n\t\t\tshape = Shape.CIRCLE;\n\t\t\tthis.radius=radius;\n\t\t}\n\n\t\t// Rectangle Constructor\n\t\tFigure (double length, double width) {\n\t\t\tshape = Shape.RECTANGLE;\n\t\t\tthis.length=length;\n\t\t\tthis.width=width;\n\t\t}\n\n\t\tdouble area(){\n\t\t\tswitch(shape){\n\t\t\t\tcase RECTANGLE:\n\t\t\t\t\treturn length*width;\n\t\t\t\tcase CIRCLE\n\t\t\t\t\treturn Math.PI * (radius * radius);\n\t\t\t\tdefalult\n\t\t\t\t\tthrow new AssertionError();\n\t\t\t}\n\t\t}\n\t}\n```\n\nA tagged class is just a palid imitation of a class hierarchy.\n\n- The code is simple and clear.\n- The specific implementations are in its own class\n- All fields are final\n- The compiler ensures that each class's constructor initializes its data fields.\n- Extendability and flexibility (Square extends Rectangle)\n\n```java\n\n\tabstract class Figure{\n\t\tabstract double area();\n\t}\n\tclass Circle extends Figure{\n\t\tfinal double radius;\n\n\t\tCircle(double radius) { this.radius=radius;}\n\n\t\tdouble area(){return Math.PI * (radius * radius);}\n\t}\n\tclass Rectangle extends Figure{\n\t\tfinal double length;\n\t\tfinal double width;\n\n\t\tRectangle (double length, double width) {\n\t\t\tthis.length=length;\n\t\t\tthis.width=width;\n\t\t}\n\n\t\tdouble area(){return length*width;}\n\t}\n\n\tclass Square extends Rectangle {\n\t\tSquare(double side){\n\t\t\tsuper(side,side);\n\t\t}\n\t}\n```\n\n## 21. Use function objects to represent strategies\n\nStrategies are facilities that allow programs to store and transmit the ability to invoke a particular function. Similar to _function pointers_, _delegates_ or _lambda expression_.\n\nIt is possible to define a object whose method perform operations on other objects.\n\n**Concrete strategy**\n\n```java\n\n\tclass StringLengthComparator{\n\t\tpublic int compare(String s1, String s2){\n\t\t\treturn s1.length() - s2.length();\n\t\t}\n\t}\n```\n\nConcrete strategies are typically _stateless_ threfore they should be singletons.\n\nTo be able to pass different strategies, clients should invoke methods from a _strategy interface_ instead of a concrete class.\n\n**Comparator interface.** _Generic_([Item 26](#26-favor-generic-types))\n\n```java\n\n\tpublic interface Comparator\u003cT\u003e{\n\t\tpublic int compare(T t1, T t2);\n\t}\n```\n\n```java\n\n\tclass StringLengthComparator implements Comparator\u003cString\u003e{\n\t\tprivate StringLengthComparator(){} // Private constructor\n\t\tpublic static final StringLengthComparator INSTANCE = new StringLengthComparator(); // Singleton instance\n\t\tpublic int compare(String s1, String s2){\n\t\t\treturn s1.length() - s2.length();\n\t\t}\n\t}\n```\n\nUsing **anonymous classes**\n\n```java\n\n\tArrays.sort(stringArray, new Comparator\u003cString\u003e(){\n\t\tpublic int compare(String s1, String s2){\n\t\t\treturn s1.length() - s2.length();\n\t\t}\n\t})\n```\n\nAn anonymous class will create a new instance each time the call is executed. Consider a private static final field and reusing it.\n\nConcrete strategy class don't need to be public, because the strategy interface serve as a type.\nA 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.\n\n```java\n\n\t// Exporting a concrete strategy\n\tclass Host{\n\t\tprivate static class StringLengthComparator implements Comparator\u003cString\u003e, Serializable {\n\t\t\tpublic int compare(String s1, String s2){\n\t\t\t\treturn s1.length() - s2.length();\n\t\t\t}\n\t\t}\n\n\t\t//Returned comparator is serializable\n\t\tpublic static final Comparator\u003cString\u003e STRING_LEGTH_COMPARATOR = new StringLengthComparator();\n\n\t\t...\n\t}\n```\n\n## 22. Favor static member classes over nonstatic\n\n4 types of nested classes.\n\n1. static\n2. nonstatic\n3. anonymous\n4. local\n\n**Static**, a member class that does not require access to an enclosing instance must be _static_.\n\nStoring references cost time, space and can cost not wanted behaviors of the garbage collector([Item 6](#6-eliminate-obsolete-object-references))\n\nCommon use of static member class is a public helper in conjuctions with its outer class. A nested class enum _Operation_ in _Calculator_ class. `Calculator.Operation.PLUS`;\n\n**Nonstatic** member class instances are required to have an enclosing instance.\n\n**Anonymous** classes are used to create _function objects_ on the fly. ([Item 21](#21-use-function-objects-to-represent-strategies))\n\n**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).\n\nAnonymous class, from the official docs: Use it if you need to declare fields or additional methods.\n\n# 5. GENERICS\n\n## 23. Don't use raw types in new code\n\nGeneric classes and interfaces are the ones who have one or more _type parameter_ as _generic_, i.e. `List\u003cE\u003e`\n\nEach generic type defines a set of _parametrized types_ `List\u003cString\u003e`\n\n_Raw types_ is the generic type definition without type parameters. `List`\n\n```java\n\n\tprivate final List stamps = ...\n\n\tstamps.add(new Coin(...)); //Erroneous insertion. Does not throw any error\n\n\tStamp s = (Stamp) stamps.get(i); // Throws ClassCastException when getting the Coin\n```\n\n```java\n\n\tprivate final Collection\u003cStamp\u003e stamps = ...\n\n\tstamps.add(new Coin()); // Compile time error. Coin can not be add to Collection\u003cStamp\u003e\n\n\tStamp s = stamps.get(i); // No need casting\n```\n\nUse of raw types lose safety and expressiveness of generics.\n\nType safety is kept in a parametrized type like `List\u003cObject\u003e` but not in raw types (`List`).\n\nThere are subtyping rules for generics. For example `List\u003cString\u003e` is a subtype of `List` but not of `List\u003cObject\u003e` ([Item 25](#25-prefer-lists-to-arrays))\n\n**Unbounded Wildcard Types `Set\u003c?\u003e`**\nUsed when a generic type is needed but we don't know or care about the actual type.\n\nNever add elements (other than null) into a `Collection\u003c?\u003e`\n\n2 exceptions (because generic type information is erased at runtime):\n\n- Use raw types in class literals `List.class`,`String[].class` are legal, `List\u003cString\u003e.class`, `List\u003c?\u003e.class` are not.\n- Use of instanceof\n\n```java\n\n\tif (o instanceof Set){\n\t\tSet\u003c?\u003e = (Set\u003c?\u003e) o;\n\t}\n```\n\n| **Term**                | **Example**                        | **Item** |\n| ----------------------- | ---------------------------------- | -------- |\n| Parametrized type       | `List\u003cString\u003e`                     | 23       |\n| Actual type parameter   | `String`                           | 23       |\n| Generic type            | `List\u003cE\u003e`                          | 23, 26   |\n| Formal type parameter   | `E`                                | 23       |\n| Unbounded wildcard type | `List\u003c?\u003e`                          | 23       |\n| Raw type                | `List`                             | 23       |\n| Bounded type parameter  | `\u003cE extends Number\u003e`               | 26       |\n| Recursive type bound    | `\u003cT extends Comparable\u003cT\u003e\u003e`        | 27       |\n| Bounded wildcard type   | `List\u003c? extends Number\u003e`           | 28       |\n| Generic method          | `static \u003cE\u003e List\u003cE\u003e asList(E[] a)` | 27       |\n| Type token              | `String.class`                     | 29       |\n\n## 24. Eliminate unchecked warnings\n\nEliminate every unchecked warning that you can, if you can´t use _Suppress-Warnings_ annotation on the smallest scope possible.\n\n```java\n\n\tSet\u003cLark\u003e exaltation = new HashSet(); Warning, unchecked conversion found.\n\tSet\u003cLark\u003e exaltation = new HashSet\u003cLark\u003e(); Good\n```\n\n## 25. Prefer lists to arrays\n\nArrays are _covariant_: if `Sub` is a subtype of `Super`, `Sub[]` is a subtype of `Super[]`  \nGenerics are _invariant_: for any two types `Type1` and `Type2`, `List\u003cType1\u003e` in neither sub or super type of `List\u003cType2\u003e`\n\n```java\n\n\t// Fails at runtime\n\tObject[] objectArray = new Long[1];\n\tobjectArray[0] =\"I don't fit in\" // Throws ArrayStoreException\n\n\t// Won't compile\n\tList\u003cObject\u003e ol = new ArrayList\u003cLong\u003e();//Incompatible types\n\tol.add(\"I don't fit in\")\n```\n\nArrays are _reified_: Arrays know and enforce their element types at runtime.\nGenerics are _erasure_: Enforce their type constrains only at compile time and discard (or _erase_) their element type information at runtime.\n\nTherefore it is illegal to create an array of a generic type, a parameterized type or a type parameter.\n\n`new List\u003cE\u003e[]`, `new List\u003cString\u003e[]`, `new E[]` will result in _generic array creation_ errors.\n\n## 26. Favor generic types\n\nMaking [Item 6](#6-eliminate-obsolete-object-references) to use generics.\n\n```java\n\n\tpublic class Stack{\n\t\tprivate E[] elements;\n\t\tprivate int size = 0;\n\t\tprivate static final int DEFAULT_INITIAL_CAPACITY = 16;\n\n\t\tpublic Stack(){\n\t\t\telements = new E [DEFAULT_INITIAL_CAPACITY];//Error: Can't create an array of a non-reifiable type.\n\t\t}\n\n\t\tpublic void push(E e){\n\t\t\tensureCapacity();\n\t\t\telements[size++] = e;\n\t\t}\n\n\t\tpublic E pop(){\n\t\t\tif (size == 0)\n\t\t\t\tthrow new EmptyStackException();\n\t\t\tE result = elements[--size];\n\t\t\telements[size] = null;\n\t\t\treturn result;\n\t\t}\n\t\t...\n\t}\n```\n\nThere will be one error:\n\n```java\n\n\t//Error: Generic array creation. Can't create an array of a non-reifiable type.\n\telements = new E [DEFAULT_INITIAL_CAPACITY];\n```\n\n**First option** (more commonly used.)\n\n```java\n\n\t// Warning: Compiler can not prove the type safe, but we can.\n\t// This elements array will contain only E instances from push(E).\n\t// This is sufficient to ensure type safety, but the runtime\n\t// type of the array won't be E[]; it will always be Object[]!\n\t@SupressWarnings(\"unchecked\")\n\tpublic Stack(){\n\t\telements = (E[]) new Object [DEFAULT_INITIAL_CAPACITY];\n\t}\n```\n\n**Second Option**\n\n```java\n\n\t...\n\tprivate Object[] elements;\n\t...\n\tresult = elements[--size] // Error: found Object, required E\n```\n\nA cast will generate a warning. Beacuse E is a non-reifiable type, there is no way the compiler can check the cast at runtime.\n\n```java\n\n\tresult = (E) elements[--size]\n```\n\nThe appropriate suppression of the unchecked warning\n\n```java\n\n\tpublic E pop(){\n\t\tif (size == 0)\n\t\t\tthrow new EmptyStackException();\n\n\t\t// push requires elements to be of type E, so cast is correct.\n\t\t@SupressWarnings(\"unchecked\") E result = elements[--size];\n\n\t\telements[size] = null;\n\t\treturn result;\n\t}\n```\n\n## 27. Favor generic Methods\n\nGeneric Method\n\n```java\n\n\t//\n\tpublic static \u003cE\u003e Set\u003cE\u003e union(Set\u003cE\u003e s1, Set\u003cE\u003e s2){\n\t\tSet\u003cE\u003e result = new HashSet\u003cE\u003e(s1);\n\t\tresult.addAll(s2);\n\t\treturn result;\n\t}\n```\n\n**Type inference**: Compiler knows because of `Set\u003cString\u003e` that `E` is a _String_\n\nIn generic constructors the type parameters have to be on both sides of the declaration. (Java 1.7 might have fix it)\n\n```java\n\n\tMap\u003cString,List\u003cString\u003e\u003e anagrams = new HashMap\u003cString, List\u003cString\u003e\u003e();\n```\n\nTo avoid ic create a _generic static factory method_\n\n```java\n\n\tpublic static \u003cK,V\u003e HashMap\u003cK,V\u003e newHashMap(){\n\t\treturn new HashMap\u003cK,V\u003e();\n\t}\n\n\t//Use\n\tMap\u003cString,List\u003cString\u003e\u003e anagrams = newHashMap();\n\n\n```\n\n**Generic Singleton Pattern** Create an object that is immutable but applicable to many different types.\n\n```java\n\n\tpublic interface UnaryFunction\u003cT\u003e{\n\t\tT apply(T arg);\n\t}\n\n\t// Generic singleton factory pattern\n\tprivate static UnaryFunction\u003cObject\u003e IDENTITY_FUNCTION = new UnaryFunction\u003cObject\u003e(){\n\t\tpublic Object apply(Object arg) {return arg;}\n\t};\n\n\t//IDENTITY_FUNCTION is stateless and its type parameter is unbounded so it's safe to share one instance across all types.\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static\u003cT\u003e UnaryFunction\u003cT\u003e identityFunction(){\n\t\treturn(UnaryFunction\u003cT\u003e) IDENTITY_FUNCTION;\n\t}\n```\n\n**Recursive Type Bound** : When the type paremeter is bounded by some expression involving that type parameter itself.\n\n```java\n\n\tpublic static\u003cT extends Comparable\u003cT\u003e\u003e T max (List\u003cT\u003e list){\n\t\tIterator \u003cT\u003e i = list.iterator():\n\t\tT result = i.next();\n\t\twhile (i.hasNext()) {\n\t\t\tT t = i.next();\n\t\t\tif(t.compareTo(result) \u003e 0)\n\t\t\t\tresult = t;\n\t\t}\n\t\treturn result;\n\t}\n```\n\n## 28. Use bounded wildcards to increase API flexibility\n\nParameterized types are invariant.([Item 25](#25-prefer-lists-to-arrays)) Ie `List\u003cString\u003e` is not a subtype of `List\u003cObject\u003e`\n\n```java\n\n\tpublic void pushAll(Iterable\u003cE\u003e src){\n\t\tfor(E e : src)\n\t\t\tpuhs(e)\n\t}\n\n\t// Integer is a subtype of Number\n\tStack\u003cNumber\u003e numberStack = new Stack\u003cNumber\u003e();\n\tIterable\u003cInteger\u003e integers = ...\n\tnumberStack.pushAll(integers); //Error message here: List\u003cInteger\u003e is not a subtype of List\u003cNumber\u003e\n```\n\n**Bounded wildcard type**\n\nProducer\n\n```java\n\n\tpublic void pushAll(Iterable\u003c? Extends E\u003e src){\n\t\tfor (E e : src)\n\t\t\tpush(e);\n\t}\n```\n\nConsumer\n\n```java\n\n\tpublic void popAll(Collection\u003c? super E\u003e dst){\n\t\twhile(!isEmpty())\n\t\t\tdst.add(pop());\n\t}\n```\n\n**PECS: producer-extends, consumer-super**\n\nIf the parameter is a producer and a conusmer don't use _wildcards_\n\nNever use _wildcards_ in return values.\n\nType inference in generics\n\n```java\n\n\tSet\u003cInteger\u003e integers =...\n\tSet\u003cDouble\u003e doubles =...\n\tSet\u003cNumber\u003e numbers = union(integers,doubles);//Error\n\n\t//Needs a 'explicit type parameter'\n\tSet\u003cNumber\u003e numbers = Union.\u003cNumber\u003eunion(integers,doubles);\n```\n\nComparable and Comparators are always consumers. Use `Comparable\u003c? super T\u003e` and `Comparator\u003c? super T\u003e`\n\nIf a type parameter appears only once in a method declaration, replace it with a wildcard.\n\n## 29. Consider _typesafe heterogeneous containers_\n\nA container for accessing a heterogeneous list of types in a typesafe way.\n\nThanks to the type of the class literal. `Class\u003cT\u003e`\n\n**API**\n\n```java\n\n\tpublic class Favorites{\n\t\tpublic void putFavorites(Class\u003cT\u003e type, T instance);\n\t\tpublic \u003cT\u003e getFavorite(Class\u003cT\u003e type);\n\t}\n```\n\n**Client**\n\n```java\n\n\tFavorites f = new Favorites();\n\tf.putFavorites(String.class, \"JAVA\");\n\tf.putFavorites(Integer.class, 0xcafecace);\n\tf.putFavorites(Class.class, Favorite.class);\n\n\tString s = f.getFavorites(String.class);\n\tint i =f.getFavorites(Integer.class);\n\tClass\u003c?\u003e c = f.getFavorites(Class.class);\n```\n\n**Implementation**\n\n```java\n\n\tpublic class Favorites{\n\t\tprivate Map\u003cClass\u003c?\u003e, Object\u003e favorites = new HashMap\u003cClass\u003c?\u003e, Object\u003e();\n\n\t\tpublic \u003cT\u003e void putFavorites(Class\u003cT\u003e type, T instance){\n\t\t\tif(type == null)\n\t\t\t\tthrow new NullPointerException(\"Type is null\");\n\t\t\tfavorites.put(type, type.cast(instance));//runtime safety with a dynamic cast\n\t\t}\n\n\t\tpublic \u003cT\u003e getFavorite(Class\u003cT\u003e type){\n\t\t\treturn type.cast(favorites.get(type));\n\t\t}\n\t}\n```\n\n# 6. ENUMS AND ANNOTATIONS\n\n## 30. Use enums instead of _int_ constants\n\nEnums are classes that export one instance for each enumeration constant via a public static final field.\nClients can not create instances or extend them.\nThey are a generalization of singletons([Item 3](#3-enforce-the-singleton-property-with-a-private-constructor-or-an-enum-type))\nThey are compile-time type safe.\n\n**Enums can have data associated**\n\n```java\n\n\tpublic enum Planet{\n\t\tMERCURY(3.334e+23,2.234e6)\n\t\tVENUS(4.234e+23,6.636e6)\n\t\tEARTH(5.865e+23,6.256e6)\n\t\t...\n\n\t\tprivate final double mass;\n\t\tprivate final double radius;\n\t\tprivate final double surfaceGravity;\n\n\t\tprivate static final double G = 6.67300E-11;\n\n\t\tPlanet(double mass, double radius){\n\t\t\tthis.mass = mass;\n\t\t\tthis.radius = radius;\n\t\t\tsurfaceGravity = G * mass/(radius * radius);\n\t\t}\n\n\t\tpublic double mass() {return mass;}\n\t\tpublic double radius() {return radius;}\n\t\tpublic double surfaceGravity() {return surfaceGravity;}\n\n\t\tpublic double surfaceWeight(double mass){\n\t\t\treturn mass * surfaceGravity;\n\t\t}\n\t}\n```\n\nEnums are immutable so their fields should be final([Item 15](#15-minimize-mutability))\nMake fields private ([Item 14](#14-in-public-classes-use-accessor-methods-not-public-fields))\n\nEnums should be a member class inside a top-level class if it is not generally used.\n\n**Enum type with constant-specific method implementations**\n\n```java\n\n\tpublic enum Operation{\n\t\tPLUS { double apply(double x, double y){return x + y;}},\n\t\tMINUS { double apply(double x, double y){return x - y;}},\n\t\tTIMES { double apply(double x, double y){return x * y;}},\n\t\tDIVIDE { double apply(double x, double y){return x / y;}};\n\n \t\t// The abstract method force us not to forget to implement the method.\n\t\tabstract double apply(double x, double y);\n\n\t}\n```\n\n**Strategy enum pattern**\nUse it, if multiple enum constants share common behaviors.\n\n```java\n\n\tenum PayrollDay{\n\t\tMONDAY(PayType.WEEKDAY),\n\t\tTUESDAY(PayType.WEEKDAY),\n\t\t...\n\t\tSATURDAY(PayType.WEEKEND),\n\t\tSUNDAY(PayType.WEEKEND);\n\n\t\tprivate final PayType payType;\n\n\t\tPayrollDay(PayType payType) {this.payType = payType;}\n\n\t\tdouble pay(double hoursWorked, double payRate){\n\t\t\treturn payType.pay(hoursWorked, payRate);\n\t\t}\n\t\t//The strategy  enum type\n\t\tprivate enum PayType{\n\t\t\tWEEKDAY{\n\t\t\t\tdouble overtimePay(double hours, double payRate) { return ...}\n\t\t\t};\n\t\t\tWEEKEND{\n\t\t\t\tdouble overtimePay(double hours, double payRate) { return ...}\n\t\t\t};\n\t\t\tprivate static final int HOURS_PER_SHIFT = 8;\n\n\t\t\tabstract double overtimePay(double hours, double payRate);\n\n\t\t\tdouble pay(double hoursWorked, double payRate){\n\t\t\t\tdouble basePay = hoursWorked * payRate;\n\t\t\t\treturn basePay + overtimePay(hoursWorked, payRate);\n\t\t\t}\n\t\t}\n\t}\n```\n\n## 31. Use instance fields instead of ordinals\n\nNever derive a value of an enum to its ordinal\n\n```java\n\n\tpublic enum Ensemble{\n\t\tSOLO, DUET, TRIO...;\n\t\tpublic int numberOfMusicians() {return ordinal() + 1}\n\t}\n```\n\nBetter approach\n\n```java\n\n\tpublic enum Ensemble{\n\t\tSOLO(1), DUET(2), TRIO(3)...TRIPLE_QUARTET(12);\n\t\tprivate final int numberOfMusicians;\n\t\tEnsemble(int size) {this.numberOfMusicians = size;}\n\t\tpublic int numberOfMusicians() {return numberOfMusicians;}\n\t}\n```\n\n## 32. Use EnumSet instead of bit fields\n\nIf the elements of an enumarated are used primarily in sets, use EnumSet.\n\n```java\n\n\tpublic class Text{\n\t\tpublic enum Style { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH }\n\n\t\t//Any Set could be passed. Best EnumSet\n\t\tpublic void applyStyles(Set\u003cStyle\u003e styles){ ... }\n\t}\n\n\t//Use\n\ttext.applyStyles(EnumSet.of(Style.BOLD, Style. ITALIC));\n```\n\nIt is a good practice to accept the interface `Set` instead of the implementation `\tEnumSet`.\n\n## 33. Use EnumMap instead of ordinal indexing\n\nUse EnumMap to associate data with an enum\n\n```java\n\n\tMap\u003cHerb.Type, Set\u003cHerb\u003e\u003e herbsByType = new EnumMap\u003cHerb.Type, Set\u003cHerb\u003e\u003e(Herb.Type.class);\n\n\tfor (Herb.Type t : Herb.Type.values())\n\t\therbsByType.put(t, new HashSet\u003cHerb\u003e())\n\n\tfor (Herb h : garden)\n\t\therbsByType.get(h.type).add(h);\n\n\tSystem.out.println(herbsByType);\n\n```\n\nIn case you need a multidimensional relationship use `EnumMap\u003c..., EnumMap\u003c...\u003e\u003e`\n\n## 34. Emulate extensible enums with interfaces\n\nEnums types can not extend another enum types.\n\n_Opcodes_ as a use case of enums extensibility.\n\n```java\n\n\tpublic interface Operation{\n\t\tdouble apply(double x, double y);\n\t}\n\tpublic enum BasicOperation implements Operation{\n\t\tPLUS(\"+\"){\n\t\t\tpublic double apply(double x, double y) {return x + y}\n\t\t},\n\t\tMINUS(\"-\"){...},TIMES(\"*\"){...},DIVIDE(\"/\"){...};\n\n\t\tprivate final String symbol;\n\t\tBasicOperation(String symbol){\n\t\t\tthis.symbol = symbol;\n\t\t}\n\t\t@Override\n\t\tpublic String toString(){ return symbol; }\n\t}\n```\n\n_BasicOperation_ is not extensible, but the interface type _Operation_ is, and it is the one used to represent operations in APIs.\n\n**Emulated extension type**\n\n```java\n\n\tpublic enum ExtendedOperation implements Operation{\n\t\tEXP(\"^\"){\n\t\t\tpublic double apply(double x, double y) {return Math.pow(x,y)}\n\t\t}\n\t\tREMAINDER(\"%\"){\n\t\t\tpublic double apply(double x, double y) {return x % y}\n\t\t}\n\n\t\tprivate final String symbol;\n\t\tExtendedOperation(String symbol){\n\t\t\tthis.symbol = symbol;\n\t\t}\n\t\t@Override\n\t\tpublic String toString(){ return symbol; }\n\t}\n```\n\n## 35. Prefer annotations to naming patterns\n\nSample of the _@Test_ annotation\n\n**Marker**\n\n```java\n\n\t//Marker annotation type declaration\n\timport java.lang.annotation.*;\n\n\t//Indicates that the annotated method is a test method.\n\t//Use only on parameterless static methods.\n\t@Retention(RetentionPolicy.RUNTIME)\n\t@Target(ElementType.METHOD)\n\tpublic @interface Test {\n\t}\n```\n\n`@Retention` and `@Target` are _meta-annotations_\n\n`@Retention(RetentionPolicy.RUNTIME)`: indicates that the Test annotation should be retained at runtime.(It makes them visible to the test tool)\n\n`@Target(ElementType.METHOD)`indicates that is legal only on method declarations. Not in class, fields or other programs declarations\n\n**Retention RetentionPolicies**\n\n| Enum    | Description                              |\n| :------ | :--------------------------------------- |\n| CLASS   | Retain only at compile time, not runtime |\n| RUNTIME | Retain at compile and also runtime       |\n| SOURCE  | Discard by the compiler                  |\n\n**Target ElementTypes**\n\n| Enum            | Valid on...                                        |\n| :-------------- | :------------------------------------------------- |\n| ANNOTATION_TYPE | Annotation type declaration                        |\n| CONSTRUCTOR     | constructors                                       |\n| FIELD           | the field (includes also enum constants)           |\n| LOCAL_VARIABLE  | local variables                                    |\n| METHOD          | methods                                            |\n| PACKAGE         | packages                                           |\n| PARAMETER       | parameter declaration                              |\n| TYPE            | class, interface, annotation and enums declaration |\n| TYPE_PARAMETER  | type parameter declarations                        |\n| TYPE_USE        | the use of a specific type                         |\n\n**Use**\n\n```java\n\n\tpublic class Sample{\n\t\t@Test public static void m1(){}\t\t// Test pass\n\t\tpublic static void m2(){} \t\t\t// Not test applied\n\t\t@Test public static void m3(){ \t\t// Test fail\n\t\t\tthrow new RuntimeException(\"Boom\")\n\t\t}\n\t\t@Test public void m4(){}\t\t\t// Invalid use. Non static method.\n\t}\n```\n\n**Process annotations**\n\n```java\n\n\timport java.lang.reflect.*\n\n\tpublic class RunTests{\n\t\tpublic static void main(String[] args) throws Exception {\n\t\t\tint tests = 0;\n\t\t\tint passed  = 0;\n\t\t\tClass testClass = Class.forName(args[0]);\n\t\t\tfor (Method m : testClass.getDeclaredMethods()){\n\t\t\t\tif (m.isAnnotationPresent(Test.class)){\n\t\t\t\t\ttests++;\n\t\t\t\t\ttry{\n\t\t\t\t\t\tm.invoke(null);\n\t\t\t\t\t\tpassed++;\n\t\t\t\t\t} catch(InvocationTargetException wrappedExc){\n\t\t\t\t\t\tThrowable exc = wrappedExc.getCause();\n\t\t\t\t\t\tSystem.out.println(m + \" failed: \" + exc);\n\t\t\t\t\t} catch (Exception exc){\n\t\t\t\t\t\tSystem.out.println(\"INVALID @Test: \" + m);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tSystem.out.printf(\"Passed: %d, Failed: %d%n\", passed, tests - passed);\n\t\t}\n\t}\n```\n\n## 36. Consistently use the _Override_ annotation\n\nUse the _Override_ annotation on every method declaration that you believe to override a super class declaration.\n\n```java\n\n\tpublic class Bigram {\n\t\tprivate final class first;\n\t\tprivate final class second;\n\t\tpublic Bigram(char first, char second){\n\t\t\tthis.first = first;\n\t\t\tthis.second = second;\n\t\t}\n\t\tpublic boolean equals(Bigram b){ //ERROR.\n\t\t\treturn b.first == first \u0026\u0026 b.second == second;\n\t\t}\n\t\t...\n\t}\n```\n\nWe are overloading equals instead of overriding it.  \nThe correct sign to override the super method is:\n\n```java\n\n\tpublic boolean equals(Object o){}\n```\n\nWith the use of Override the compiler would alert us about our mistake.\n\n## 37. Use marker interfaces to define types\n\nMarker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface.\n\nA _marker interface_ is an interface that contains no method declarations, but \"marks\" a class that implements the interface as having some property.\n\nWhen your class implements `java.io.Serializable` interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.\n\n- Marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. (Catch errors in compile time).\n- They can be targeted more precisely than marker annotations.\n- It's possible to add more information to an annotation type after it is already in use.\n\n# 7. METHODS\n\n## 38. Check parameters for validity\n\nCheck parameters before execution as soon as possible.\n\nAdd in public methods _@throw_, and use _assertions_ in non public methods\n\nDo it also in constructors.\n\n## 39. Make defensive copies when needed.\n\nYou must program defensively, with the assumption that clients of your class will do their best to destroy its invariants.\n\n```java\n\n\t//Broken \"immutable\" time period\n\tpublic final class Period{\n\t\tprivate final Date start;\n\t\tprivate final Date end;\n\t\t/**\n\t\t* @param start the beginning of the period\n\t\t* @param end the end of the period; must not precede start;\n\t\t* @throws IllegalArgumentException if start is after end\n\t\t* @throws NullPointerException if start or end is null\n\t\t*/\n\t\tpublic Period(Date start, Date end) {\n\t\t\tif(start.compare(end) \u003e 0)\n\t\t\t\tthrow new IllegalArgumentException(start + \" after \" + end );\n\t\t\tthis.start = start;\n\t\t\tthis.end = end;\n\t\t}\n\n\t\tpublic Date start(){\n\t\t\treturn start;\n\t\t}\n\n\t\tpublic Date end(){\n\t\t\treturn end;\n\t\t}\n\t\t...\n\t}\n```\n\nAttack. Because the client keep a copy (pointer) of the parameter, it can always change it after the constructor.\n\n```java\n\n\tDate start = new Date();\n\tDate end = new Date();\n\tPeriod p = new Period(start, end);\n\tend.setYear(78)// Modifies internal of p!\n```\n\nMake a _defensive copy_ of each mutable parameter to the constructor.\n\n```java\n\n\tpublic Period(Date start, Date end) {\n\t\tthis.start = new Date(start.getTime());\n\t\tthis.end = new Date(end.getTime());\n\t\tif(start.compare(end) \u003e 0)\n\t\t\tthrow new IllegalArgumentException(start + \" after \" + end );\n\t\t}\n```\n\nDefensive copies are made before checking the validity of the parameter ([Item 38](#38-check-parameters-for-validity)), and the validity check is performed on the copies rather than on the originals. It protects the class against changes to the parameters from another thread during the time between the parameters are checked and the time they are copied.(_Window of vulnerability_,time-of-check/time-of-use _TOCTOU_ attack)\n\nDo not use _clone_ method to make a defensive copy of a parameter whose type is subclass-able by untrusted parties.\n\nSecond Attack. Because the accessors returns the object used in the Period class, the client can change its value without passing the constrains.\n\n```java\n\n\tDate start = new Date();\n\tDate end = new Date();\n\tPeriod p = new Period(start, end);\n\tp.end.setYear(78)// Modifies internal of p!\n```\n\nReturn _defensive copies_ of mutable internal fields.\n\n```java\n\n\tpublic Date start(){\n\t\treturn new Date(start.getTime());\n\t}\n\n\tpublic Date end(){\n\t\treturn new Date(end.getTime());\n\t}\n```\n\nPreferable is to use **immutable objects**([Item 15](#15-minimize-mutability))\n\n## 40. Design method signatures carefully\n\n- Choose method names carefully. ([Item 56](#56-adhere-to-generally-accepted-naming-conventions))\n- Don't go overboard in providing convenience methods. Don't add too many.\n- Avoid long parameter list. Make a subset of methods, helper classes ([Item 22](#22-favor-static-member-classes-over-nonstatic)), or a builder ([Item 2](#2-use-builders-when-faced-with-many-constructors)) instead.\n- For parameter types, favor interfaces over classes ([Item 52](#52-refer-to-objects-by-their-interface)) No reason to write a method that takes a _HashMap_ on input, use _Map_ instead.\n- Prefer two-element enum types to _boolean_ parameters. `public enum TemperatureScale {CELSIUS, FARENHEIT}`\n\n## 41. Use overloading judiciously\n\nThe choice of which overloading to invoke is made at compile time.\nSelection among overloaded methods is static, while selection among overridden methods is dynamic.\n\n```java\n\n\t// Broken! - What does this program print?\n\tpublic class CollectionClassifier {\n\t\tpublic static String classify(Set\u003c?\u003e s) {\n\t\t\treturn \"Set\";\n\t\t}\n\t\tpublic static String classify(List\u003c?\u003e lst) {\n\t\t\treturn \"List\";\n\t\t}\n\t\tpublic static String classify(Collection\u003c?\u003e c) {\n\t\t\treturn \"Unknown Collection\";\n\t\t}\n\t\tpublic static void main(String[] args) {\n\t\t\tCollection\u003c?\u003e[] collections = {\n\t\t\t\tnew HashSet\u003cString\u003e(),\n\t\t\t\tnew ArrayList\u003cBigInteger\u003e(),\n\t\t\t\tnew HashMap\u003cString, String\u003e().values()\n\t\t\t};\n\t\tfor (Collection\u003c?\u003e c : collections)\n\t\t\tSystem.out.println(classify(c)); // Returns \"Unknown Collection\" 3 times\n\t\t}\n\t}\n```\n\nOverriding works different. The “most specific” overriding method always gets executed.\n\n```java\n\n\tclass Wine {\n\t\tString name() { return \"wine\"; }\n\t}\n\tclass SparklingWine extends Wine {\n\t\t@Override String name() { return \"sparkling wine\"; }\n\t}\n\tclass Champagne extends SparklingWine {\n\t\t@Override String name() { return \"champagne\"; }\n\t}\n\tpublic class Overriding {\n\t\tpublic static void main(String[] args) {\n\t\t\tWine[] wines = {\n\t\t\t\tnew Wine(), new SparklingWine(), new Champagne()\n\t\t\t};\n\t\t\tfor (Wine wine : wines)\n\t\t\t\tSystem.out.println(wine.name()); // prints: wine, sparkling wine, and champagne\n\t\t}\n\t}\n```\n\nOverloading does not give the functionallity we want in the first sample. A possible solution is:\n\n```java\n\n\tpublic static String classify(Collection\u003c?\u003e c) {\n\t\treturn \tc instanceof Set ? \"Set\" :\n\t\t\t\tc instanceof List ? \"List\" : \"Unknown Collection\";\n\t}\n```\n\nDo not have overloaded methods in APIs to avoid confusing the clients of the API.\n\nA conservative policy is to never export two overloadings with the same number of parameters. Use different names.`writeBoolean(boolean)`, `writeInt(int)`, and `writeLong(long)`\n\nFor constructors you can use static factories ([Item 1](#1-use-static-factory-methods-instead-of-constructors))\n\nIf parameters are radically different this rule can be violated but always ensure that all overloadings behave identically\nwhen passed the same parameters. To ensure this, have the more specific overloading forward to the more general.\n\n```java\n\n\tpublic boolean contentEquals(StringBuffer sb) {\n\t\treturn contentEquals((CharSequence) sb);\n\t}\n```\n\n## 42. Use varargs judiciously\n\nvarargs methods are a convenient way to define methods that require a variable number of arguments, but they should not be overused.\n\n```java\n\n\t// The right way to use varargs to pass one or more arguments\n\tstatic int min(int firstArg, int... remainingArgs) {\n\t\tint min = firstArg;\n\t\tfor (int arg : remainingArgs)\n\t\t\tif (arg \u003c min)\n\t\t\t\tmin = arg;\n\t\treturn min;\n\t}\n```\n\n## 43. Return empty arrays or collections, not nulls\n\nThere is no reason ever to return null from an array- or collection-valued method instead of returning an empty array or collection\n\nReturn an immutable empty array instead of null.\n\n```java\n\n\t// The right way to return an array from a collection\n\tprivate final List\u003cCheese\u003e cheesesInStock = ...;\n\n\tprivate static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];\n\n\t/**\n\t* @return an array containing all of the cheeses in the shop.\n\t*/\n\tpublic Cheese[] getCheeses() {\n\t\treturn cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);\n\t}\n```\n\nIn Collections emptySet, emptyList and emptyMap methods do the same job.\n\n```java\n\n\t// The right way to return a copy of a collection\n\tpublic List\u003cCheese\u003e getCheeseList() {\n\t\tif (cheesesInStock.isEmpty())\n\t\t\treturn Collections.emptyList(); // Always returns same list\n\t\telse\n\t\t\treturn new ArrayList\u003cCheese\u003e(cheesesInStock);\n\t}\n```\n\n## 44. Write _doc comments_ for all exposed API elemnts\n\nTo document your API properly, you must precede every exported class, interface, constructor, method, and field declaration with a doc comment.\n\nThe doc comment for a method should describe succinctly:\n\n- The _contract_ between the method and its client, what the method does rather than how it does its job.\n- The _preconditions_ described implicity by the _@throws_ tag.\n- The _postconditions_, things that will be true after the invocation has completed successfully.\n- The _side effects_, change in the state of the system.\n- The _thread safety_ of the class and methods\n- The _summary description of the element_, the first “sentence” of each doc comment.Should not contains a space after a period.\n\n```java\n\n\t/**\n\t* Returns the element at the specified position in this list. *\n\t* \u003cp\u003eThis method is \u003ci\u003enot\u003c/i\u003e guaranteed to run in constant\n\t* time. In some implementations it may run in time proportional * to the element position.\n\t*\n\t* @param index index of element to return; must be\n\t* non-negative and less than the size of this list\n\t* @return the element at the specified position in this list\n\t* @throws IndexOutOfBoundsException if the index is out of range\n\t*\t\t({@code index \u003c 0 || index \u003e= this.size()})\n\t*/\n\tE get(int index);\n```\n\nHave special care in:\n\n- Generics: document all type parameters\n- Enums: document all the constants, the type and the public methods.\n- Annotatons: document all members an the type.\n\nDon't forget to documment:\n\n- The _thread-safety level_ ([Item 70](#70-document-thread-safety))\n- The _serialized form_ ([Item 75](#75-consider-using-a-custom-serialized-form)), if the class is _serializable_\n\n# 8. GENERAL PROGRAMMING\n\n## 45. Minimize the scope of local variables.\n\nDeclare local variable where it is first used.  \nMost local variable declaration should contain an initializer.  \nPrefer for loops to while loops.  \nKeep methods small and focused.\n\n## 46. Prefer for-each loops to traditional for loops.\n\n```java\n\n\t // No longer the preferred idiom to iterate over a collection!\n\t\tfor (Iterator i = c.iterator(); i.hasNext(); ) {\n\t\t\tdoSomething((Element) i.next()); // (No generics before 1.5)\n\t}\n\t// No longer the preferred idiom to iterate over an array!\n\t   for (int i = 0; i \u003c a.length; i++) {\n\t       doSomething(a[i]);\n\t}\n```\n\nUse for each loop:\n\n```java\n\n\t// The preferred idiom for iterating over collections and arrays\n\t   for (Element e : elements) {\n\t       doSomething(e);\n\t}\n```\n\nError when iterating in nested loops\n\n```java\n\n\t // Can you spot the bug?\n\t   enum Suit { CLUB, DIAMOND, HEART, SPADE }\n\t   enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT,\n\t               NINE, TEN, JACK, QUEEN, KING }\n\t   ...\n\t   Collection\u003cSuit\u003e suits = Arrays.asList(Suit.values());\n\t   Collection\u003cRank\u003e ranks = Arrays.asList(Rank.values());\n\t   List\u003cCard\u003e deck = new ArrayList\u003cCard\u003e();\n\t   for (Iterator\u003cSuit\u003e i = suits.iterator(); i.hasNext(); )\n\t       for (Iterator\u003cRank\u003e j = ranks.iterator(); j.hasNext(); )\n\t           deck.add(new Card(i.next(), j.next())); // i.next() should be run only in the outer loop\n\n```\n\nA solution\n\n```java\n\n\t// Fixed, but ugly - you can do better!\n\tfor (Iterator\u003cSuit\u003e i = suits.iterator(); i.hasNext(); ) {\n\t   Suit suit = i.next();\n\t   for (Iterator\u003cRank\u003e j = ranks.iterator(); j.hasNext(); )\n\t\t\tdeck.add(new Card(suit, j.next()));\n\t}\n```\n\nFor each loop fix this directly\n\n```java\n\n\t// Preferred idiom for nested iteration on collections and arrays\n\t   for (Suit suit : suits)\n\t       for (Rank rank : ranks)\n\t           deck.add(new Card(suit, rank));\n```\n\nSituations where you can’t use a for-each loop:\n\n- **Filtering—If** you need to traverse a collection and remove selected elements, then you need to use an explicit iterator so that you can call its remove method.\n- **Transforming—If** you need to traverse a list or array and replace some or all of the values of its elements, then you need the list iterator or array index in order to set the value of an element.\n- **Parallel iteration—If** you need to traverse multiple collections in parallel, then you need explicit control over the iterator or index variable, so that all it- erators or index variables can be advanced in lockstep (as demonstrated unin-tentionally in the buggy card examples above).\n\n## 47. Know and use libraries\n\nBy using a standard library:\n\n- Advantage of the knowledge of the experts who wrote it and the experience of those who used it before you.\n- Don’t have to waste your time writing ad hoc solutions to problems that are only marginally related to your work.\n- Their performance tends to improve over time\n- Your code will be easily readable, maintainable, and reusable.\n\nNumerous features are added to the libraries in every major release, and it pays to keep abreast of these additions\n\nEvery programmer should be familiar with:\n\n- java.lang\n- java.util\n- java.io\n- java.util.concurrent\n\n## 48. Avoid float and double if exact answer are required\n\nFor monetary calculations use _int_(until 9 digits) or _long_ (until 18 digits) taken you care of the decimal part and you don't care too much about the rounding. Use _BigDecimal_ for numbers bigger that 18 digits and if you need full control of the rounding methods used.\n\n## 49. Prefer primitive types to boxed primitives\n\nPrimitives: _int_, _double_, _boolean_  \nBoxed Primitives: _Integer_, _Double_, _Boolean_  \nDifferences:\n\n- Two boxed primitives could have the same value but different identity.\n- Boxed primitives have one nonfunctional value: _null_.\n- Primitives are more space and time efficient.\n\nDon't use **==** between boxed primitives.\n\n```java\n\n\tfirst = new Integer(1);\n\tsecond = new Integer(1);\n\tfirst == second; //Uses unboxing  Don't have to be true.\n```\n\nUse Auto-unboxing to create new primitives\n\n```java\n\n\t...\n\tint f = first;  //Auto-unboxing\n\tint s = second  //Auto-unboxing\n\tf == s;// This is true\n```\n\nIf a Boxed primitive is not initialize it will return null\n\n```java\n\n\tInteger  i;\n\ti == 42 // NullPointerException\n```\n\nPerformance can be perturbed when boxing primitives values due to the creation of unnecessary objects.\n\nWhen you **must** use boxed primitives:\n\n- As elements, keys and values in Collections\n- As type parameters in parametrized types ([Chapter 5](#5-generics))\n- When making reflective invocations ([Item 53](#53-prefer-interfaces-to-reflection))\n\nIn other cases prefer primitives.\n\n## 50. Avoid Strings where other types are more appropriate\n\n- Strings are more cumbersome than other types.\n- Strings are less flexible than other types.\n- String are slower than other types.\n- Strings are more error-prone than other types.\n- Strings are poor substitutes for other value types.\n- Strings are poor substitutes for _enum_ types.\n- Strings are poor substitutes for _aggregate_ types.\n- Strings are poor substitutes for _capabilities_.\n\nSo, use String to represent text!\n\n## 51. Beware the performance of string concatenation\n\nUsing the string concatenation operator repeatedly to concatenate _n_ strings requires time quadratic in _n_.\n\n```java\n\n\t// Inappropriate use of string concatenation - Performs horribly!\n\tpublic String statement()\n\t\tString result = \"\";\n\t\tfor (int i = 0; i \u003c numItems(); i++)\n\t\t\tresult += lineForItem(i);\n\t\treturn result;\n\n```\n\nTo achieve acceptable performance, use StringBuilder in place of String.\n\n```java\n\n\tpublic String statement(){\n\t\tStringBuilder b = new StringBuilder(numItems() * LINE_WIDTH);\n\t\tfor (int i = 0; i \u003c numItems(); i++)\n\t\t\tb.append(lineForItem(i));\n\t\treturn b.toString();\n\t}\n```\n\n## 52. Refer to objects by their interface\n\nIf appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.\n\n```java\n\n\t// Good - uses interface as type\n\tList\u003cSubscriber\u003e subscribers = new Vector\u003cSubscriber\u003e();\n```\n\nrather than this:\n\n```java\n\n\t// Bad - uses class as type!\n\tVector\u003cSubscriber\u003e subscribers = new Vector\u003cSubscriber\u003e();\n```\n\nIt makes the program much more flexible. We could change the implementation of the `subscribers` changing just one line.\n\n```java\n\n\tList\u003cSubscriber\u003e subscribers = new ArrayList\u003cSubscriber\u003e();\n```\n\n**Caveat**: if the original implementation has a special functionality not required the interface contract and the code dependent on that functionality, the new implementation must provide this functionality.\n\nIf there is not an appropriate interface we can refer to the object by a class. Like:\n\n- Value classes: String, BigDecimal...\n- Framework classes\n- Classes that extend the interface functionality with extra methods.\n\n## 53. Prefer interfaces to reflection\n\n_java.lang.reflection_ offers access to information about loaded classes.\n\nGiven a _Class_ object, you can obtain _Constructor_, _Method_ and _Field_ instances.\n\nAllows one class to use another, even if the latter class did not exist when the former was compiled.\n\n- Lose all benefits of compile-time type checking\n- Code to perform reflective access is clumsy and verbose\n- Performance suffers.\n\n**As a rule, objects should not be accessed reflectively in normal applications at runtime**\n\nObtain many of the benefits of reflection incurring few of its costs by **creating instances reflectively and access them normally via their interface or superclass**.\n\n```java\n\n\t// Reflective instantiation with interface access\n\tpublic static void main (String[] args){\n\t\t// Translate the class name into a class object\n\t\tClass\u003c?\u003e cl =  null;\n\t\ttry{\n\t\t\tcl = Class.forName(args[0]);// Class is specified by the first command line argument\n\t\t}catch(ClassNotFoundException e){\n\t\t\tSystem.err.println(\"Class not found\");\n\t\t\tSystem.exit(1);\n\t\t}\n\n\t\t//Instantiate the class\n\t\tSet\u003cString\u003e s = null;\n\t\ttry{\n\t\t\ts = (Set\u003cString\u003e) cl.newInstance(); //  The class can be either a HashSet or a TreeSet\n\t\t} catch(IllegalAccessException e){\n\t\t\tSystem.err.println(\"Class not accessible\");\n\t\t\tSystem.exit(1);\n\t\t}catch(InstantionationException e){\n\t\t\tSystem.err.println(\"Class not instantiable\");\n\t\t\tSystem.exit(1);\n\t\t}\n\n\t\t//Excercise the Set\n\t\t// Print the remaining arguments. The order depends in the class. If it is a HashSet\n\t\t// the order will be random, if it is a TreeSet it will be alphabetically\n\t\ts.addAll(Arrays.asList(args).subList(1,args.length));\n\t\tSystem.out.println(s);\n\t}\n```\n\nA legitimate use of reflection is to manage a class's dependencies on other classes, methods or fields that may be absent at runtime.\n\nReflection is powerful and useful in some sophisticated systems programming tasks. It has many disadvantages.\nUse reflection, if possible, only to instantiate objects and access the objects using an interface or a superclass that is known at compile time.\n\n## 54. Use native methods judiciously\n\nHistorically, native methods have had three main uses.\n\n- They provided access to platform-specific facilities.\n- They provided access to libraries of legacy code.\n- To write performance-critical parts\n\nNew Java versions make use of NDK rarely advisable for improve performance.\n\n## 55. Optimize judiciously\n\nStrive to write good programs rather than fast ones, speed will follow.  \nIf a good program is not fast enough, its architecture will allow it to be optimized.\n\n- More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason — including blind stupidity.\n- We should forget about small efficiencies, say about 97% of the time: premature\n  optimization is the root of all evil.\n- We follow two rules in the matter of optimization:\n  - Rule 1. Don't do it.\n  - Rule 2 (for experts only). Don't do it yet — that is, not until you have a perfectly clear and unoptimized solution.\n\nIf you finally do it **measure performance before and after each attempted optimization**, and focus firstly in the choice of algorithms rather than in low level optimizations.\n\n## 56. Adhere to generally accepted naming conventions\n\n**Typographical naming conventions**\n\n| Indentifier Type   | Examples                                      |\n| ------------------ | --------------------------------------------- |\n| Package            | com.google.inject, org.joda.time.format       |\n| Class or Interface | Timer, FutureTask, LinkedHashMap, HttpServlet |\n| Method or Field    | remove, ensureCapacity, getCrc                |\n| Constant Field     | MIN_VALUE, NEGATIVE_INFINITY                  |\n| Local Variable     | i, xref, houseNumber                          |\n| Type Parameter     | T, E, K, V, X, T1, T2                         |\n\n**Grammatical naming conventions**\n\n| Type                                                                    | Convention                                   | Example                                                   |\n| ----------------------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------- |\n| Classes and enum types                                                  | Singular noun or noun phrase                 | Timer, BufferedWriter, ChessPiece                         |\n| Interfaces                                                              | Like classes                                 | Collection, Comparator                                    |\n| Interfaces                                                              | With an adjective ending in _able_ or _ible_ | Runnable, Iterable, Accessible                            |\n| Annotation types                                                        | Nouns, verbs, prepositions, adjectives ...   | BindingAnnotation, Inject, ImplementedBy, Singleton       |\n| Static factories (common names)                                         | ---                                          | valueOf, of, getInstance, newInstance, getType, newType   |\n| **Methods that...**                                                     | ---                                          | ---                                                       |\n| perform actions                                                         | verb or verb phrase                          | append, drawImage                                         |\n| return a boolean                                                        | names beginning with _is_ or, _has_          | isDigit, isProbablePrime, isEmpty, isEnabled, hasSiblings |\n| return a non-boolean or attribute                                       | noun, a noun phrase, or begin with _get_     | size, hashCode, or getTime                                |\n| convert the type of an object                                           | _toType_                                     | toString, toArray                                         |\n| return a view ([Item 5](#5-avoid-creating-objects)) of a different type | _asType_                                     | asList                                                    |\n| return a primitive with the same value                                  | _typeValue_                                  | intValue                                                  |\n\n# 9. EXCEPTIONS\n\n## 57. Use exceptions only for exceptional conditions\n\nExceptions are for exceptional conditions.  \nNever use or (expose in the API) exceptions for ordinary control flow.\n\n## 58. Use checked exceptions for recoverable conditions and runtime exceptions for programming errors\n\nThrowables:\n\n- checked exceptions: for conditions from which the caller can reasonably be expected to recover\n- unchecked exceptions: shouldn't, be caught. recovery is impossible and continued execution would do more harm than good.\n  - runtime exceptions: to indicate programming errors. The great majority indicate precondition violations.\n  - errors : are reserved for use by the JVM. (as a convention)\n\nUnchecked throwables that you implement should **always** subclass _RuntimeException_.\n\n## 59. Avoid unnecessary use of checked exceptions\n\nUse checked exceptions only if these 2 conditions happen:\n\n- The exceptional condition cannot be prevented by proper use of the API\n- The programmer using the API can take some useful action once confronted with the exception.\n\nRefactor the checked exception into a unchecked exception to make the API more pleasant.\n\nInvocation with checked exception\n\n```java\n\n\ttry {\n\t\tobj.action(args);\n\t} catch(TheCheckedException e) {\n\t\t// Handle exceptional condition\n\t\t...\n\t}\n```\n\nInvocation with state-testing method and unchecked exception\n\n```java\n\n\tif (obj.actionPermitted(args)) {\n\t\tobj.action(args);\n\t} else {\n\t\t// Handle exceptional condition\n\t\t...\n\t}\n```\n\n## 60. Favor the use of standard exceptions\n\n| Exception                       | Occasion for Use                                                              |\n| ------------------------------- | ----------------------------------------------------------------------------- |\n| IllegalArgumentException        | Non-null parameter value is inappropriate                                     |\n| IllegalStateException           | Object state is inappropriate for method invocation                           |\n| NullPointerException            | Parameter value is null where prohibited                                      |\n| IndexOutOfBoundsException       | Index parameter value is out of range                                         |\n| ConcurrentModificationException | Concurrent modification of an object has been detected where it is prohibited |\n| UnsupportedOperationException   | Object does not support method                                                |\n\n### Java 8 Exceptions\n\n|                                |                                   |                                 |\n| ------------------------------ | --------------------------------- | ------------------------------- |\n| AclNotFoundException           | InvalidMidiDataException          | RefreshFailedException          |\n| ActivationException            | InvalidPreferencesFormatException | RemarshalException              |\n| AlreadyBoundException          | InvalidTargetObjectTypeException  | RuntimeException                |\n| ApplicationException           | IOException                       | SAXException                    |\n| AWTException                   | JAXBException                     | ScriptException                 |\n| BackingStoreException          | JMException                       | ServerNotActiveException        |\n| BadAttributeValueExpException  | KeySelectorException              | SOAPException                   |\n| BadBinaryOpValueExpException   | LambdaConversionException         | SQLException                    |\n| BadLocationException           | LastOwnerException                | TimeoutException                |\n| BadStringOperationException    | LineUnavailableException          | TooManyListenersException       |\n| BrokenBarrierException         | MarshalException                  | TransformerException            |\n| CertificateException           | MidiUnavailableException          | TransformException              |\n| CloneNotSupportedException     | MimeTypeParseException            | UnmodifiableClassException      |\n| DataFormatException            | MimeTypeParseException            | UnsupportedAudioFileException   |\n| DatatypeConfigurationException | NamingException                   | UnsupportedCallbackException    |\n| DestroyFailedException         | NoninvertibleTransformException   | UnsupportedFlavorException      |\n| ExecutionException             | NotBoundException                 | UnsupportedLookAndFeelException |\n| ExpandVetoException            | NotOwnerException                 | URIReferenceException           |\n| FontFormatException            | ParseException                    | URISyntaxException              |\n| GeneralSecurityException       | ParserConfigurationException      | UserException                   |\n| GSSException                   | PrinterException                  | XAException                     |\n| IllegalClassFormatException    | PrintException                    | XMLParseException               |\n| InterruptedException           | PrivilegedActionException         | XMLSignatureException           |\n| IntrospectionException         | PropertyVetoException             | XMLStreamException              |\n| InvalidApplicationException    | ReflectiveOperationException      | XPathException                  |\n\n## 61. Throw exceptions appropriate to the abstraction\n\nHigher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.\n\n```java\n\n\t// Exception Translation\n\ttry {\n\t\t// Use lower-level abstraction to do our bidding\n\t\t...\n\t} catch(LowerLevelException e) {\n\t\tthrow new HigherLevelException(...);\n\t}\n```\n\nDo not overuse. The best way to deal with exceptions from lower layers is to avoid them, by ensuring that lower-level methods succeed.\n\n**Exception chaining**\nWhen the lower-level exception is utile for the debugger, pass the lower-level to the higher-level exception, with an accessor method (Throwable.getCause) to retrieve the lower-level exception.\n\n```java\n\n\t// Exception with chaining-aware constructor\n\tclass HigherLevelException extends Exception {\n\t\tHigherLevelException(Throwable cause) {\n\t\tsuper(cause);\n\t\t}\n\t}\n```\n\n## 62. Document all exceptions thrown by each method\n\nUnchecked exceptions generally represent programming errors ([Item 58](#58-use-checked-exceptions-for-recoverable-conditions-and-runtime-exceptions-for-programming-errors)), and familiarizing programmers with all of the errors they can make helps them avoid making these errors.\n\nAlways declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag.\n\nDo not use the throws keyword to include unchecked exceptions in the method declaration.\n\n## 63. Include failure-capture information in detail messages\n\nIt is critically important that the exception’s `toString` method return as much information as possible concerning\nthe cause of the failure.\nTo capture the failure, the detail message of an exception should contain the values of all parameters and fields that contributed to the exception.\nOne way to ensure that is to require this information in their constructors instead of a string detail message. Also provide accessors to this parameters could help useful to recover from the failure\n\n```java\n\n\t// Alternative IndexOutOfBoundsException.\n\tpublic IndexOutOfBoundsException(int lowerBound, int upperBound, int index) {...}\n```\n\n## 64. Strive for failure atomicity\n\nA failed method invocation should leave the object in the state that it was in prior to the invocation.\nOptions to achieve this:\n\n- Design immutable objects\n- Order the computation so that any part that may fail takes place before any part that modifies the object.\n- Write recovery code (Undo operation)\n- Perform the operation on a temporary copy of the object, and replace it once is completed.\n\n## 65. Don't ignore exceptions\n\nDon't let catch blocks empty.\n\n```java\n\n\t// Empty catch block ignores exception - Highly suspect!\n\ttry {\n\t...\n\t} catch (SomeException e) {\n\t}\n```\n\n# 10. CONCURRENCY\n\n## 66. Synchronize access to shared mutable data\n\nSynchronization prevent a thread from observing an object in an inconsistent state.\nSynchronization ensures that each thread entering a synchronized method or block sees the effects\nof all previous modifications that were guarded by the same lock.\n\nIn Java reading or writing a variable is atomic unless type long or double, but for all atomic operations it does not guarantee that a value written by one thread will be visible to another.\n\nSynchronization is required for reliable communication between threads as well as for mutual exclusion.\n\n```java\n\n\t// Broken! - How long would you expect this program to run?\n\tpublic class StopThread {\n\t\tprivate static boolean stopRequested;\n\n\t\tpublic static void main(String[] args) throws InterruptedException {\n\t\t\tThread backgroundThread = new Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tint i = 0;\n\t\t\t\t\twhile (!stopRequested)\n\t\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t});\n\t\t\tbackgroundThread.start();\n\n\t\t\tTimeUnit.SECONDS.sleep(1);\n\t\t\tstopRequested = true;\n\t\t}\n\t}\n```\n\nBecause of _hoisting_ the while loop is translated to this:\n\n```java\n\n\tif (!done)\n\t\twhile (true)\n\t\t\ti++;\n\n```\n\nand therefore the loop never stops.\n\n```java\n\n\t// Properly synchronized cooperative thread termination\n\tpublic class StopThread {\n\t\tprivate static boolean stopRequested;\n\n\t\tprivate static synchronized void requestStop() {\n\t\t\tstopRequested = true;\n\t\t}\n\t\tprivate static synchronized boolean stopRequested() {\n\t\t\treturn stopRequested;\n\t\t}\n\n\t\tpublic static void main(String[] args) throws InterruptedException {\n\t\t\tThread backgroundThread = new Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tint i = 0;\n\t\t\t\t\twhile (!stopRequested())\n\t\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t});\n\t\tbackgroundThread.start();\n\n\t\tTimeUnit.SECONDS.sleep(1);\n\t\trequestStop();\n\t\t}\n\t}\n```\n\nSynchronization has no effect unless both read and write operations are synchronized.\n\nOther solution is using _volatile_ modifier, it performs no mutual exclusion, but it guarantees that any thread that reads the field will see the most recently written value.\n\n```java\n\n\tpublic class StopThread {\n\t\tprivate static volatile boolean stopRequested;\n\n\t\tpublic static void main(String[] args) throws InterruptedException {\n\t\t\tThread backgroundThread = new Thread(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tint i = 0;\n\t\t\t\t\twhile (!stopRequested)\n\t\t\t\t\t\ti++;\n\t\t\t}\n\t\t});\n\t\tbackgroundThread.start();\n\n\t\tTimeUnit.SECONDS.sleep(1);\n\t\tstopRequested = true;\n\t\t}\n\t}\n```\n\nBe careful with _volatile_ when using non atomic functions like ++\n\n```java\n\n\tprivate static volatile int nextSerialNumber = 0;\n\n\tpublic static int generateSerialNumber() {\n\t\treturn nextSerialNumber++;\n\t}\n```\n\nWe can synchronize the access to nextSerialNumber and remove _volatile_ or use AtomicLong.\nAtomicLong can help us with the synchronization of long values\n\n```java\n\n\tprivate static final AtomicLong nextSerialNum = new AtomicLong();\n\n\tpublic static long generateSerialNumber() {\n\t\treturn nextSerialNum.getAndIncrement();\n\t}\n```\n\n**effectively immutable**: data object modified by one thread to modify shared it with other threads, synchronizing only the act of sharing the object reference. Other threads can then read the object without further synchronization, so long as it isn't modified again.\n\n**safe publication**: Transferring such an object reference from one thread to others.\n\n_In general:_ When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization\n\n_Best thing to do:_ **Not share mutable data.**\n\n## 67. Avoid excessive synchronization\n\nInside a synchronized region, do not invoke a method (_alien_) that is designed to be overridden, or one provided by a client in the form of a function object ([Item 21](#21-use-function-objects-to-represent-strategies)). Calling it from a synchronized region can cause exceptions,\ndeadlocks, or data corruption.\nMove alien method invocations out of synchronized blocks. Taking a “snapshot” of the object that can then be safely traversed without a lock.\n\n```java\n\n\t// Alien method moved outside of synchronized block - open calls\n\tprivate void notifyElementAdded(E element) {\n\t\tList\u003cSetObserver\u003cE\u003e\u003e snapshot = null;\n\t\tsynchronized(observers) {\n\t\t\tsnapshot = new ArrayList\u003cSetObserver\u003cE\u003e\u003e(observers);\n\t\t}\n\t\tfor (SetObserver\u003cE\u003e observer : snapshot)\n\t\t\tobserver.added(this, element);\n\t}\n```\n\nOr use a _concurrent collection_ ([Item 69](#69-prefer-concurrency-utilities-to-wait-and-notify)) known as CopyOnWriteArrayList. It is a variant of ArrayList in which all write operations are implemented by making a fresh copy of the entire underlying array.\nThe internal array is never modified and iteration requires no locking.\n\n**open call**: An alien method invoked outside of a synchronized region\n\n_As Rule_:\n\n- **do as little work as possible inside synchronized regions**\n- **limit the amount of work that you do from within synchronized regions**\n\n## 68. Prefer executors and tasks to threads\n\nCreating a work queue:\n\n```java\n\n\tExecutorService executor = Executors.newSingleThreadExecutor();\n```\n\nSubmit a runnable for execution:\n\n```java\n\n\texecutor.execute(runnable);\n```\n\nTerminate gracefully the executor\n\n```java\n\n\texecutor.shutdown();\n```\n\nExecutorService possibilities:\n\n- wait for a particular task to complete: `background thread SetObserver`\n- wait for any or all of a collection of tasks to complete: `invokeAny` or `invokeAll`\n- wait for the executor service's graceful termination to complete: `awaitTermination`\n- retrieve the results of tasks one by one as they complete: `ExecutorCompletionService`\n  \\*...\n\nFor more than one thread use a _thread pool_.\nFor lightly loaded application, use: `Executors.new-CachedThreadPool`\nFor heavily loaded application, use: `Executors.newFixedThreadPool`\n\n**executor service**: mechanism for executing tasks\n\n**task**: unit of work. Two types.\n\n- Runnable\n- Callable, similar to Runnable but returns a value\n\n## 69. Prefer concurrency utilities to _wait_ and _notify_\n\nGiven the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FHugoMatilla%2FEffective-JAVA-Summary","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FHugoMatilla%2FEffective-JAVA-Summary","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FHugoMatilla%2FEffective-JAVA-Summary/lists"}