Effective Java - Gbv.de

Transcription

Effective JavaThird EditionJoshua BlochVAddison-WesleyBostonDubai ColumbusLondon IndianapolisMadridSao Paulo MilanSydney New YorkMunich Hong Kong San FranciscoParis MontrealSeoul AmsterdamTorontoSingapore Taipei Delhi Cape Town TokyoMexicoCity

ntroduction2Creatingand15Destroying ObjectsItem 1:Consider staticItem 2:Considerafactory methods instead of constructors.builder when faced with many10parametersItem 3:Enforce thesingleton property withaprivateconstructor17oranenumtypeItem 7:Item 8:Avoid finalizers and cleanersItem 9:PreferItem 5:Item 6:3withnoninstantiabilityprivatePrefer dependency injection to hardwiring resourcesAvoid creating unnecessary objectsEliminate obsolete object referencesItem 4:Enforcetry-with-resourcesMethods Common to Allto taconstructor.19.20222629ry-f i nal 1 y3437ObjectsObey the general contract when overriding equal sItem 11: Always override hashCode when you override equalItem 12: Always override toStri ng37Item 10:Item 13: Override cloneItem 14: Consider45constructorjudiciouslyimplementing ComparableClasses and Interfacess.505558667373accessibility of classes and membersfields78notuseaccessormethods,Item 16: In public classes,public80Item 17: Minimize mutabilityItem 15: Minimize theItem 18: Favorcomposition over inheritance87

viiiCONTENTSItem 19:Design and document for inheritanceorelseprohibitit99Item 20: Prefer interfaces to abstract classesDesign interfaces for posterityItem 22: Use interfaces only to define typesItem 23: Prefer class hierarchies to tagged classes104Item 24: Favor static member classes112Item 21:Item 25: Limit5filessourceto aover107109nonstaticsingle top-level class115117GenericsItem 26: Don'tuse raw117typesItem 27: Eliminate unchecked warnings123Item 28: Prefer lists126toarrays130Item 29: Favorgeneric typesItem 30: Favor generic methods135Item 31: Use bounded wildcardsItemto increase APIflexibilityand varargsItem 32: Combine6genericsjudiciously33: Consider typesafe heterogeneous containersenums.139146151157Enums and AnnotationsItem 34: Useinstead of i157nt constantsItem 35: Use instance fields instead of ordinals168Item 36: Use EnumSet instead of bit fields169EnumMap instead of ordinal indexingItem 38: Emulate extensible enums with interfaces171Item 39: Prefer annotations to180Item 37: UseItem 40:Consistentlyusenaming patternsthe Overi de annotationrItem 41: Use marker interfaces to define793193Item 42: Prefer lambdas to anonymous classesItem 44: Favor theItem 45: Useusestreams188191typesLambdas and StreamsItem 43: Prefer method references176to193lambdas197of standard functional interfaces199203judiciouslyItem 46: Prefer side-effect-free functions in streams210Item 47: Prefer Collection to Stream216Item 48: Use caution whenmakingas a returnstreamstypeparallel222

CONTENTS8Methods227Item 49: Check parameters forItem 50: Make defensiveItem 51:validity227copies when needed231methodDesignsignatures carefullyoverloading judiciouslyItem 53: Use varargs judiciously236Item 52: UseItem 54: Return empty collectionsItem 55: Returnorarrays,238245not nullsoptionals judiciouslycomments for all exposed APIItem 56: Write doc9General247249elementsProgrammingItem 59: Know andItem 60: Avoid f 1Item 61: PreferItem 62: Avoiduse261264loopsthe libraries267oat and doubl e if exact answers areprimitive typesstrings254261Item 57: Minimize the scope of local variablesItem 58: Prefer for-each loops to traditional forto boxedwhere otherrequired. 270273primitivesappropriatetypesperformance of string concatenationobjects by their interfacesare more.276Item 63: Beware the279Item 64: Refer to280Item 65: Prefer interfaces to reflectionItem 66: Use native methodsItem 67:Item 68:10.282judiciouslyOptimize judiciouslyAdhere to generally accepted naming285286conventionsExceptions289293Item 69: UseItem 70:Item 71:293exceptions only for exceptional conditionsUse checked exceptions for recoverable conditions andruntime exceptions for programming errors296Avoid unnecessary use of checked exceptions298Item 72: Favor theuseof standardexceptionsItem 73: Throw300to the abstraction302exceptions appropriatethrowneachmethod304exceptionsbyInclude failure-capture information in detail messages. 306Item 74: Document allItem 75:Item 76: Strive for failureItem 77: Don'tatomicityignore exceptions308310ix

XCONTENTS11311ConcurrencyItem 78:SynchronizeaccessItem 79: Avoid excessiveto shared mutable data311317synchronizationItem 80: Prefer executors, tasks, andItem 81: Prefer concurrency utilitiesstreams tothreadsto wai t and notify323325Item 82: Document thread330Item333Itemsafety83: Use lazy initialization judiciously84: Don't depend on the thread scheduler33612 Serialization339Item 85: Prefer alternatives to Java serializationItem 86:ImplementItem 87: ConsiderItem 88: WriteSen' al i zablusinga custom339with great cautionserialized formereadObject methods defensivelyItem 89: For instance control,preferenumtypes353359Item 90: Consider serializationproxiesinstead of eItems343to Second Edition367References371Index377

Effective Java ThirdEdition JoshuaBloch VAddison-Wesley Boston Columbus Indianapolis NewYork San Francisco Amsterdam CapeTown Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi MexicoCity SaoPaulo Sydney HongKong Seoul Singapore Taipei Tokyo. Contents Foreword xi Preface xiii Acknowledgments xvii 1 .