0% found this document useful (0 votes)
99 views7 pages

ABAP Static Vs Instance Method - Which To Use When - ABAP Help Blog

This article discusses the differences between static and instance methods in ABAP and provides guidance on when to use each. Static methods can be called without creating an object instance but cannot be redefined via inheritance, making them less flexible. Instance methods require object instantiation but allow for polymorphism. The article recommends using instance methods when conditional logic may need to be added in the future or when multiple instances are needed within a session. Static methods are best for utility classes and object creation patterns like factories.

Uploaded by

Vinay Shenoy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views7 pages

ABAP Static Vs Instance Method - Which To Use When - ABAP Help Blog

This article discusses the differences between static and instance methods in ABAP and provides guidance on when to use each. Static methods can be called without creating an object instance but cannot be redefined via inheritance, making them less flexible. Instance methods require object instantiation but allow for polymorphism. The article recommends using instance methods when conditional logic may need to be added in the future or when multiple instances are needed within a session. Static methods are best for utility classes and object creation patterns like factories.

Uploaded by

Vinay Shenoy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1/1/2016

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog

ZEVOLVING
> Home > ABAP Objects > OO Concepts ABAP Static vs Instance method Which to use when?

ABAP Static vs Instance method Which to use when?


By Naimesh Patel | March 18, 2013 | ABAP Objects, OO Concepts |

view 9,640 | comment 14

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

Why not to use Static methods


Asyoucanseefromthesamplecode,Itmaysoundgoodandlucrativetocreateastaticmethodasitdoesnotinvolvelongstepswhencallingthemethods
declaringreferencevariable,instantiatingtheobjectandcallingmethod.Staticmethodcanbedirectlycalledwithoutdoingthesesteps.Butthedesignusing
staticwillnotbeasgoodasitsounds.Letmeshowyouwhy:

Static methods cannot be Redefined


OneofthemostimportantaspectoftheObjectOrientedprogrammingisthePolymorphismreplacingthedefaultimplementationwiththemorespecific
implementationwheneveritsrequired.InOOABAPthepolymorphismwouldbeachievedusing MethodRedefinition .Aswehavediscussedinearlierarticle
OverrideStaticmethod ,wecantredefineStaticmethods.Theprimaryreasonbehindthisisstaticmethodsareoperableontheirown.Withstaticmethods,you
callthembyexplicitlyspecifyingthetypeonwhichtheyaredefined.Whichmeans,youdirectlycalltheimplementation,whichisnotboundtoanyspecific
implementationoftheinstanceobject.
LetsseethisbytheasimplescenarioIfyouhavestaticmethodwhichdoestheSalesOrderCreationusingtheBAPI.Whenyoudesigned,thismethodwas
onlyusedforonebusinessscenario.Now,youwanttousethisfordifferentbusinessscenario.Inthisnewscenario,youneedtosetsomeadditionalfieldson
item,likeHigherLevelitem,determineanewitemcategoryetc.Whatyouwouldthinkasasimplesolutionwouldbetoaddacodeblockinthemethodtodothis
logicforXYZSalesArea,ZABCordertype.Whatyouhavedonehereisopenedaboxwhereyouwouldkeeponaddingmoreandmoreconditions.Thus
violatingtheSingleResponsibilityPrinciple.
IfyouhadanInstancemethod,youcouldhaveeasilyinheritedanotherclass,redefinedthemethodandreplacedtheexistingimplementation.Inthisnew
implementation,yousettheadditionalfieldsandcallSuperMethodtodotherest.

Problem in ABAP unit testing


IhaventcoveredABAPUnityet.Theyarecomingsoon

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.

Reuse the Utility in same Session


Staticattributeswouldbeboundtomemorytillthesessionisover.Thismeansthatifthevaluesaresetonce,theywontbecleareduntilthesessionisfinished.
Ifstaticattributesitwontbepossibletoleveragethesamelogicinthesamesession.E.g.AsimpleutilityclasstogeneratingApplicationLog.
Thedesignislike:
Collectloginanattributeofthestaticclass
CallstaticmethodtogenerateApplicationlogafterthecollect.
Thedesignseemsfullyappropriatefortheutilityclasswhichshouldbestatic.Buttheproblemwiththisis,itrestrictyoufromusingthesamelogicagaininthe
samesessionwithoutlosingtheexistinginformation.Letssay,youarecollectingaerrorsusingthisapplicationlog.Now,inthesameprogram,youwontto
generateanotherapplicationlogtotracktheactivitiesperformed.Sinceyouhavecollectingalltheerrorsinthestaticattributes,unlessyoucopyitintoanother

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

# March 19th, 2013 at 5:43 am


Ok,letsthinkofthefollowingscenario:customdevelopment,customtable,createmethodsandsomeothermethodswherethepossibility
isthataccordingtoaspecificcondition,theywouldneedtobedifferent(redefinitioninsubclass)
Mycurrentideatobestpracticethis(afterthediscussionsinthepreviousarticles):
Objectsneeded:
Staticclass,singletonfactorywhichreturnsaninstanceobject
Instancesuperclassforthemainflow
Instancesubclassesfortheconditionbasedflows
Inourapplication,letssayaWebdynproABAPapplication,wewouldcallthestaticclassfactorymethodinthe
COMPONENTCONTROLLER,WDDOINITmethodandwepassalongtheconditionbasedparameter.
Thisfactorymethodwouldreturnaninstanceofthecorrectclass(ZCL_SUPERorZCL_SUB_COUNTRY_A).
Thiswouldgiveustheflexibility,thatforCountryAthecreatewouldbethatway,andforcountryBtheretrievalofadescriptionwouldbe
anotherway.
WecouldalsousethestaticclasstoinitiateaBALLoginthestaticconstructorandaddmessagestoitalongtheway.
Whatdoyouguysthink?

steve oldner

# March 19th, 2013 at 6:36 am


@WouterthatisabitmoreadvancedthatwhatImdoing.
Mytake,staticmethod=functionmodule.Instancemethodlikealocallyusedandchangeablefunctionmodule.
Thecoolestformeisusingasafunctionalmethodcallsandusingtheminsteadofvariables.

Naimesh Patel

# March 19th, 2013 at 8:49 am


http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/

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

# March 19th, 2013 at 12:54 pm


Pleasekeeppostedsucharticlesthanksalot

Fred Verheul

# March 20th, 2013 at 2:41 am


HiNaimesh,
Imwithyouonnotusingstaticmethodstoomuch,butforme,itsnot(only)aboutmethods,itsaboutobjects.Objectsencapsulate
data/statewithmethodstodosomethingintelligentwiththedata.Soforanyclass(=responsibility),ifthereiscommondatasharedbyits
methods(=howtoimplementtheresponsibility),thatdatashouldbeintheattributes,andthemethodsshouldbeinstancemethods.
Staticmethods/attributesshouldthusbetheexception,andthequestionwhichonetouseshouldnotevenberaisedingeneral.
Justmy2centsofcourse
Cheers,Fred

Naimesh Patel

# March 20th, 2013 at 9:05 am


HelloFred,
Icompletelyagreewithyouontheoveralldesignperspective.Wedefinitelyneedtothinkabouttheresponsibilityandstateoftheobjects.
Butassoonasyousayobjects,youaregoingtouseInstancemethods.ThisbasicguidelineswouldhelptodecidetouseObjectsornot.
Assoonasyougoforobjects,therewillbesecondstageofrefactoringtoachievepolymorphism,responsibilityandsettingproperstate
ThanksMuchforyourcomment.
Regards,
NaimeshPatel

Wouter

# March 20th, 2013 at 1:16 pm


HeyFred,
Agreed,butIdontemediatelydaretouseitoncustomersystemstobehonest.JustbecausethatapproachistooOO.Iveheard
proceduralABAPpersalreadycomplainaboutsimpleclassesandsuch,alsotheydontlikeitbecausethenFunctionalpeopleoreven
internalITpeoplecannotdebuganymore(ornotaseasily)tolocateissues.
IfIwouldlookatmyexample,astaticclasswithcreatemethodsandmethodstochangethestatus,andconvertthistoyourapproach,
fullyOOthatwouldmean:
Instantiateanobjectwiththekey,callthecreatemethodswhichpreparestherecordstosavetothetablelateron.Someupdatemethods
tosetdifferentstatussesandonandeverythingwouldbedoneintheattributes.
iwouldhavetoretrievethevalueswithgettersandsettersandcommittothedbwithamethod.
ButifIwoulddothisinmass,itwouldbelessreadableandIwouldalwaysgeteverythingoutofobjects,whileotherwiseIcancallmy
staticcreatemethodsandappendthistoalargeinternaltable.
Anythoughts?Doyoualsohaveexperiencesantiooorbettersaid,peoplenotwillingtolearnooorpostponelearningooaslongas
possible.
Greets,
Wouter

steve oldner

# March 21st, 2013 at 5:39 am


Asacustomerdeveloper,wehaveverylittleoutsidedevelopment.Andwhenwedo,theymustcodewithinourstandards,However,we
dochangeandupdateourstandardseveryfewyears(wellIinstigatemostofthechangesusuallybyintroducingnewfunctionality)
ThebiggestcomplaintIhaveaboutSAPsOOcodeisknowingwhatexactlyitdoesandissupposetodo.Toomuchabstractionandlittle

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

# March 21st, 2013 at 8:57 am


HelloWouter,
Thanksyouverymuchforyourvaluableinputs.
ThedesignyouarethinkingforeachdatabaserecordisKindofPersistentObjects.WhenusingthePersistentobjects,youcreate
settersandgettermethods.EachfieldinyourtablewhichyouwanttoupdatewouldbecomeandinstanceattributeofyourPersistent
Object.Youkeeponcollectingthepersistentobjectforeachrowinthecontext.AtCOMMITWORK,systemwouldtakealltheactive
changesandupdatethemintheDBtable.
PersistentObjectsarenotgettingmuchofthepopularityinABAP.MainlythelackofObjectservicestoaccessthetablesandretrieve
theinformationfromDBtables.Asyouhavenoted,theywouldbeperformanceintensiveaswell.
ThestatebaseddesignwouldbeidealsolutionfortheUserEntryscreenslike,ME21NPurchaseOrderentry.ThatisusingkindofState
mechanismtohandleeachrecord.ItwouldgenerateobjectsforHeader,foreachitem,foreachschedulelineitem,etc.Atsave,itwould
checkthestateofeachobjecttodecideonupdate.
AgreethatitwouldbedifficultforproceduralITpeopletounderstand.Fordevelopers,weshouldkeepourTechnicalDesigndocument
uptodatewiththecurrentdesign.IncludingUMLswouldbeagreatidea.AslongasthedeveloperscanreadUML,theywouldbeableto
understanditeasily.Forfunctionalteams,theywouldneedtokeepuptheirskilltogetusedtoit.
Itoogetthispushbackfrommyotherteammembers,butIwouldstillpursueusingOOABAP.
Regards,
NaimeshPatel

Naimesh Patel

# March 21st, 2013 at 9:01 am


HelloSteve,
IagreethatwhenyouareusingOOABAP,thenewbiewouldhavedifficulttimetounderstandespeciallyiftheyhavealreadytastedthe
ProceduralABAP.But,asImentionedinmyreplytoWouter,theyshouldbeabletounderstandthedesigniftheTDiswelluptodate.
Obviously,OOABAPneedsmoretimefrombeginningofdevelopmenttotestingfortheinitialdevelopment.Butasthatsoftwareevolves,
wewouldstartreapingthebenefitsofthat.
Thanksmuchformakingthisdiscussionsounique.
Regards,
NaimeshPatel

Wouter Peeters

# March 23rd, 2013 at 10:14 am


Onelastthought:whenwetalkaboutinstancemethods,weareactuallyalwaystalkingaboutpersistanceobjects(usingclass
attributes)?Theonlyotherinstancescrnarioicanthinkofrightnowisaninstanceclassthatistheapplicationmodel,whichdoessome
mainthingssuchaslogging,andallothermethodswouldactasstaticmethods(asinmethodswhodontuseclassattributesyoucould
settheseasinstancetootoenableredefinition).

Naimesh Patel

# March 25th, 2013 at 8:47 am


HelloWouter,
Youcanuseyourinstancemethods&attributesinanycontext.Itdoesntneedtobepersistentonly.Forexample,Ifyouareusingto

http://zevolving.com/2013/03/abapstaticvsinstancemethodwhichtousewhen/

5/7

1/1/2016

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
updateastandarddocumentsaySalesOrderusingBAPI,thanyourclassdesignisnotPersistent.YouonlycareaboutsettingtheBAPI
parametersfromyourclassproperly.AnotherexamplecouldbeareporttwooptionsSummaryandDetails.Summarycanbe
inheritedfromDetailsassummarywouldbeideallytotalofalltheamount/qtyfields.
Thanks,
NaimeshPatel

Aasim

# April 6th, 2013 at 1:39 am


HeyNaimesh,
ImaregularfollowerofyourblogsonABAP.We,asanaudience,gettolearnalotbyreadingyourarticles.Youve,kindof,
anagrammatizedABAPinabeautifulway.
Iwas,however,thinkingthatwouldntitbegreatifyoucouldwritesomethingonnewdimensiontopicslikeCRMWebUI,Webdynproor
evenALE/Idocsforthatmatter?
Cheerz!
Aasim

Naimesh Patel

# April 8th, 2013 at 8:49 am


HelloAasim,
Imgladthatyoulikethewhatyoureadonzevolving.
RegardingnewdimensiontopicsIhavethemlinedupandtheywouldbecomingupsoon.BTW,designpatterns,andallOOStuffyou
findhere,isanewdimensionalready
Regards,
NaimeshPatel

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

You might also like