Effective Java

Jetzt loslegen. Gratis!
oder registrieren mit Ihrer E-Mail-Adresse
Effective Java von Mind Map: Effective Java

1. 1 - Creating and destroying objects

1.1. 7 - Avoid Finalizers

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

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

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

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

2. 3 - Methods Commons to all objects

2.1. 8: Obey the general contract when overriding equals

2.1.1. When possible use equals from Object Each instance of the class is unique The class doesn't need logical equality The superclass already overriden de equals The equals never will be invoked

2.1.2. Value Class are candidates for overridding

2.1.3. Equals Contract Reflexive: x.equals(x) == true Symmetric: x.equals(y) == y.equals(x) Transitive: if x.equals(y) == true && y.equals(z) Then x.equals(z) == true Consistency - Multiple invocation of x.equals(y) should return the same value Null: x.equals(null) should return false

2.1.4. Recipe for Equals method Uss o == this to check if it is the same isntance Use o instance of "Class". Se o é nulo retorna falso. Cast the parameter to the correct type Check each field Use == for primitive, but double and float double and float use Double.compare e Float.compare Use equals recursively for objects Compare first fields that are more likely to differ, Write unit test to check the contract

2.2. 9 - Always override HashCode when you override Equals

2.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.

2.2.2. HashCode Contract Return the same result whenever it's invoked for the same object If two objects are "Equals" they must return the same hash Unequal objects could return the same hash

2.3. 10 - Always Override toString

2.3.1. Nothing to say....

2.4. 11 - Override Clone Judisciously

2.4.1. Cloneable says that a class can be cloned If the class doesn't implement the interface a exception will be throwed when clone is invoked

2.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.

2.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

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

2.5. 12 - Consider implementing Comparable

2.5.1. Permits order and equality comparisom

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

2.5.3. Contract 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. 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. All objects that compare as equal must yield the same results when compared to any other object. 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.

2.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;

3. 4 - Classes and Interfaces

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

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

3.1.2. Minimize visibility as much as you can

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

3.3. Item 15: Minimize mutability

3.3.1. Rules for make an immutable class Don't provide setter methods make the class final Make all fields final Make all fields private Take care of mutable fields. Make defensive copies

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

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

3.4. Item 16: Favor composition over inheritance

3.4.1. Problems with inherintance Mudanças na classe mãe impactam a classe filha Um método novo na classe mãe com assinatura parecida na classe filha pode fazer com que a classe filha deixe de compilar Violates encapsulation

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

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

3.5.1. Never invoke a overridable method from a superclass constructor

3.6. Item 19 - Use interfaces only to define types

3.6.1. Don't use interfaces to define constants

3.6.2. Define contants in a class

3.7. Item 20: Prefer class hierarchies to tagged classes

3.8. Item 21: Use function objects to represent strategies

3.9. Item 22: Favor static member classes over nonstatic

4. 5 - Generics

4.1. 24: Eliminate Unchecked Warnings

4.1.1. You know the reason of the warning? Put a @SupressWarning <== Yes Put in a little scope possible Do your best to eliminate it <== No

4.2. 25 - Prefer Lists to Arrays

4.2.1. Arrays are covariants Sub is a subtype of Super, So...Sub[] is a subtype of Super[].

4.2.2. Generics are invariants

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

4.3. 26: Favor generic types

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

4.4.1. You use the wildcard to let an hierarchy of objects be used extends: The class and the classes below(abaixo) super: The class and classes above(acima)

5. 6 - Enuns e Annotations

5.1. Item 30: Use enums instead of int constants

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

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

5.2. Item 31: Use instance fields instead of ordinals

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

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

5.3. Item 34: Emulate extensible enums with interfaces

5.3.1. An Enum can implement an interface

5.3.2. They can't be extended

5.4. Item 35: Prefer annotations to naming patterns

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

5.5. Item 36: Consistently use the Override annotation

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

6. 7 - Methods

6.1. Item 38: Check parameters for validity

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

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

6.2. Item 39: Make defensive copies when needed

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

6.2.2. To defense your class make it immutable

6.3. Item 40: Design method signatures carefully

6.3.1. Avoid a long list of parameters Offer more methods with less parameters to do the same job Create a helper class to hold the parameters

6.3.2. Favor interface parameter instead of a class

6.4. Item 41: Use overloading judiciously

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

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

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

6.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

6.5. Item 42: Use varargs judiciously

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

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

7. 8 - General Programming

7.1. Item 45: Minimize the scope of local variables

7.1.1. Prefer foor loops intead of while one

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

7.3. Item 55: Optimize judiciously

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

7.4. Item 56: Adhere to generally accepted naming conventions

8. 9 - Exception

8.1. Item 57: Use exceptions only for exceptional conditions

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

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

8.3. Item 59: Avoid unnecessary use of checked exceptions

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

8.4. Item 60: Favor the use of standard exceptions

8.4.1. Try to reuse the unchecked exceptions defined by java Turn you API easy to learn and read, because is familimar The class loader please, because he needs to deal with few class derived by RuntimeExceptions

8.5. Item 61: Throw exceptions appropriate to the abstraction

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

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

8.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.

8.7. Item 64: Strive for failure atomicity

8.7.1. If an exception occurs the object should be returned to the state that it was prior to the invocation. Validate the parameters before alter the object Put any code tha can fail before the part to alter the object If the object was already altered, get the original ones in the BD, 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

8.8. Item 65: Don’t ignore exceptions

8.8.1. You never should have a empty catch block.

9. Serialization

9.1. Item 74: Implement Serializable judiciously

9.1.1. Cons of implement serializable Decrease Flexibility. Change the interface change the serial number. Change the interface complicate your client Increase de likelihood of bugs and secutiry. A serializacao nao invoca o construtor, entao a classe pode ficar em um estado invalido. 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