What is a good use case for static import of methods? - Stack ...
文章推薦指數: 80 %
For example methods from java.lang.Math and java.awt.Color. But if abs and getAlpha are not ambiguous I don't see why readEmployee is. As in lot ...
Home
Public
Questions
Tags
Users
Collectives
ExploreCollectives
FindaJob
Jobs
Companies
Teams
StackOverflowforTeams
–Collaborateandshareknowledgewithaprivategroup.
CreateafreeTeam
WhatisTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Whatisagoodusecaseforstaticimportofmethods?
AskQuestion
Asked
13yearsago
Active
5monthsago
Viewed
99ktimes
149
47
Justgotareviewcommentthatmystaticimportofthemethodwasnotagoodidea.ThestaticimportwasofamethodfromaDAclass,whichhasmostlystaticmethods.SoinmiddleofthebusinesslogicIhadadaactivitythatapparentlyseemedtobelongtothecurrentclass:
importstaticsome.package.DA.*;
classBusinessObject{
voidsomeMethod(){
....
save(this);
}
}
ThereviewerwasnotkeenthatIchangethecodeandIdidn'tbutIdokindofagreewithhim.Onereasongivenfornotstatic-importingwasitwasconfusingwherethemethodwasdefined,itwasn'tinthecurrentclassandnotinanysuperclasssoittoosometimetoidentifyitsdefinition(thewebbasedreviewsystemdoesnothaveclickablelinkslikeIDE:-)Idon'treallythinkthismatters,static-importsarestillquitenewandsoonwewillallgetusedtolocatingthem.
Buttheotherreason,theoneIagreewith,isthatanunqualifiedmethodcallseemstobelongtocurrentobjectandshouldnotjumpcontexts.Butifitreallydidbelong,itwouldmakesensetoextendthatsuperclass.
So,whendoesitmakesensetostaticimportmethods?Whenhaveyoudoneit?Did/doyoulikethewaytheunqualifiedcallslook?
EDIT:Thepopularopinionseemstobethatstatic-importmethodsifnobodyisgoingtoconfusethemasmethodsofthecurrentclass.Forexamplemethodsfromjava.lang.Mathandjava.awt.Color.ButifabsandgetAlphaarenotambiguousIdon'tseewhyreadEmployeeis.Asinlotofprogrammingchoices,Ithinkthistooisapersonalpreferencething.
javastatic-import
Share
Follow
editedJul29'21at7:21
JacobvanLingen
7,98766goldbadges4141silverbadges7272bronzebadges
askedJan7'09at15:46
MiserableVariableMiserableVariable
27.7k1414goldbadges7070silverbadges126126bronzebadges
2
2
Hereisverygoodusageofstaticimports:ibm.com/developerworks/library/j-ft18
– intrepidis
Jun26'13at17:39
2
@mr5thesyntaxisimportstatic,thefeatureisstaticimport
– MiserableVariable
Mar16'18at0:11
Addacomment
|
16Answers
16
Active
Oldest
Votes
162
ThisisfromSun'sguidewhentheyreleasedthefeature(emphasisinoriginal):
Sowhenshouldyouusestaticimport?Verysparingly!Onlyuseitwhenyou'dotherwisebetemptedtodeclarelocalcopiesofconstants,ortoabuseinheritance(theConstantInterfaceAntipattern)....Ifyouoverusethestaticimportfeature,itcanmakeyourprogramunreadableandunmaintainable,pollutingitsnamespacewithallthestaticmembersyouimport.Readersofyourcode(includingyou,afewmonthsafteryouwroteit)willnotknowwhichclassastaticmembercomesfrom.Importingallofthestaticmembersfromaclasscanbeparticularlyharmfultoreadability;ifyouneedonlyoneortwomembers,importthemindividually.
(https://docs.oracle.com/javase/8/docs/technotes/guides/language/static-import.html)
TherearetwopartsIwanttocalloutspecifically:
Usestaticimportsonlywhenyouweretemptedto"abuseinheritance".Inthiscase,wouldyouhavebeentemptedtohaveBusinessObjectextendsome.package.DA?Ifso,staticimportsmaybeacleanerwayofhandlingthis.Ifyouneverwouldhavedreamedofextendingsome.package.DA,thenthisisprobablyapooruseofstaticimports.Don'tuseitjusttosaveafewcharacterswhentyping.
Importindividualmembers.Sayimportstaticsome.package.DA.saveinsteadofDA.*.Thatwillmakeitmucheasiertofindwherethisimportedmethodiscomingfrom.
Personally,Ihaveusedthislanguagefeatureveryrarely,andalmostalwaysonlywithconstantsorenums,neverwithmethods.Thetrade-off,forme,isalmostneverworthit.
Share
Follow
editedFeb22'18at15:33
ktulinho
3,58288goldbadges2525silverbadges3333bronzebadges
answeredJan7'09at17:01
RossRoss
9,16888goldbadges3434silverbadges3535bronzebadges
2
9
Agreed.I'veusedstaticimportsveeeryoccasionallywherethey'veactuallymadethecodesignificantlyeasiertofollow.
– NeilCoffey
Jan7'09at17:36
2
IliketousethemwithCollectorsandstreams.IfeelaStream.collect(toSet())ismorereadablethanaStream.collect(Collectors.toSet()).Wouldthisbeconsideredanappropriateuse?
– Snap
Nov3'20at17:48
Addacomment
|
67
AnotherreasonableuseforstaticimportsiswithJUnit4.InearlierversionsofJUnitmethodslikeassertEqualsandfailwereinheritedsincethetestclassextendedjunit.framework.TestCase.
//oldway
importjunit.framework.TestCase;
publicclassMyTestClassextendsTestCase{
publicvoidmyMethodTest(){
assertEquals("foo","bar");
}
}
InJUnit4,testclassesnolongerneedtoextendTestCaseandcaninsteaduseannotations.Youcanthenstaticallyimporttheassertmethodsfromorg.junit.Assert:
//newway
importstaticorg.junit.Assert.assertEquals;
publicclassMyTestClass{
@TestpublicvoidmyMethodTest(){
assertEquals("foo","bar");
//insteadof
Assert.assertEquals("foo","bar");
}
}
JUnitdocumentsusingitthisway.
Share
Follow
answeredJan7'09at18:32
RobHruskaRobHruska
114k2828goldbadges163163silverbadges188188bronzebadges
2
5
I'dagree.Simplifyingtestcasesisoneplacewheretheintentisunlikelytobemisunderstood.
– BillMichell
Jan9'09at11:10
6
We'vehadthisonourprojectandactuallyhadissueswithpeopleusingassert()andincorrectlythinkingthatitcomesfromtheirstaticimportoftheAssertpackage.Oncewefoundthisproblem,aquickscanofourcode-basefoundaround30instancesofthisinourtestsmeaningthat30assertionswereNOTbeingrunwhenthetestframeworkwasexecutedbecausetheDEBUGflagisn'tsetwhenweruntests.
– ChrisWilliams
Dec3'13at18:49
Addacomment
|
30
EffectiveJava,SecondEdition,attheendofItem19notesthatyoucanusestaticimportsifyoufindyourselfheavilyusingconstantsfromautilityclass.Ithinkthisprinciplewouldapplytostaticimportsofbothconstantsandmethods.
importstaticcom.example.UtilityClassWithFrequentlyUsedMethods.myMethod;
publicclassMyClass{
publicvoiddoSomething(){
intfoo=UtilityClassWithFrequentlyUsedMethods.myMethod();
//Canbewrittenlessverboselyas
intbar=myMethod();
}
}
Thishasadvantagesanddisadvantages.Itmakesthecodeabitmorereadableattheexpenseoflosingsomeimmediateinformationaboutwherethemethodisdefined.However,agoodIDEwillletyougotothedefinition,sothisisn'tmuchofanissue.
Youshouldstillusethissparingly,andonlyifyoufindyourselfusingthingsfromtheimportedfilemany,manytimes.
Edit:Updatedtobemorespecifictomethods,asthat'swhatthisquestionisreferringto.Theprincipleappliesregardlessofwhat'sbeingimported(constantsormethods).
Share
Follow
editedJan14'21at12:38
Lii
10.5k77goldbadges5656silverbadges7575bronzebadges
answeredJan7'09at18:20
RobHruskaRobHruska
114k2828goldbadges163163silverbadges188188bronzebadges
5
1
Myquestionisaboutstatic-importingmethods,notfields.
– MiserableVariable
Jan8'09at6:08
10
PerhapsUtilityClassWithFrequentlyUsedMethodsneedstobeshortened.
– SteveKuo
Sep6'12at19:59
5
@SteveKuocertainlylessthanInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState:P
– AnirbanNag'tintinmj'
Apr3'14at18:50
@Rob-HruskaCouldn'tIjustwrapastaticimportmethodorfieldinanewmethodorfieldifI'mplanningonusingthemfrequently?Wouldthatallowmetonotstaticallyimport?suchas:doublemyPI=Math.PI;andthenIcanIjustkeepreferringtomyPIinsteadofMath.PI.
– Netero
Jul8'14at13:17
@Abdul-Yeah,youcoulddothat.
– RobHruska
Jul8'14at13:33
Addacomment
|
20
IthinkstaticimportisreallyusefultoremoveredundantclassnameswhenusingutilsclasseslikeArraysandAssertions.
NotsurewhybutRossskippedoutthelastsentencethatmentionsthisinthedocumentationheisreferencing.
Usedappropriately,staticimportcanmakeyourprogrammorereadable,byremovingtheboilerplateofrepetitionofclassnames.
Basicallycopiedfromthisblog:https://medium.com/alphadev-thoughts/static-imports-are-great-but-underused-e805ba9b279f
Soforexample:
Assertionsintests
ThisisthemostobviouscasewhichIthinkweallagreeon
Assertions.assertThat(1).isEqualTo(2);
//Usestaticimportinstead
assertThat(1).isEqualTo(2);
Utilsclassesandenums
Theclassnamecanberemovedinmanycaseswhenusingutilsclassesmakingthecodeeasiertoread
List
延伸文章資訊
- 1Java Gossip: import 靜態成員(Static import) - OpenHome.cc
- 2Java Packages and How to import them? - Programiz
- 3importing a method into a java class | DaniWeb
- 4What is a good use case for static import of methods? - Stack ...
For example methods from java.lang.Math and java.awt.Color. But if abs and getAlpha are not ambig...
- 5Java Packages and import statement | Studytonight