Sei sulla pagina 1di 6

08/12/2014

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 |

17,316 | 14

WealldebateoverwhentouseStaticmethodsorInstancemethods.Mostofthetimeswegoforsimplestapproach,butthatmaynotbethecorrectone.Lets
trytoexploreandseewhatshouldbepossiblythebestapproachwhendecidingStaticorInstance.

Basics
Beforejumpingintothedifferenceandwhichshouldbeused,checkoutthebasicsofbothStaticmethodandInstancemethod.

Current Poll
DoyoulikeQualityAssuranceofyour
Build/Design?
YES. I live for it!
I don't mind
NO. I hate it
Vote

View Results

Static Methods
Staticmethodsaremethodswhichcanbecalledirrespectivetotheclassinstance.YoucanaccessonlystaticattributesandstaticeventswithintheStatic
method.
Thisishowyoudeclareandcallstaticmethod:

*staticmethoddeclaration
CLASSlcl_dataDEFINITION.
PUBLICSECTION.
CLASSMETHODS:
get_dataIMPORTINGiv_dateTYPEd.
ENDCLASS."lcl_dataDEFINITION
*
*staticmethodcallcallingusingclassname
lcl_data=>get_data('20130313').
*

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

1/6

08/12/2014

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog

CLASSlcl_dataIMPLEMENTATION.
METHODget_data.
*dosomething
ENDMETHOD."get_Data
ENDCLASS."lcl_dataIMPLEMENTATION

Instance Methods
InstancemethodsaremethodswhichcanbeONLYcalledusingtheobjectreference.Instancemethodscanaccessinstanceattributesandinstanceevents.
Thisishowyoudeclaredandcallinstancemethod:

*Instancemethoddeclaration
CLASSlcl_dataDEFINITION.
PUBLICSECTION.
METHODS:
get_dataIMPORTINGiv_dateTYPEd.
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

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

2/6

08/12/2014

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog

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
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.
TOP

On a side note

ImplementedquiteafewchangesonsiteHomepageandotherpagesincludingNavigation,Menu,RelatedPostetc.Thesiteisalsonowmobile(iPhone,
Android,Nokia,andothers)aswellastablet(iPad,Galaxyandothers)friendly.Checkitoutandletusknowyourfeedback.

Naimesh Patel

{245 articles}

I'mSAPABAPConsultantformorethanadecade.IliketoexperimentwithABAPespeciallyOO.IhavebeenSDNTopContributor.
Follow:
Exploreallofhis245articles.

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.

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

3/6

08/12/2014

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
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


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.

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

4/6

08/12/2014

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog
Greets,
Wouter

steve oldner

# March 21st, 2013 at 5:39 am


Asacustomerdeveloper,wehaveverylittleoutsidedevelopment.Andwhenwedo,theymustcodewithinourstandards,However,we
dochangeandupdateourstandardseveryfewyears(wellIinstigatemostofthechangesusuallybyintroducingnewfunctionality)
ThebiggestcomplaintIhaveaboutSAPsOOcodeisknowingwhatexactlyitdoesandissupposetodo.Toomuchabstractionandlittle
documentation(notavailibleinyourlanguage!?!)makeitlikeanesting/nesteddoll,thatwhenyougettothelastone,itsjustsimpleABAP
thatwouldhavebeenbetterinthefirstdoll.Yougetthefeelingtheyarerecodingjusttomakeitshinyandchargemoremoneyforthe
samething,inanewandimprovedpackage.
Ifyouwanttoselltoacustomer,makeiteasyforthemtounderstand.Makeitsimpleforthemtouse.Makeiteasytomaintain.Showthem
K.I.S.S.
FlexibilityWeareaUSstategovernment.Idontuseflexibility.Anythingthatisnotstraightforward,oreasytounderstandorsimpleis
reallywastedandtakesupspace.Whenproductionproblemsoccur,Ireallydontneedtospendmytimeanalyzingnestedcodetofindout
whatitissupposetodo.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,youcreatesetters
andgettermethods.EachfieldinyourtablewhichyouwanttoupdatewouldbecomeandinstanceattributeofyourPersistentObject.You
keeponcollectingthepersistentobjectforeachrowinthecontext.AtCOMMITWORK,systemwouldtakealltheactivechangesand
updatethemintheDBtable.
PersistentObjectsarenotgettingmuchofthepopularityinABAP.MainlythelackofObjectservicestoaccessthetablesandretrievethe
informationfromDBtables.Asyouhavenoted,theywouldbeperformanceintensiveaswell.
ThestatebaseddesignwouldbeidealsolutionfortheUserEntryscreenslike,ME21NPurchaseOrderentry.ThatisusingkindofState
mechanismtohandleeachrecord.ItwouldgenerateobjectsforHeader,foreachitem,foreachschedulelineitem,etc.Atsave,itwould
checkthestateofeachobjecttodecideonupdate.
AgreethatitwouldbedifficultforproceduralITpeopletounderstand.Fordevelopers,weshouldkeepourTechnicalDesigndocumentup
todatewiththecurrentdesign.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).

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

5/6

08/12/2014

ABAPStaticvsInstancemethodWhichtousewhen?ABAPHelpBlog

Naimesh Patel

# March 25th, 2013 at 8:47 am


HelloWouter,
Youcanuseyourinstancemethods&attributesinanycontext.Itdoesntneedtobepersistentonly.Forexample,Ifyouareusingto
updateastandarddocumentsaySalesOrderusingBAPI,thanyourclassdesignisnotPersistent.YouonlycareaboutsettingtheBAPI
parametersfromyourclassproperly.AnotherexamplecouldbeareporttwooptionsSummaryandDetails.Summarycanbeinherited
fromDetailsassummarywouldbeideallytotalofalltheamount/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

CommentsonthisPostarenowclosed.Ifyouhavesomethingimportanttoshare,youcanalwayscontactme.

Since2008|COPYRIGHT2013zevolving|www.zevolving.com|Advertise
Allproductnamesaretrademarksoftheirrespectivecompanies.zevolving.comisnotaffiliatedwithSAPAG.

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

6/6

Potrebbero piacerti anche