Effective Java

Get Started. It's Free
or sign up with your email address
Effective Java by Mind Map: Effective Java

1. 3 - Methods Commons to all objects

1.1. 8: Obey the general contract when overriding equals

1.1.1. When possible use equals from Object

1.1.1.1. Each instance of the class is unique

1.1.1.2. The class doesn't need logical equality

1.1.1.3. The superclass already overriden de equals

1.1.1.4. The equals never will be invoked

1.1.2. Value Class are candidates for overridding

1.1.3. Equals Contract

1.1.3.1. Reflexive: x.equals(x) == true

1.1.3.2. Symmetric: x.equals(y) == y.equals(x)

1.1.3.3. Transitive: if x.equals(y) == true && y.equals(z) Then x.equals(z) == true

1.1.3.4. Consistency - Multiple invocation of x.equals(y) should return the same value

1.1.3.5. Null: x.equals(null) should return false

1.1.4. Recipe for Equals method

1.1.4.1. Uss o == this to check if it is the same isntance

1.1.4.2. Use o instance of "Class". Se o é nulo retorna falso.

1.1.4.3. Cast the parameter to the correct type

1.1.4.4. Check each field

1.1.4.4.1. Use == for primitive, but double and float

1.1.4.4.2. double and float use Double.compare e Float.compare

1.1.4.4.3. Use equals recursively for objects

1.1.4.4.4. Compare first fields that are more likely to differ,

1.1.4.5. Write unit test to check the contract

1.2. 9 - Always override HashCode when you override Equals

1.2.1. HashCode are used by hash-based collection to locate the object in the hash. After locate, they use the method equals to reassure that it's the object, because different objects can return the same hash code.

1.2.2. HashCode Contract

1.2.2.1. Return the same result whenever it's invoked for the same object

1.2.2.2. If two objects are "Equals" they must return the same hash

1.2.2.3. Unequal objects could return the same hash

1.3. 10 - Always Override toString

1.3.1. Nothing to say....

1.4. 11 - Override Clone Judisciously

1.4.1. Cloneable says that a class can be cloned

1.4.1.1. If the class doesn't implement the interface a exception will be throwed when clone is invoked

1.4.2. The Clone method of Object return a copy of the object copying field by field of the object. You should manually clone the references.

1.4.3. We can override Clone from Object like this: - change the visibilty for public - return the especific type (thanks covariants) - call super.object() - catch the exception CloneNotSupportedException

1.4.4. Clone is too complex, consider offer a copy constructor or a factory static method

1.5. 12 - Consider implementing Comparable

1.5.1. Permits order and equality comparisom

1.5.2. The method comes from Comparable Interface and it's generics

1.5.3. Contract

1.5.3.1. if the first object is less than the second, then the second must be greater than the first; if the first object is equal to the second, then the second must be equal to the first; if the first object is greater than the second, then the second must be less than the first.

1.5.3.2. if one object is greater than a second, and the second is greater than a third, then the first must be greater than the third.

1.5.3.3. All objects that compare as equal must yield the same results when compared to any other object.

1.5.3.4. Compare to should be equivalent to equals, bus it's not an obligation. Take care, sorted collections use compareTo when you add an element, when non-sorted use equals.

1.5.4. Whwn your object has multiple significants fields you should use the following technique: int areaCodeDiff = areaCode - pn.areaCode; if (areaCodeDiff != 0) return areaCodeDiff; instead of: if (areaCode < pn.areaCode) return -1; if (areaCode > pn.areaCode) return 1;

2. 5 - Generics

2.1. 24: Eliminate Unchecked Warnings

2.1.1. You know the reason of the warning?

2.1.1.1. Put a @SupressWarning <== Yes

2.1.1.1.1. Put in a little scope possible

2.1.1.2. Do your best to eliminate it <== No

2.2. 25 - Prefer Lists to Arrays

2.2.1. Arrays are covariants

2.2.1.1. Sub is a subtype of Super, So...Sub[] is a subtype of Super[].

2.2.2. Generics are invariants

2.2.3. arrays provide runtime type safety but not compile-time type safety and vice versa for generics

2.3. 26: Favor generic types

2.4. Item 28: Use bounded wildcards to increase API flexibility

2.4.1. You use the wildcard to let an hierarchy of objects be used

2.4.1.1. extends: The class and the classes below(abaixo)

2.4.1.2. super: The class and classes above(acima)

3. 6 - Enuns e Annotations

3.1. Item 30: Use enums instead of int constants

3.1.1. The values() method for an Enun returns an array of its values

3.1.2. You can define a abstract method and implement a especific implementation for each value

3.2. Item 31: Use instance fields instead of ordinals

3.2.1. The ordinal method return the position of the Enun minus 1. The first Enun is zero.

3.2.2. To know the positionorder prefer use a instance field (Passado no construtor o valor da posicao)

3.3. Item 34: Emulate extensible enums with interfaces

3.3.1. An Enum can implement an interface

3.3.2. They can't be extended

3.4. Item 35: Prefer annotations to naming patterns

3.4.1. the chapter describe the way like Junit do the things work

3.5. Item 36: Consistently use the Override annotation

3.5.1. use the anotation and the compiler will help you to override methods correctly (equals and hashcode)

4. 8 - General Programming

4.1. Item 45: Minimize the scope of local variables

4.1.1. Prefer foor loops intead of while one

4.2. Item 46: Prefer for-each loops to traditional for loops

4.3. Item 55: Optimize judiciously

4.3.1. Strive (Esforce-se) to write a good program, not necessaraly fast. Do right first, if it is slow, try to optimize with the support from a profiler tool.

4.4. Item 56: Adhere to generally accepted naming conventions

5. 9 - Exception

5.1. Item 57: Use exceptions only for exceptional conditions

5.1.1. Use exceptions olny for exceptional conditions, for ordinary flow don't use that

5.2. Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

5.3. Item 59: Avoid unnecessary use of checked exceptions

5.3.1. Just do it when the callen can handle tje situation

5.4. Item 60: Favor the use of standard exceptions

5.4.1. Try to reuse the unchecked exceptions defined by java

5.4.1.1. Turn you API easy to learn and read, because is familimar

5.4.1.2. The class loader please, because he needs to deal with few class derived by RuntimeExceptions

5.5. Item 61: Throw exceptions appropriate to the abstraction

5.5.1. Catch a low layer expection and enapsulate it within a high layer exception. This action is called exception chain.

5.6. Item 63: Include failure-capture information in detail messages

5.6.1. Put the parameters in the text maessage of the exception. Sometimes is hard do simulate an error, so if you have the parameter is easier to understand the problem.

5.7. Item 64: Strive for failure atomicity

5.7.1. If an exception occurs the object should be returned to the state that it was prior to the invocation.

5.7.1.1. Validate the parameters before alter the object

5.7.1.2. Put any code tha can fail before the part to alter the object

5.7.1.3. If the object was already altered, get the original ones in the BD,

5.7.1.4. Do a temporary copy the object in the beginning of the method, if the method fail use the temp object, else discard it and accept the changes

5.8. Item 65: Don’t ignore exceptions

5.8.1. You never should have a empty catch block.

6. 1 - Creating and destroying objects

6.1. 7 - Avoid Finalizers

6.1.1. Uso 1 - Liberar recursos de métodos nativos

6.1.2. Uso 2 - Liberar recursos explicitamente. Ex.: Close nas classes que lidam com arquivos. Lembre de chamar o finalizaer da classe mãe.

6.1.3. Não uso 1 - Liberar recurso. O GC faz isso bem.

6.1.4. Não uso 2 - Forçar liberação de recurso imediata. Não há garantias.

7. 4 - Classes and Interfaces

7.1. Item 13: Minimize the accessibility of classes and members

7.1.1. Hide internal Information of your class, so you can easily change the internal part without breaking the interfaces that the caller wait.

7.1.2. Minimize visibility as much as you can

7.2. Item 14: In public classes, use accessor methods, not public fields

7.3. Item 15: Minimize mutability

7.3.1. Rules for make an immutable class

7.3.1.1. Don't provide setter methods

7.3.1.2. make the class final

7.3.1.3. Make all fields final

7.3.1.4. Make all fields private

7.3.1.5. Take care of mutable fields. Make defensive copies

7.3.2. Immutable objects are inherently(inerentemente) thread-safe

7.3.3. The main disavantage is tha we need one object for each different value, it can cost a lot.

7.4. Item 16: Favor composition over inheritance

7.4.1. Problems with inherintance

7.4.1.1. Mudanças na classe mãe impactam a classe filha

7.4.1.2. Um método novo na classe mãe com assinatura parecida na classe filha pode fazer com que a classe filha deixe de compilar

7.4.1.3. Violates encapsulation

7.4.2. A class B should extend a class A only if an “is-a” relationship exists between the two classes.

7.5. Item 17: Design and document for inheritance or else prohibit it

7.5.1. Never invoke a overridable method from a superclass constructor

7.6. Item 19 - Use interfaces only to define types

7.6.1. Don't use interfaces to define constants

7.6.2. Define contants in a class

7.7. Item 20: Prefer class hierarchies to tagged classes

7.8. Item 21: Use function objects to represent strategies

7.9. Item 22: Favor static member classes over nonstatic

8. 7 - Methods

8.1. Item 38: Check parameters for validity

8.1.1. Before continue the execution of any methods validate de parameters. ASAP

8.1.2. It's the warranty for the variant (Estado consistente)

8.2. Item 39: Make defensive copies when needed

8.2.1. You do the job, validate de parameteres, but you allow a parameter be modifiable outside the class

8.2.2. To defense your class make it immutable

8.3. Item 40: Design method signatures carefully

8.3.1. Avoid a long list of parameters

8.3.1.1. Offer more methods with less parameters to do the same job

8.3.1.2. Create a helper class to hold the parameters

8.3.2. Favor interface parameter instead of a class

8.4. Item 41: Use overloading judiciously

8.4.1. When you override a method and call this method from the mother class, the method of the object that will be called.

8.4.2. Try to specify in the name of the method about the parameter. E.g: writeInt ()

8.4.3. Try to put a differente number of parameter in the overloadeds methods

8.4.4. Avoid overload methods with parameters that can be reached by the same call. Like Integer, tha can be reacher by int and Integer

8.5. Item 42: Use varargs judiciously

8.6. Item 43: Return empty arrays or collections, not nulls

8.6.1. When you do that the client doens't need to treat the null return

9. Serialization

9.1. Item 74: Implement Serializable judiciously

9.1.1. Cons of implement serializable

9.1.1.1. Decrease Flexibility. Change the interface change the serial number. Change the interface complicate your client

9.1.1.2. Increase de likelihood of bugs and secutiry. A serializacao nao invoca o construtor, entao a classe pode ficar em um estado invalido.

9.1.1.3. Increase the number of tests. when released a new version of the class. You need to warrant that every old serialized object can be deserilized to the new version of the class

9.2. ITEM 75: CONSIDER USING A CUSTOM SERIALIZED FORM