ABAP Static Vs Instance Method - Which To Use When - ABAP Help Blog
ABAP Static Vs Instance Method - Which To Use When - ABAP Help Blog
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
ZEVOLVING
> Home > ABAP Objects > OO Concepts ABAP Static vs Instance method Which to use when?
WealldebateoverwhentouseStaticmethodsorInstancemethods.Mostofthetimeswegoforsimplestapproach,butthatmaynotbethecorrectone.Lets
trytoexploreandseewhatshouldbepossiblythebestapproachwhendecidingStaticorInstance.
Basics
Beforejumpingintothedifferenceandwhichshouldbeused,checkoutthebasicsofbothStaticmethodandInstancemethod.
Static Methods
Staticmethodsaremethodswhichcanbecalledirrespectivetotheclassinstance.YoucanaccessonlystaticattributesandstaticeventswithintheStatic
method.
Thisishowyoudeclareandcallstaticmethod:
*staticmethoddeclaration
CLASSlcl_dataDEFINITION.
PUBLICSECTION.
CLASSMETHODS:
get_dataIMPORTINGiv_dateTYPEd.
ENDCLASS."lcl_dataDEFINITION
*
*staticmethodcallcallingusingclassname
lcl_data=>get_data('20130313').
*
CLASSlcl_dataIMPLEMENTATION.
METHODget_data.
*dosomething
ENDMETHOD."get_Data
ENDCLASS."lcl_dataIMPLEMENTATION
Instance Methods
InstancemethodsaremethodswhichcanbeONLYcalledusingtheobjectreference.Instancemethodscanaccessinstanceattributesandinstanceevents.
Thisishowyoudeclaredandcallinstancemethod:
*Instancemethoddeclaration
CLASSlcl_dataDEFINITION.
PUBLICSECTION.
METHODS:
get_dataIMPORTINGiv_dateTYPEd.
http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/
1/7
1/1/2016
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
ENDCLASS."lcl_dataDEFINITION
*
*Instancemethodcallcallingusingtheobjectreference
DATA:lo_dataTYPEREFTOlcl_data.
CREATEOBJECTlo_data.
lo_data>get_data('20130313').
*
CLASSlcl_dataIMPLEMENTATION.
METHODget_data.
"getdata
ENDMETHOD."get_data
ENDCLASS."lcl_dataIMPLEMENTATION
Test Fixture
InABAPunit,youcansetthetestdatainspecialmethodscalledtestfixtures.Afterthismethod,yourtestmethodwouldbecalledwhereyouhaveaccessto
testdata.SinceeachABAPUnittestshouldbeoperableandtestableonitsown,Staticmethodsmakesitverydifficulttotestwith.Staticmethodswoulduse
staticattributesandsincetheyareusingthat,youhavetohaveadditionallogictogetridofthemallthetimeinyourtestfixturemethods.
Ifyouareworkingwiththeinstanceiftheobject,itcanbeeasilycleared.Whenyouinstantiateanewobject,theoldobjectwouldbedereferencedwithoutany
additionallogic
Constructor
DesignusingthestaticmethodswouldendupusingtheCLASS_CONSTRUCTOR,asopposedtothemethodCONSTRUCTORforInstancemethods.AsI
notedearlier, CLASS_CONSTRUCTORandCONSTRUCTOR:Whocomesbeforewhom? ,itwouldbedifficulttopredictwhenCLASS_CONSTRUCTOR
wouldbecalled.CLASS_CONSTRUCTORcanbecalledwhentheclassisfirstaccessedeventhoughitwasaccessedtogetConstantvalue.Thismakesit
inoperableanduntestableonitsown.
http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/
2/7
1/1/2016
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
placeholderandcalltheUtilityclassforgeneratingthetrackinglog,youwouldlosetheerrorlogdatawhenyoutrytousethesameUtilityclass.
Ontheotherhand,youhadadesignusinginstancemethodandattributes,youwouldbeabletosimplycreateanotherinstanceandstartusingitfortrackinglog.
Thumb Rules
Sobasedonallthesefacts,wecanconcludetothesethumbrules:
Ifyouareplanningtocreateanystaticattributewhichwouldbeusedbystaticmethod,Considercreatinginstancemethods.Itwouldallowyoutoworkwith
multipleinstances.Italsoallowsyoutocontrolonwhenyoucanfreeuptheboundmemory.
Ifyouthinkthattherewouldbeachancetoaddaconditionallogicinfuture,Goforinstance.Thismakesdesignmoreflexiblebyallowingyoutoleverage
polymorphismby Redefinition
Staticshouldonlyusedforobjectcreationdesignpatternslike Singleton , FactoryMethod , AbstractFactory , SingletonFactory tofacilitatetheobject
creation.
Staticshouldbeforpureutilityclassesnotforhelperclasses.ThebestexampleswouldbemethodswithintheclassCL_GUI_FRONTEND_SERVICES.
LetmeknowifyouwanttoaddanyotherperspectiveofusingvsnotusingtheStaticmethod.
On a side note
ImplementedquiteafewchangesonsiteHomepageandotherpagesincludingNavigation,Menu,RelatedPostetc.Thesiteisalsonowmobile(iPhone,
Android,Nokia,andothers)aswellastablet(iPad,Galaxyandothers)friendly.Checkitoutandletusknowyourfeedback.
Naimesh Patel
{263 articles}
I'mSAPABAPConsultantformorethanadecade.IliketoexperimentwithABAPespeciallyOO.IhavebeenSDNTopContributor.
Follow:
Exploreallofhis263articles.
14 Comments
Wouter
steve oldner
Naimesh Patel
3/7
1/1/2016
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
HelloWouter,
Yes,Ioverallagreewithyourdesign.Definitelylookslikeaeasilyextendabledesign.AnewconditionforCOUNTRY_B,Inheritthesuper
class,extendthefactory/singletonmethodforobjectcreation,easy!AfterallOOisforeasymaintenance.
Forobjectcreation,IguesswhatyouarelookingforistheSingleton,asyourapplicationwouldonlyexecutedforasingleconditionata
time.ComparetoFactorymethodwhichgivesNEWobjectallthetime,Singletonprovidesthesameobjectagainandagain.
Regards,
NaimeshPatel
Saurabh Tiwari
Fred Verheul
Naimesh Patel
Wouter
steve oldner
http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/
4/7
1/1/2016
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
documentation(notavailibleinyourlanguage!?!)makeitlikeanesting/nesteddoll,thatwhenyougettothelastone,itsjustsimpleABAP
thatwouldhavebeenbetterinthefirstdoll.Yougetthefeelingtheyarerecodingjusttomakeitshinyandchargemoremoneyforthe
samething,inanewandimprovedpackage.
Ifyouwanttoselltoacustomer,makeiteasyforthemtounderstand.Makeitsimpleforthemtouse.Makeiteasytomaintain.Show
themK.I.S.S.
FlexibilityWeareaUSstategovernment.Idontuseflexibility.Anythingthatisnotstraightforward,oreasytounderstandorsimpleis
reallywastedandtakesupspace.Whenproductionproblemsoccur,Ireallydontneedtospendmytimeanalyzingnestedcodetofind
outwhatitissupposetodo.Iwanttoknowwhatthedatais,whereitcamefrom,andhowtheresultoccurred.
So,whenIusetheOOapproachsIhavelearnedhere,IrunitbythemostjuniorABAPPERstoseeiftheyunderstand,becausetheywill
betheonesmostlikelytochangeandmaintainthiscode.AndItakethetimetoreviewitwithmyQAreviewersotheyunderstandby
usingthisparticularOOcode,Ihavemadeanimprovement.Then,theydosuggestusingthisinotherprograms,anditbecomesade
factostandard.
Toallposters,thankyouverymuchforposting.Ilearnfromreadingyourcomments.
Thanks!!
Naimesh Patel
Naimesh Patel
Wouter Peeters
Naimesh Patel
http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/
5/7
1/1/2016
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
updateastandarddocumentsaySalesOrderusingBAPI,thanyourclassdesignisnotPersistent.YouonlycareaboutsettingtheBAPI
parametersfromyourclassproperly.AnotherexamplecouldbeareporttwooptionsSummaryandDetails.Summarycanbe
inheritedfromDetailsassummarywouldbeideallytotalofalltheamount/qtyfields.
Thanks,
NaimeshPatel
Aasim
Naimesh Patel
Comments on this Post are now closed. If you have something important to share, you can always contact me.
Subscribe
Keep in touch. We would do great working together.
1400
SubscribetoEmail
Follow@zevolving
your email
Current Poll
DoyoulikeQualityAssuranceofyourBuild/Design?
YES. I live for it!
I don't mind
NO. I hate it
Vote
View Results
http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/
6/7
1/1/2016
ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
Search
SearchinZevolving
http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/
7/7