effective java 笔记

Creating and Destroying Objects

Item 1: Consider static factory methods instead of constructors

advantage

  • they have names.
  • they are not required to create a new object each time they’re invoked.
  • they can return an object of any subtype of their return type.
  • the class of the returned object can vary from call to call as a function of the input parameters.
  • the class of the returned object need not exist when the class containing the method is written.

disadvantage

  • classes without public or protected constructors cannot be subclassed.(using composite)
  • they are hard for programmers to find.(java tools, and good name)

eg:


image.png

Item 2: Consider a builder when faced with many constructor parameters

the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if many of the parameters are optional or of identical type.

performance

Item 3: Enforce the singleton property with a private constructor or an enum type

it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation.

enum type is often the best way to implement a singleton.(static final)

image.png
image.png

Item 4: Enforce noninstantiability with a private constructor

image.png

Item 5: Prefer dependency injection to hardwiring resources

image.png

Item 6: Avoid creating unnecessary objects

image.png

Item 7: Eliminate obsolete object references

image.png

Item 8: Avoid finalizers and cleaners

Cleaners are less dangerous than finalizers, but still unpredictable, slow, and generally unnecessary.

There is a severe performance penalty for using finalizers and cleaners.

Just have your class implement AutoCloseable

image.png

Item 9: Prefer try-with-resources to try-finally

image.png

Methods Common to All Objects

Item 10: Obey the general contract when overriding equals

Item 11: Always override hashCode when you override equals

https://blog.csdn.net/wangyunpeng0319/article/details/74156934

Item 12: Always override toString

Item 13: Override clone judiciously

https://blog.csdn.net/bigconvience/article/details/25025561

Item 14:Consider implementing Comparable

Classes and Interfaces

Item 15: Minimize the accessibility of classes and members

make each class or member as inaccessible as possible.

Item 16: In public classes, use accessor methods, not public fields

Item 17: Minimize mutability

To make a class immutable, follow these five rules:(Immutable objects are inherently thread-safe)

  1. Don’t provide methods that modify the object’s state (known as mutators).

  2. Ensure that the class can’t be extended.

  3. Make all fields final.

  4. Make all fields private.

  5. Ensure exclusive access to any mutable components.

Item 18: Favor composition over inheritance

inheritance violates encapsulation

Item 19: Design and document for inheritance or else prohibit it

the class must document its self-use of overridable methods.

Item 20: Prefer interfaces to abstract classes

Item 21: Design interfaces for posterity

Item 22: Use interfaces only to define types

Item 23: Prefer class hierarchies to tagged classes

Item 24: Favor static member classes over nonstatic

Item 25: Limit source files to a single top-level class

Item 26: Don’t use raw types

If you use raw types, you lose all the safety and expressiveness benefits of generics.

Item 27: Eliminate unchecked warnings

If you can’t eliminate a warning, but you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning

with an @SuppressWarnings("unchecked") annotation.

Item 28: Prefer lists to arrays

Arrays are

covariant and reified; generics are invariant and erased. As a consequence, arrays

provide runtime type safety but not compile-time type safety, and vice versa for

generics.

Item 29: Favor generic types

generic types are safer and easier to use than types that require

casts in client code.

Item 30: Favor generic methods

Item 31: Use bounded wildcards to increase API flexibility

PECS stands for producer-extends, consumer-super. (super: 当前类或则父类, extends:当前类或者子类)

eg:

public static <T> void copy(List<? super T> dest,List<? extends T> src)

在<code>src</code>中,我们可以传入与<code>T</code>类型相关的<code>List</code>,并且能够保证取出的是<code>T</code>类型或者<code>T</code>的子类型的值。

在<code>dest</code>中,我们可以传入<code>T</code>类型和<code>T</code>的父类的<code>List</code>,并且能够保证我们从存放的值都满足要求

Item 32: Combine generics and varargs judiciously ?

Item 33: Consider typesafe heterogeneous containers?

Enums and Annotations

Item 34: Use enums instead of int constants

Item 35: Use instance fields instead of ordinals

Item 36: Use EnumSet instead of bit fields

Item 37: Use EnumMap instead of ordinal indexing

Item 38: Emulate extensible enums with interfaces

Item 39: Prefer annotations to naming patterns

Item 40: Consistently use the Override annotation

Item 41: Use marker interfaces to define types

Lambdas and Streams

Item 42: Prefer lambdas to anonymous classes

Item 43: Prefer method references to lambdas

Item 44: Favor the use of standard functional interfaces

Item 45: Use streams judiciously

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

Item 47: Prefer Collection to Stream as a return type

Item 48: Use caution when making streams parallel

Methods

Item 49: Check parameters for validity

Item 50: Make defensive copies when needed

保护性复制,防止变量被修改,date

Item 51: Design method signatures carefully

Choose method names carefully.

Don’t go overboard in providing convenience methods.

Avoid long parameter lists.

For parameter types, favor interfaces over classes

Prefer two-element enum types to boolean parameters,

Item 52: Use overloading judiciously

overloaded methods is static, while selection among overridden methods is dynamic.

Item 53: Use varargs judiciously

Item 54: Return empty collections or arrays, not nulls

Item 55: Return optionals judiciously

Item 56: Write doc comments for all exposed API elements

General Programming

Item 57: Minimize the scope of local variables

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

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.

java.lang, java.util, and java.io, java.util.concurrent...

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

Item 61: Prefer primitive types to boxed primitives

Item 62: Avoid strings where other types are more appropriate

Item 63: Beware the performance of string concatenation

Item 64: Refer to objects by their interfaces

Item 65: Prefer interfaces to reflection

Item 66: Use native methods judiciously

Item 67: Optimize judiciously

Item 68: Adhere to generally accepted naming conventions

Exceptions

Item 69: Use exceptions only for exceptional conditions

Item 70: Use checked exceptions for recoverable conditions and

runtime exceptions for programming errors

Item 71: Avoid unnecessary use of checked exceptions

Item 72: Favor the use of standard exceptions

Item 73: Throw exceptions appropriate to the abstraction

Item 74: Document all exceptions thrown by each method

Item 75: Include failure-capture information in detail messages

Item 76: Strive for failure atomicity

Item 77: Don’t ignore exceptions

Concurrency

Item 78: Synchronize access to shared mutable data

when multiple threads share mutable data, each thread that

reads or writes the data must perform synchronization.

Item 79: Avoid excessive synchronization

Item 80: Prefer executors, tasks, and streams to threads

Item 81: Prefer concurrency utilities to wait and notify

Item 82: Document thread safety

Item 83: Use lazy initialization judiciously

Item 84: Don’t depend on the thread scheduler

Serialization

Item 85: Prefer alternatives to Java serialization

Item 86: Implement Serializable with great caution

Item 87: Consider using a custom serialized form

Item 88: Write readObject methods defensively

Item 89: For instance control, prefer enum types to readResolve

Item 90: Consider serialization proxies instead of serialized
instances

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,686评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,668评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,160评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,736评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,847评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,043评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,129评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,872评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,318评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,645评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,777评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,861评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,589评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,687评论 2 351

推荐阅读更多精彩内容