毕业论文外文翻译Effectjava.docx

上传人:b****5 文档编号:29853279 上传时间:2023-07-27 格式:DOCX 页数:12 大小:27.41KB
下载 相关 举报
毕业论文外文翻译Effectjava.docx_第1页
第1页 / 共12页
毕业论文外文翻译Effectjava.docx_第2页
第2页 / 共12页
毕业论文外文翻译Effectjava.docx_第3页
第3页 / 共12页
毕业论文外文翻译Effectjava.docx_第4页
第4页 / 共12页
毕业论文外文翻译Effectjava.docx_第5页
第5页 / 共12页
点击查看更多>>
下载资源
资源描述

毕业论文外文翻译Effectjava.docx

《毕业论文外文翻译Effectjava.docx》由会员分享,可在线阅读,更多相关《毕业论文外文翻译Effectjava.docx(12页珍藏版)》请在冰豆网上搜索。

毕业论文外文翻译Effectjava.docx

毕业论文外文翻译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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 考试认证 > 交规考试

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1