毕业论文外文翻译Effectjava.docx
《毕业论文外文翻译Effectjava.docx》由会员分享,可在线阅读,更多相关《毕业论文外文翻译Effectjava.docx(12页珍藏版)》请在冰豆网上搜索。
毕业论文外文翻译Effectjava
外文资料
《Effectjava》
1.AlwaysOverrideHashCodeWhenYouOverrideEquals
AcommonsourceofbugsisthefailuretooverridethehashCodemethod.YoumustoverridehashCodeineveryclassthatoverridesequals.FailuretodosowillresultinaviolationofthegeneralcontractforObject.hashCode,whichwillpreventyourclassfromfunctioningproperlyinconjunctionwithallhash-basedcollections,includingHashMap,HashSet,andHashtable.
Hereisthecontract,copiedfromtheObjectspecification[JavaSE6]:
(1)Wheneveritisinvokedonthesameobjectmorethanonceduringanexecutionofanapplication,thehashCodemethodmustconsistentlyreturnthesameinteger,providednoinformationusedinequalscomparisonsontheobjectismodified.Thisintegerneednotremainconsistentfromoneexecutionofanapplicationtoanotherexecutionofthesameapplication.
(2)Iftwoobjectsareequalaccordingtotheequals(Object)method,thencallingthehashCodemethodoneachofthetwoobjectsmustproducethesameintegerresult.
(3)Itisnotrequiredthatiftwoobjectsareunequalaccordingtotheequals(Object)method,thencallingthehashCodemethodoneachofthetwoobjectsmustproducedistinctintegerresults.However,theprogrammershouldbeawarethatproducingdistinctintegerresultsforunequalobjectsmayimprovetheperformanceofhashtables.
ThekeyprovisionthatisviolatedwhenyoufailtooverridehashCodeisthesecondone:
equalobjectsmusthaveequalhashcodes.Twodistinctinstancesmaybelogicallyequalaccordingtoaclass’sequalsmethod,buttoObject’shashCodemethod,they’rejusttwoobjectswithnothingmuchincommon.ThereforeObject’shashCodemethodreturnstwo
seeminglyrandomnumbersinsteadoftwoequalnumbersasrequiredbythecontract.
2.AlwaysOverridetoString
Whilejava.lang.ObjectprovidesanimplementationofthetoStringmethod,thestringthatitreturnsisgenerallynotwhattheuserofyourclasswantstosee.Itconsistsoftheclassnamefollowedbyan“at”sign(@)andtheunsignedhexadecimalrepresentationofthehashcode.ThegeneralcontractfortoStringsaysthatthereturnedstringshouldbe“aconcisebutinformativerepresentationthatiseasyforapersontoread”[JavaSE6].Whileitcouldbearguedthat“PhoneNumber@163b91”isconciseandeasytoread,itisn’tveryinformativewhencomparedto“(707)867-5309.”ThetoStringcontractgoesontosay,“Itisrecommendedthatallsubclassesoverridethismethod.”Goodadvice,indeed!
Whileitisn’tasimportantasobeyingtheequalsandhashCodecontracts,providingagoodtoStringimplementationmakesyourclassmuchmorepleasanttouse.ThetoStringmethodisautomaticallyinvokedwhenanobjectispassedtoprintln,printf,thestringconcatenationoperator,orassert,orprintedbyadebugger.
Ifyou’veprovidedagoodtoStringmethodforPhoneNumber,generatinga
usefuldiagnosticmessageisaseasyasthis:
System.out.println("Failedtoconnect:
"+phoneNumber);
ProgrammerswillgeneratediagnosticmessagesinthisfashionwhetherornotyouoverridetoString,butthemessageswon’tbeusefulunlessyoudo.ThebenefitsofprovidingagoodtoStringmethodextendbeyondinstancesoftheclasstoobjectscontainingreferencestotheseinstances,especiallycollections.Whichwouldyouratherseewhenprintingamap,“Jenny=PhoneNumber@163b91”or“Jenny=(707)867-5309”?
Whenpractical,thetoStringmethodshouldreturnalloftheinterestinginformationcontainedintheobject,asinthephonenumberexamplejustshown.Itisimpracticalifthe
objectislargeorifitcontainsstatethatisnotconducivetostringrepresentation.Underthesecircumstances,toStringshouldreturnasummarysuchas“Manhattanwhitepages(1487536listings)”or“Thread[main,5,main]”.Ideally,thestringshouldbeself-explanatory.(TheThreadexampleflunksthistest.)
Oneimportantdecisionyou’llhavetomakewhenimplementingatoStringmethodiswhethertospecifytheformatofthereturnvalueinthedocumentation.Itisrecommendedthatyoudothisforvalueclasses,suchasphonenumbersormatrices.Theadvantageofspecifyingtheformatisthatitservesasastandard,unambiguous,human-readablerepresentationoftheobject.Thisrepresentationcanbeusedforinputandoutputandinpersistenthuman-readabledataobjects,suchasXMLdocuments.Ifyouspecifytheformat,it’susuallyagoodideatoprovideamatchingstaticfactoryorconstructorsoprogrammerscaneasilytranslatebackandforthbetweentheobjectanditsstringrepresentation.ThisapproachistakenbymanyvalueclassesintheJavaplatformlibraries,includingBigInteger,BigDecimal,andmostoftheboxedprimitiveclasses.
ThedisadvantageofspecifyingtheformatofthetoStringreturnvalueisthatonceyou’vespecifiedit,you’restuckwithitforlife,assumingyourclassiswidelyused.Programmerswillwritecodetoparsetherepresentation,togenerateit,andtoembeditintopersistentdata.Ifyouchangetherepresentationinafuturerelease,you’llbreaktheircodeanddata,andtheywillyowl.Byfailingtospecifyaformat,youpreservetheflexibilitytoaddinformationorimprovetheformatinasubsequentrelease.
Whetherornotyoudecidetospecifytheformat,youshouldclearlydocumentyourintentions.Ifyouspecifytheformat,youshoulddosoprecisely.Whetherornotyouspecifytheformat,provideprogrammaticaccesstoalloftheinformationcontainedinthevaluereturnedbytoString.Forexample,thePhoneNumberclassshouldcontainaccessorsfortheareacode,prefix,andlinenumber.Ifyoufailtodothis,youforceprogrammerswhoneedthisinformationtoparsethestring.Besidesreducingperformanceandmakingunnecessaryworkforprogrammers,thisprocessiserror-proneandresultsinfragilesystemsthatbreakif
youchangetheformat.Byfailingtoprovideaccessors,youturnthestringformatintoadefactoAPI,evenifyou’vespecifiedthatit’ssubjecttochange.
3.MinimizetheAccessibilityofClassesandMembers
Thesinglemostimportantfactorthatdistinguishesawell-designedmodulefroma
poorlydesignedoneisthedegreetowhichthemodulehidesitsinternaldataandotherimplementationdetailsfromothermodules.Awell-designedmodulehidesallofitsimplementationdetails,cleanlyseparatingitsAPIfromitsimplementation.ModulesthencommunicateonlythroughtheirAPIsandareoblivioustoeachothers’innerworkings.Thisconcept,knownasinformationhidingorencapsulation,isoneofthefundamentaltenetsofsoftwaredesign[Parnas72].
Informationhidingisimportantformanyreasons,mostofwhichstemfromthefactthatitdecouplesthemodulesthatcompriseasystem,allowingthemtobedeveloped,tested,optimized,used,understood,andmodifiedinisolation.Thisspeedsupsystemdevelopmentbecausemodulescanbedevelopedinparallel.Iteasestheburdenofmaintenancebecausemodulescanbeunderstoodmorequicklyanddebuggedwithlittlefearofharmingothermodules.Whileinformationhidingdoesnot,inandofitself,causegoodperformance,itenableseffectiveperformancetuning:
onceasystemiscompleteandprofilinghasdeterminedwhichmodulesarecausingperformanceproblems(Item55),thosemodulescanbeoptimizedwithoutaffectingthecorrectnessofothermodules.Informationhidingincreasessoftwarereusebecausemodulesthataren’ttightlycoupledoftenproveusefulinothercontextsbesidestheonesforwhichtheyweredeveloped.
Finally,informationhidingdecreasestheriskinbuildinglargesystems,because
individualmodulesmayprovesuccessfulevenifthesystemdoesnot.Javahasmanyfacilitiestoaidininformationhiding.Theaccesscontrolmechanism[JLS,6.6]specifiestheaccessibilityofclasses,interfaces,andmembers.Theaccessibilityofanentityisdeterminedbythelocationofitsdeclarationandbywhich,ifany,oftheaccessmodifiers(private,protected,andpublic)ispresentonthedeclaration.Properuseofthesemodifiersisessentialtoinformationhiding.
Theruleofthumbissimple:
makeeachclassormemberasinaccessibleaspossible.Inotherwords,usethelowestpossibleaccesslevelconsistentwiththeproperfunctioningofthesoftwarethatyouarewriting.Fortop-level(non-nested)classesandinterfaces,thereareonlytwopossibleaccesslevels:
package-privateandpublic.Ifyoudeclareatop-levelclassorinterfacewiththepublicmodifier,itwillbepublic;otherwise,itwillbepackage-private.Ifatop-levelclassorinterfacecanbemadepackage-private,itshouldbe.Bymakingitpackage-private,youmakeitpartoftheimplementationratherthantheexportedAPI,andyoucanmodifyit,replaceit,oreliminateitinasubsequentreleasewithoutfearofharmingexistingclients.Ifyoumakeitpublic,youareobligatedtosupportitforevertomaintaincompatibility.
Ifapackage-privatetop-levelclass(orinterface)isusedbyonlyoneclass,considermakingthetop-levelclassaprivatenestedclassofthesoleclassthatusesit(Item22).Thisreducesitsaccessibilityfromalltheclassesinitspackagetotheoneclassthatusesit.Butitisfarmoreimportanttoreducetheaccessibilityofagratuitouslypublicclassthanofapackage-privatetop-levelclass:
thepublicclassispartofthepackage’sAPI,whilethepackage-privatetop-levelclassisalreadypartofitsimplementation.
Aftercarefullydesigningyourclass’spublicAPI,yourreflexshouldbetomakeallothermembersprivate.Onlyifanotherclassinthesamepackagereallyneedstoaccessamembershouldyouremovetheprivatemodifier,makingthememberpackage-private.Ifyoufindyourselfdoingthisoften,youshouldreexaminethedesignofyo