Effective Java summary By Doo and Cheolho

Effective Java 3/E summary chanpter 9 (Shorter version)

Chanpter 9 : Exceptions

You can find the longer version of this summary here.

When to use?

  • Exception situation other than control flow (normal API should not use Exception)
  • If Exception occurs, that is, the client needs to recover, use checked exception.
  • Use runtime exceptions for Programming errors.

Standard exceptions

IllegalArgumentException : Argument is invalid IllegalStateException : Object state is inappropriate for method execution ConcurrentModificationException : Single threaded design accessed by multiple threads UnsupportedOperationException : When calling an unavailable method NullPointerException : If null is not allowed, but null is entered IndexOutOfBoundsException : When the index range is exceeded

Better exception

  • If low-level exceptions are widespread, high-level exceptions are used.
  • If you want to show low-level exceptions, use exception chaining.
  • If it is difficult to provide information due to exception, use logging.
  • Documentation.
  • Include failure information in detail messages.
  • Maintains the state of the object even if an exception occurs.

Effective Java 3/E summary item 56 to 65 (Longer version)

Item 56: Write doc comments for all exposed API elements

  • The conventions are described in the How to Write Doc Comments web page [Javadoc-guide].
  • To document your API properly, you must precede every exported class, interface, constructor, method, and field declaration with a doc comment.
  • Say what the method does rather than how it does its job.
  • To avoid confusion, no two members or constructors in a class or interface should have the same summary description.
  • Whether or not a class or static method is thread-safe, you should document its thread-safety

Item 57: Minimize the scope of local variables

  • The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.
  • Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.
  • The for loop, in both its traditional and for-each forms, allows you to declare loop variables, limiting their scope to the exact region where they’re needed. Therefore, prefer for loops to while loops, assuming the contents of the loop variable aren’t needed after the loop terminates.
  • keep methods small and focused.

Item 58: Prefer for-each loops to traditional for loops

  • Traditional for-loop has some clutter when iterating over colletion or array. For-each loop does not have them.

Item 59: Know and use the libraries

  • By using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you.
  • every programmer should be familiar with the basics of java.lang, java.util, and java.io, and their subpackages.

Item 60: Avoid float and double if exact answers are required

  • The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.
  • The right way is to use BigDecimal, int, or long for monetary calculations.

Item 61: Prefer primitive types to boxed primitives

  • There are three major differences between primitives and boxed primitives. First, primitives have only their values, whereas boxed primitives have identities distinct from their values. In other words, two boxed primitive instances can have the same value and different identities. Second, primitive types have only fully functional values, whereas each boxed primitive type has one nonfunctional value, which is null, in addition to all the functional values of the corresponding primitive type. Last, primitives are more time- and space-efficient than boxed primitives. All three of these differences can get you into real trouble if you aren’t careful.

Item 62: Avoid strings where other types are more appropriate

  • Strings are designed to represent text, and they do a fine job of it.
  • Strings are poor substitutes for other value types.

Item 63: Beware the performance of string concatenation

  • Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n.
  • To achieve acceptable performance, use a StringBuilder

Item 64: Refer to objects by their interfaces

  • If you get into the habit of using interfaces as types, your program will be much more flexible.

Effective Java 3/E summary chanpter 8 (Shorter version)

Chanpter 8 : General Programming

You can find the longer version of this summary here.

  1. Minimize the scope of local variables
    • Declare a varaible when it is first used
    • Keep methods small and do only one function
  2. Prefer for-each loops to traditional for loops
    • Avoid using for-each loops for Destructive filtering, transfroming, parallel iteration
  3. Know and use the libraries
  4. Avoid float and double if exact answers are required
    • Float and double are designed for scientific and engineering calculations. (Follows IEEE 754 floating point)
    • Use BigDecimal, int or long!
  5. Prefer primitive types to boxed primitives
    • Null safe
    • Use ==
    • Performance
  6. Avoid strings where other types are more appropriate
    • If you use String as a key, it is used globally and is vulnerable to security.
  7. Beware the performance of string concatenation
    • String concatenation is O(n^2)
  8. Refer to objects by their interfaces
    • Declare interface type as possible for params, return, var, field
  9. Prefer interfaces to reflection
    • Reflection: Java code exists in static area as byte code, and constructor, method, and field can be accessed only with the name of the class.
      • No type checking
      • Code smell
      • 11 times slower
    • Use reflection only when creating it, and refer to it by an interface or a higher class.
  10. Avoid using JNI (Java Native Interface)
  11. Don’t optimize, do it when you need it through profiling.

Effective Java 3/E summary chanpter 7 (Shorter version)

Chanpter 7 : Method

You can find the longer version of this summary here.

Parameters

  • Consider protective copied instance to prevent an attack
  • Validation early + Documentation
    • Null check
    • Range check
    • Type check
  • Minimize parameters
    • Highly orthogonal
    • Use static member class
    • Use static member class + Builder pattern
  • Interface is better than Class
  • Enum is better than boolean
  • Avoid overloading when same size of paramters
  • When using varargs, define required params separately
      static int min(int firstArg, int... remainingArgs) { ... }
    

Return

  • Do not return null
  • Return Collections.empty*() replacing null
  • Return Optional<T> when
    • avoiding return null
    • clients need to deal with return value specially

Comments for all exposed API

  • Write WHAT, not HOW
  • Write @params, @return, @throws, postcondition, side effect, thread safety level

Effective Java 3/E summary item 46 to 55 (Longer version)

You can find the shorter version of this summary here.

Item 46: Prefer side-effect-free functions in streams

  • Streams isn’t just an API, it’s a paradigm based on functional programming.

  • The essence of programming stream pipelines is side-effect-free function objects.

Item 47: Prefer Collection to Stream as a return type

  • If an API returns only a stream and some users want to iterate over the returned sequence with a for-each loop, those users will be justifiably upset.

  • The only thing preventing programmers from using a for-each loop to iterate over a stream is Stream’s failure to extend Iterable.

  • But do not store a large sequence in memory just to return it as a collection. If the sequence you’re returning is large but can be represented concisely, consider implementing a special-purpose collection.

Item 48: Use caution when making streams parallel

  • Writing concurrent programs in Java keeps getting easier, but writing concurrent programs that are correct and fast is as difficult as it ever was.

  • Do not parallelize stream pipelines indiscriminately.

  • An acquaintance who maintains a multimillion-line codebase that makes heavy use of streams found only a handful of places where parallel streams were effective.

Item 49: Check parameters for validity

  • Each time you write a method or constructor, you should think about what restrictions exist on its parameters. You should document these restrictions and enforce them with explicit checks at the beginning of the method body.

Item 50: Make defensive copies when needed

  • You must program defensively, with the assumption that clients of your class will do their best to destroy its invariants.

Item 51: Design method signatures carefully

  • Choose method names carefully.

  • Don’t go overboard in providing convenience methods.

  • Avoid long parameter lists. Aim for four parameters or fewer.

  • For parameter types, favor interfaces over classes.

Item 52: Use overloading judiciously

  • You should avoid confusing uses of overloading.

  • A safe, conservative policy is never to export two overloadings with the same number of parameters.

Item 53: Use varargs judiciously

  • varargs are effective in circumstances where you want a method with a variable number of arguments, but every invocation of a varargs method causes an array allocation and initialization.

Item 54: Return empty collections or arrays, not nulls

  • Never return null in place of an empty array or collection. It makes your API more difficult to use and more prone to error, and it has no performance advantages.

Item 55: Return optionals judiciously

  • If you find yourself writing a method that can’t always return a value and you believe it is important that users of the method consider this possibility every time they call it, then you should probably return an optional.

  • Container types, including collections, maps, streams, arrays, and optionals should not be wrapped in optionals.

  • You should be aware that there are real performance consequences associated with returning optionals; for performance-critical methods, it may be better to return a null or throw an exception.

  • You should rarely use an optional in any other capacity than as a return value.