0% found this document useful (0 votes)
338 views

Chapter 7 - Modularization - SAP ABAP - Hands-On Test Projects With Business Scenarios

SAP ABAP Modularization
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)
338 views

Chapter 7 - Modularization - SAP ABAP - Hands-On Test Projects With Business Scenarios

SAP ABAP Modularization
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/ 40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

SAP ABAP: Hands-On Test Projects with Business Scenarios

Recent

Topics
Tutorials

NEXT

PREV

Chapter 6: Internal Tables

Highlights
Chapter 8: Open SQL
Data Retrieval

CHAPTER7

Settings
Feedback

Modularization

Sign Out

Introduction
IntheABAPenvironment,modularizationinvolvestheorganizationof
programsintomodularunits,alsoknownaslogicalblocks.The
modularizationshouldreduceredundancyandincreaseprogram
readabilityevenasyouarecreatingitandsubsequentlyduringthe
maintenancecycle.Modularizationalsoenablesreusabilityofthesame

Settings
10 days left in your trial. Subscribe.

Feedback

codeagain.ABAP,withitsrootsinprocedureorientedtechnology,has
madeitnecessaryfordeveloperstomodularize:organizetheprograms
relativelymorethanintheOOPSbasedlanguages,whichhaverelatively

Sign Out

morebuiltinmodularfeatures.
Inadditiontomodularization,ABAPmessagemaintenanceandthe
MESSAGE...statementisalsocoveredinthepresentchapter.The
MESSAGE...statementisusedtoissuemessagesaswellasraiseerror
exceptionsinsideafunctionmodule.Functionmodulesarepartof
modularization.
RecallfromChapter4aboutthestructureofABAPprograms.TheABAP
programsaremadeupofprocessingblocks.Twooftheprocessingblocks
are:

Enjoy Safari? Subscribe Today

Theprocessingblockscalledfromoutsidetheprogramandfromthe
ABAPruntimeenvironment(i.e.,eventblocksanddialog
modules).
ProcessingblockscalledfromABAPprograms:
SubroutinesInternalandexternal
Functionmodules(basicallygenericsubroutines)
Methods

Theseprocessingblocksarecalledasthemodularizingprocessingblocks.
Eventprocessingblockshavebeenalreadyintroduced.Asmorecontexts
arise,moreeventswillbeintroduced.Dialogmoduleswillbecoveredin
Chapter14entitledScreenProgramming.
Apartfromallowingthemodularizationwithprocessingblocks,ABAP
alsofacilitatesmodularizationwithsourcecodethroughlocalmacrosand
globalincludeprograms.Thefollowingwillbediscussedinthischapter:
ModularizationatSourceCodeLevel
LocalMacros
GlobalIncludeprograms

ModularizationthroughprocessingblocksCalledfromABAP
programs
Internalsubroutines
Functionmodules

Externalsubroutinesareessentialonlyinonecontext(i.e.,SAPScripts).
Functionmodulesarethepreferredoptionoverexternalsubroutines.
MethodswillbecoveredinChapters11,12,and13.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

1/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Fornow,thecoveragewillconsistof:
Macros
Internalsubroutines
Includeprograms
Functionmodules
Macros
Thisisthemostrudimentarymodeofmodularization.Atypicalsituation
whenamacrocanbeusediswheninanABAPprogram,anumberof
sourcelinesorstatementsarebeingrepeated.Therepeatedstatements
canbelocatedatoneplaceasamacroandinvokedfrommultipleplaces.
Itisacaseofreducingredundancyandavoidingtheclutteringoftoo
manystatements.TheABAPcompileronencounteringthemacrowill
expandthemacro,thatis,replaceitsinvocationwiththestatements
containedinthemacrodefinition.
Aroughsyntaxofamacrodefinitionisasfollows:

DEFINE<macroname1>."DEFINEiskeyword
<statements>
ENDOFDEFINITION."ENDOFDEFINITIONiskeyphrase
........
<macroname1>[<parameters1><parameters2>..]."Macroinvocation

Itisnecessarytodefineamacrofirstbeforeinvokingit.
The<parameter1>...etc.replacetheplaceholders&1...inthe
ABAPstatementscontainedinthemacrodefinition.Therecanbea
maximumofnineplaceholdersinamacrodefinition.
Youcaninvokeamacrowithinanothermacro,butnotthesame
macro.
Youshouldbecarefulwhenusingbothmacrosandinclude
programs,asthereisnosyntaxcheckofincludeprogramsexcept
thetopinclude.
IfyourecallfromChapter4,wehadaprogramDESCRIBEFIELD...It
offersyouthescopeofmacroapplication.Therearealotofrepetitive
linesinthatprogram.Butbeforeyouapplymacrostothisprogram,let
theinternalsubroutinebeintroduced,andyouwillthenapplymacros
andsubroutinestotheChapter4programDESCRIBEFIELD...
Subroutines
Thisdiscussionisconfinedtointernalsubroutines.Whentheword
subroutineisused,internalisimplicit.
Likemacros,thesubroutinesalsoreduceredundancyandenhance
programreadability,butwithsomemoreadvantagesoverthemacros.
Thesubroutinescanacceptalltypesofparametersunlikethemacros,
whichacceptonlystringsintheplaceholders.Thesubroutinescanalso
returnvalues(outputparameters).Errorhandlingorraisingexceptionis
supportedwithinthesubroutines.Thesubroutinescanalsohavelocal
data.Likethemacros,thesubroutineshavetobedefinedandthen
invokedorcalled.
SubroutineDefinition
Aroughsyntaxofasubroutinedefinitionis:

FORM<subroutinename>USING<formalparameter1>
VALUE(<formalparameter2>)TYPE<dataobject2>
CHANGING<formalparameter3>LIKE<dataobject3>
VALUE(<formalparameter4>)."thisisasinglestatementtodefinesubroutine
<statementsblock>
ENDFORM.

Deliberately,fourparametershavebeenspecifiedtomakethe
explanationeasytounderstand.
Theparameter/sspecifiedwiththesubroutinedefinitionistheformal
parameters.
FORMisthekeywordtodefineasubroutine.Thekeywordhasto
befollowedbythenameofthesubroutine.
Parameterscanbepassedbyreference(thedefault),value,and
valueandresult.
IfyouuseeitherofthekeywordsUSINGorCHANGINGfollowed
bytheformalparameter,(withoutthekeywordVALUE),the
parameterispassedbyreference.
IfyouusethekeywordsUSINGVALUEfollowedbytheformal
parameterenclosedinparentheses,thentheparameterispassed
byvalue.
IfyouusethekeywordsCHANGINGVALUEfollowedbythe
formalparameterenclosedinparenthesis,thentheparameteris

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

2/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

passedbyvalueandresult.
Youcanassignatypetoaparameterbyusingtheappropriate
keywordTYPEorLIKEfollowedbyeitherthepredefinedABAP
elementarytypes,C,D,F,I,N,P,T,X,STRING,andXSTRING)
oralocaltypedeclaredwiththeTYPESstatementoraDDICdata
typeintheDDICtypegrouporadataobjectname(inmostcasesa
DDICdataobject)orasystemfield.Youcanalsoassigntypetothe
formalparametersbyreferringtotheABAPgenerictypes.Atable
oftheABAPgenerictypesistobefoundintheonline
documentationthroughthenavigation:ABAPByTheme
InTypesandDataObjectsandFunctions

Built

BuiltInDataTypes

GenericABAPTypes.Whensubroutineformalparametersare
assignedtypes,thenatcompiletime,theactualparametertypewill
becomparedwiththetypespecifiedforthisformalparameter,and
amismatchwilltriggeracompatibilityerrorcondition.
ThekeywordENDFORMistoindicatetheendofthesubroutine.
Inthesyntaxstatement,youarepassing<formalparameter1>by
reference,<formalparameter2>byvalue,<formalparameter3>by
referenceand<formalparameter4>byvalueandresult.
Youhaveassignedtypetotheparameters<formalparameter2>and
<formalparameter3>.
Asubroutinecannotbelocatedwithinasubroutinenonesting.
Asubroutinecancallitself,andasubroutinecanberecursive.
SubroutinesshouldbelocatedattheendofanABAPprogram.
Youcanalsospecifyalongwithparameters,theexceptionsinthe
subroutine.Theparametersspecificationalongwiththeexceptionsis
calledthesubroutineinterface.InChapter11,theclassbasedexceptions
willbeelaborated,andclassbasedexceptionsraisedinsidesubroutines
willbeillustrated.
Subroutinecalling
Aroughsyntaxofcallingasubroutine:

PERFORM<subroutinename>USING<actualparameter1><actualparameter2>
CHANGING<actualparameter3><actualparameter4>.

PERFORMisthekeywordtocallasubroutine.Thecontroljumpstothe
firstexecutablestatementinthesubroutine<subroutinename>.When
ENDFORMisencountered,controljumpsbacktothestatement
followingthePERFORMstatement.
ThekeywordVALUEisspecifiedonlywiththeformalparametersinthe
subroutinedefinition.ThekeywordVALUEwiththekeywordUSINGisto
indicateparametersarebeingpassedbyvalue.ThekeywordVALUEwith
thekeywordCHANGINGistoindicateparametersarebeingpassedby
valueandresult.
Theorderandnumberoftheformalparametersmustbeidenticaltothe
actualparameters.
SubroutineParameterPassing
ByReference
Youarepassingparametersbyreferencewhenyouareusingeitherof
thekeywordsUSINGorCHANGINGwithoutthekeywordVALUE.The
keywordsUSINGorCHANGINGcanbeusedinterchangeably.They
servethepurposeofdocumentation.Ifyouarechangingthevalueofthis
parameterwithinthesubroutine,usethekeywordCHANGINGorelse
usethekeywordUSING.Thememoryaddressofthedataobjectispassed
ontotheformalparameterofthesubroutine.Thesubroutinewilldirectly
operateonthisdataobjectpassedasparameterbyreference.Ifwithin
thesubroutine,thevalueoftheformalparameterischanged,thevalueof
actualparameteralsochangesbecausetheyareoneandthesame.
ByValue
YouarepassingparametersbyvaluewhenyouusethekeywordUSING
followedbythekeywordVALUEandtheformalparameterenclosedin
parentheses.Inthiscase,thesubroutinecreatesaduplicateoftheactual
parameterwithinthesubroutineasalocalcopy.Anychangesmadetothe
formalparameterareperformedonthelocalcopy,andtheoriginalor
actualparameterremainsunchanged.
ByValueandResult
Youarepassingparametersbyvalueandresultwhenyouusethe
keywordCHANGINGfollowedbythekeywordVALUEandtheformal
parameterenclosedwithinparentheses.Whenaparameterispassedin
thismanner,thesubroutineagainmakesaduplicatelocalcopyofthe
actualparameter.Whentheformalparameterischangedwithinthe

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

3/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

subroutine,thechangesareperformedonthelocalcopy.Ifthe
subroutineexitsinanormalway(notthroughanerrorexception),the
valuesoftheformalparameterortheduplicatecopyiscopiedbacktothe
originaloractualparameter.Ifthesubroutineexitsthroughanerror
exception,thevalueofformalparameterisnotcopiedtotheoriginalor
actualparameter.ClassbasederrorexceptionsarecoveredinChapter11
andtheeffectofvalueandresultsubroutineparameterisdemonstrated
inChapter11.
SubroutinesInternalTablesandStructuresasParameters
Youcanpassinternaltablesandstructureslikeanyotherelementary
typeparametersbyreference,value,andbyvalueandresult.
InternalTables
Whenpassinginternaltablesbyvalueandvalueandresult,youshould
bearinmind(a)theextraRAMtomaintainaduplicateofinternaltable,
and(b)thatthereisanoperationofcopyingofinternaltables(oncein
thecaseofpassingbyvalueandtwiceinthecaseofpassingbyvalue
andresult).Thiscouldhaveaneffectonperformance.Theinternal
tablesshouldpreferablybepassedbyreference.
Youmustassigntypetoaninternaltableformalparameteras
STANDARDTABLE,INDEXTABLE,ANYTABLE,SORTEDTABLE,and
HASHEDTABLE.Ahandsonexercisedemonstratesthepassingofan
internaltableasasubroutineparameter.Youcanpassastandard
internaltablebyreferenceusingthekeywordTABLESinplaceofUSING
orCHANGING.Butthisnotationisnowconsideredobsolete.
Structures
Whenastructureispassedasaparameterandthecomponentsorfields
ofthestructurearetobeaccessedinthesubroutine,thestructureformal
parametermustbeassignedatypebyreferringtoanappropriateDDIC
orprogramstructure.Whenassigningatypetoastructureparameter,
youcanusethekeywordSTRUCTUREinsteadofthekeywordsTYPEor
LIKE.Ahandsonexercisedemonstratesthepassingofstructure
parameterandaccessingofstructurefieldsinsidethesubroutine.
SubroutinesLocalDataandLocalDataDeclarations
Datacanbedeclaredwithinasubroutinelikeyoudowiththekeywords
DATA,TABLES,andCONSTANTS.Thedatadeclaredwithinasubroutine
islocaltothesubroutineandcanbeaccessedonlywithinthesubroutine.
Thedatadeclaredinasubroutinecomesintoexistenceonlywhenthe
subroutineisenteredbutceasestoexistwhenthesubroutineisexited.In
thiscontext,datadeclaredwithinasubroutineisreferredaslocaldata
visvisthedatadeclaredinthemainprogram,whichisreferredtoas
programglobaldata:datathatcanbereferredanywherewithinanABAP
program.
SubroutineSTATIC:RetainLocalVariableValues
Sometimeswhenyouareexecutingasubroutineamultiplenumberof
times,youwantthedatadeclaredwithinasubroutinetoretainvalues.
Normally,likeithasbeenmentionedintheprecedingitem,everytime
youenterasubroutine,thedatadeclaredwithinthesubroutinecomes
intoexistenceandgetsundefinedonexitingthesubroutine.Sowhatever
valueswereassumedbythevariableswithinthesubroutinearelostwhen
younextenterthesubroutineagain.Ifyouwantthevaluestobe
retained,declarethedatausingkeywordSTATICinsteadofthekeyword
DATA.
SubroutineLOCAL:ProtectGlobalData
Withinasubroutine,ifyoudeclaredatawiththesamenameasdata
objectsinthemainprogram,thelocallydeclareddataobjectswillbe
operateduponwithinthesubroutine.Thelocaldataobjectswillmaskout
themainprogramdataobjectsofthesamename.Thesubroutinelocal
dataobjects(declaredwithkeywordDATA)havingthesamenameasthe
dataobjectsinthemainprogrammightnothavethesameattributes
(type,length,etc.).
Youcouldenforcethesubroutinelocaldataobjectshavingthesamename
asmainprogramdataobjectstohavethesameattributesasthemain
programdataobjectsbyusingthekeywordLOCALtodeclaresuchdata
objects.WiththekeywordLOCAL,thesystemwillnotallowthetype,
length,etc.,tobespecified.Thetype,length,etc.,willbeinheritedfrom
themainprogramdataobjectsattributesofthesamename.The
followingbitofABAPcodewillelucidatethisfurther:

TABLES:TCURT.
DATA:COUNT1TYPEIVALUE100,
COUNT2TYPEIVALUE200,
T005TTYPET005T.
TCURTLTEXT='U.S.Dollar'.
PERFORMSRTN.
WRITE:/5TCURTLTEXT.
WRITE:/5(6)COUNT1,(6)COUNT2.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

4/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

**************************************
FORMSRTN.
*TABLESTCURT."erroneous,willgivesyntaxerror
LOCAL:TCURT,
COUNT1."typeIinmainprogram.
DATA:T005TTYPET005T,
COUNT2TYPEP."typeIinmainprogram.
TCURTLTEXT='DOLLAR'.
COUNT1=1000.
COUNT2=2000.
ENDFORM.

SubroutineReferencetoMainProgramGlobalDatawithina
Subroutine
Asubroutinecanrefertoanyofthemainprogramsdataobject(program
globaldataobjects).Thismakestheparameterpassingaredundant
exercise.Inthiscase,therewillbenoencapsulation.Hence,toenforce
encapsulation,allthereferencestothemainprogramsdataobjects
shouldbechanneledthroughthesubroutinesparameterinterface.
SubroutineTerminatingorExiting
YoucanusetheEXITstatementtoexitasubroutine.YouusedanEXIT
statementtoexitaloopinChapter4.YoucanalsousetheCHECK
statement.IftheCHECKstatementconditionistrue,thestatements
followingtheCHECKstatementareexecutedorelsethesubroutineis
exited.
HandsOnExercise:ModifyChapter44ProgramonDESCRIBE
FIELDUseMacroandSubroutinetoMakeItanEfficient
Program
Afterthetheoreticalbackgroundandthesyntaxofmacrosand
subroutines,letthefeaturesbeappliedtoanABAPprogram.InChapter
4,youhadahandsonexerciseusingtheDESCRIBEFIELDstatement.
Inthisprogram,youhavealotofrepetitive,similarstatements.The
repetitivenessgivesscopeforlocatingtherepetitivestatementsin
macrosorsubroutines.
Oneawkwardissueyouwerefacinginthisprogramwasrelatedtothe
determinationofthelengthofafield.Youwantedthelengthtobe
returnedincharacters(INCHARACTERMODE)whenthefieldtypeisC
orDorNorT.Youwantedthelengthtobereturnedinbytes(INBYTE
MODE)ifthefieldtypeisotherthanC,D,N,andT.YouwereusinganIF
statementtocheckthefieldtypeandappropriatelygivingtheaddition:
INCHARACTERMODEorINBYTEMODEintheDESCRIBEFIELD
<field>LENGTH<length>statement.Thecompilerwasdoingitsown
checkingoftypeandsyntacticallynotacceptingINCHARACTERMODE
ifthefieldtypeisotherthanC,D,N,andT.Youdonotwantthischecking
bythecompiler,becauseyouwantyourcheckingtotakeeffect.You
circumventedtheproblembysimplycommentingthelineswiththe
syntaxerror.Youcoulddothisbecauseyoualreadyknewfieldtypes:
NAME1istypeCNETWRistypeP,etc.
IfyoulocatetheDESCRIBEFIELD<field>LENGTH<length>
statementinsideasubroutine,thecompilerisnotperforminganycheck
ofthefieldtypeandrelatingittotheadditionINCHARACTERMODEor
INBYTEMODE.Thecompileristreatingitasaruntimeissue,nota
compiletimeissue.
So,inthecurrenthandsonexercise,youwilllocatetherepetitivesimilar
statementsinamacroandlocateaDESCRIBEFIELD<field>LENGTH
<length>statementinasubroutine.Butfirst,asegmentoftheoriginal
Chapter4program:

********************************************************
*DESCRIBEFIELD:DetermineAttributesofDataobjects*
********************************************************
DATA:NAME1TYPEKNA1NAME1,"DDICtablefield
FKDATTYPEVBRKFKDAT,"DDICtablefield
NETWRTYPEVBRKNETWR,"DDICtablefield
..............
TYP(1)TYPEC,
LENTYPEI,
OLENTYPEI,
DECITYPEI,
COMPOTYPEI.
**************************************************************************

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

5/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

DESCRIBEFIELDNAME1TYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
DESCRIBEFIELDNAME1LENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDNAME1LENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'KNA1NAME1TYPE&LENGTH:',TYP,(3)LEN.
**************************************************************************
DESCRIBEFIELDFKDATTYPETYP.
IFTYP='C'ORTYP='D'ORTYP='N'ORTYP='T'.
DESCRIBEFIELDFKDATLENGTHLENINCHARACTERMODE.
ELSE.
DESCRIBEFIELDFKDATLENGTHLENINBYTEMODE.
ENDIF.
WRITE:/5'VBRKFKDATTYPE&LENGTH:',TYP,(3)LEN.
**************************************************************************
............

Thestatements:
DESCRIBEFIELD<fieldname>TYPETYP...
IfTYP=...
WRITE...
...........

arerepetitive.Theyaremarkedinthesourceprogramlistedabove.So
youcanlocatetheserepetitivelinesinamacro.Youwillalsocreatetext
symbolsforthetextliteralsintheWRITEstatements.Eachcallor
invocationtothemacrowilldetermineandoutputtheattributesofone
field.Youwillfeedthemacrowithtwoparameters:thefieldnamewhose
attributesaretobedeterminedandthetextsymbol.
Fromwithinthemacroyouwillcallasubroutinetodeterminethefield
length.Thesubroutinewillhavethreeparameters(i.e.,fieldwhose
lengthistobedetermined),avariableinwhichlengthwillbereturned,
andthefieldtypetobeusedintheIFstatement.Thecalltothe
subroutineisenablingyoutoovercometheawkwardsituationof
compilercheckingfieldtypewhenyoudontwantittobechecked.
TheprogramtextsymbolswilllooklikeFigure71.

Figure71.ProgramYCL_CH07_01_DESCRIBE_FLD_MODUL
TextSymbols

Remembertoremovetheoccurrenceofsinglequotestwiceinliterals,if
youarecopyingChapter4literalstothetextsymbols.
Therevisedsourceprogram:

REPORTYCL_CH07_01_DESCRIBE_FLD_MODUL.
********************************************************
*DESCRIBEFIELD:DetermineAttributesofDataobjects*
*ModularizeCode.UsageofMacro&Subroutine*
********************************************************
************************************************************************
*declareelementarydataobjectsreferringtoDDICtablefields**
*declareelementarydataobjectreferringtoDDICdataelement**
*declarestructuredataobjectreferringtoDDICtabledefinition**
*declareelementaryTYPESTRING**
***
*invokemacrowhichusesDESCRIBEFIELDtodetermineTYPE.**
*fromwithinthemacro,PERFORMsubroutinewhichusesDESCRIBEFIELD**
*todeterminelength.**

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

6/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

***
*fromwithinthemacro,outputattributesTYPE,length**
*(alsonoofdecimalsforTYPEP,noofcomponentsforstructure)**
***
************************************************************************
DATA:NAME1TYPEKNA1NAME1,"DDICtablefield
FKDATTYPEVBRKFKDAT,"DDICtablefield
NETWRTYPEVBRKNETWR,"DDICtablefield
TEXT1TYPETBOOKSHOPTEXT1,"DDICtablefield
LENGTHTYPETBOOKSHOPLENGTH,"DDICtablefield
WAERSTYPEWAERS,"referencetodataelement
INT1TYPEMCSAPINT1,"referencetodataelement
VBRKTYPEVBRK,"referencetotablestructure
STRNGTYPESTRING,
TYP(1)TYPEC,
LENTYPEI,
DECITYPEI,
COMPOTYPEI.
***********************************************
*macrotoavoidrepetitionofsimilarlines**
*macrotakestwoparameters:**
*&1thefieldname**
*&2textsymbolid.**
***********************************************
DEFINEDESCRIBE_FLD."macrodefinition
DESCRIBEFIELD&1TYPETYP."determineTYPE
PERFORMGET_LENGTHUSING&1LENTYP."determinelength
IFTYP<>'F'ANDTYP<>'P'ANDTYP<>'u'ANDTYP<>'v'.
WRITE:/5&2,TYP,(4)LEN.
ELSEIFTYP='F'ORTYP='P'.
DESCRIBEFIELD&1DECIMALSDECI."determinenoofdecimals
WRITE:/5&2,TYP,(4)LEN,(2)DECI.
ELSEIFTYP='u'ORTYP='v'.
DESCRIBEFIELD&1TYPETYPCOMPONENTSCOMPO."determinenooffields
WRITE:/5&2,TYP,(4)LEN,(3)COMPO.
*DESCRIBEFIELD&1COMPONENTSCOMPO.
ENDIF.
ENDOFDEFINITION.
*****************************************
STARTOFSELECTION.
DESCRIBE_FLDNAME1TEXT001."macrocalls
DESCRIBE_FLDFKDATTEXT002.
DESCRIBE_FLDNETWRTEXT003.
DESCRIBE_FLDTEXT1TEXT004.
DESCRIBE_FLDLENGTHTEXT005.
DESCRIBE_FLDWAERSTEXT006.
DESCRIBE_FLDINT1TEXT007.
DESCRIBE_FLDVBRKTEXT008.
DESCRIBE_FLDSTRNGTEXT009.
***************************************************************
*subroutinetodeterminelength.takesthreeparameters**
*(1)field(FLD)whoselengthistobedeterminedbyvalue**
*(2)returningfieldlength(LNGT)byreference**
*(3)fieldTYPE(TP)byvalue**
***
*returnslengthincharactersforTYPESC,D,N,T**
*returnslengthinbytesforTYPESotherthanC,D,N,T**
***************************************************************
FORMGET_LENGTHUSINGVALUE(FLD)LNGTVALUE(TP).
IFTP<>'C'ANDTP<>'D'ANDTP<>'N'ANDTP<>'T'.
DESCRIBEFIELDFLDLENGTHLNGTINBYTEMODE.
ELSE.
DESCRIBEFIELDFLDLENGTHLNGTINCHARACTERMODE.
ENDIF.
ENDFORM.

YouhaveincorporatedtheSTARTOFSELECTIONstatement.In
Chapter4,theeventswerenotintroducedthoughalludedto.Youhad
decidedinChapter5thateveryABAPprogramwillhaveanexplicit
STARTOFSELECTIONstatement.
TheoutputwilllooklikeFigure72.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

7/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure72.ProgramYCL_CH07_01_DESCRIBE_FLD_MODUL
Output

HandsOnExercise:ModifyChapter44ProgramonDESCRIBE
FIELDUseSubroutineOnly
ThisisanotherversionoftheDESCRIBEFIELDprogram,thistimeusing
asubroutineonly.Macrosshouldbeusedonlyinthescenarioofjusttext
replacement.YouhavealsoshiftedthevariablesTYP,LEN,DECI,and
COMPOfromthemainprogramtothesubroutine.
Allthreeprograms(ofChapter4andthetwoprogramsinthecurrent
chapter)produceidenticalresults,butthecodeisprogressivelymore
efficientfromthefirstprogramtothethird.
Thesourceprogram:

REPORTYCL_CH07_02_DESCRIBE_FLD_SROUT.
********************************************************
*DESCRIBEFIELD:DetermineAttributesofDataobjects*
*ModularizedProgramUsageofSubroutine*
********************************************************
************************************************************************
*declareelementarydataobjectsreferringtoDDICtablefields**
*declareelementarydataobjectreferringtoDDICdataelement**
*declarestructuredataobjectreferringtoDDICtabledefinition**
*declareelementaryTYPESTRING**
***
*callsubroutinetodeterminefieldattributes&output**
***
************************************************************************
DATA:NAME1TYPEKNA1NAME1,"DDICtablefield
FKDATTYPEVBRKFKDAT,"DDICtablefield
NETWRTYPEVBRKNETWR,"DDICtablefield
TEXT1TYPETBOOKSHOPTEXT1,"DDICtablefield
LENGTHTYPETBOOKSHOPLENGTH,"DDICtablefield
WAERSTYPEWAERS,"referencetodataelement
INT1TYPEMCSAPINT1,"referencetodataelement
VBRKTYPEVBRK,"referencetotablestructure
STRNGTYPESTRING.
***************************************************************
STARTOFSELECTION.
PERFORMPROCESSUSINGNAME1TEXT001.
PERFORMPROCESSUSINGFKDATTEXT002.
PERFORMPROCESSUSINGNETWRTEXT003.
PERFORMPROCESSUSINGTEXT1TEXT004.
PERFORMPROCESSUSINGLENGTHTEXT005.
PERFORMPROCESSUSINGWAERSTEXT006.
PERFORMPROCESSUSINGINT1TEXT007.
PERFORMPROCESSUSINGVBRKTEXT008.
PERFORMPROCESSUSINGSTRNGTEXT009.
*****************************************************************
*subroutinetoprocess&output.takestwoparameters**
***
*(1)field(FLD)whoseattributestobedeterminedbyvalue**
*(2)textsymbolid(TSYM)byvalue**
***
*variablesTYP,LEN,DECI,COMPOshiftedfrommainprogramto**
*thesubroutine.**
*****************************************************************
FORMPROCESSUSINGVALUE(FLD)VALUE(TSYM).
DATA:TYP(1)TYPEC,
LENTYPEI,
DECITYPEI,
COMPOTYPEI.
DESCRIBEFIELDFLDTYPETYP."determineTYPE
*******************************************************
IFTYP<>'C'ANDTYP<>'D'ANDTYP<>'N'ANDTYP<>'T'.
DESCRIBEFIELDFLDLENGTHLENINBYTEMODE.
ELSE.
DESCRIBEFIELDFLDLENGTHLENINCHARACTERMODE.
ENDIF.
********************************************************
IFTYP<>'F'ANDTYP<>'P'ANDTYP<>'u'ANDTYP<>'v'.
WRITE:/5TSYM,TYP,(4)LEN.
ELSEIFTYP='F'ORTYP='P'.
DESCRIBEFIELDFLDDECIMALSDECI."determinenoofdecimals
WRITE:/5TSYM,TYP,(4)LEN,(2)DECI.
ELSEIFTYP='u'ORTYP='v'.
DESCRIBEFIELDFLDTYPETYPCOMPONENTSCOMPO."determinenooffields
WRITE:/5TSYM,TYP,(4)LEN,(3)COMPO.
*DESCRIBEFIELD&1COMPONENTSCOMPO."syntacticallynotacceptable
ENDIF.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

8/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

ENDFORM.

Themainprogramconsistshereofjustcallstothesubroutines.Atypical
procedureorientedenvironmentmodularprogramwouldbejustlike
this.Everyotherfunctionalityisimplementedbysubroutines,withthe
mainprogramjustconsistingofcallstothesubroutines.Evenno
repetitiveprogramlinesconsistingofexclusivelogicandactionare
locatedinasubroutine.
Theoutputofthisprogramwilllooklikethis:

Figure73.ProgramYCL_CH07_02_DESCRIBE_FLD_SROUT
Output

HandsOnExercise:SubroutinewithanInternalTableas
Parameter
Thishandsonexerciseistodemonstrateasubroutinehavinganinternal
tableasaparameter.Youwillloadaninternaltablewithdataandcalla
subroutineinwhichyousetupLOOPAT...WRITE...ENDLOOP.
YoucandeclareaninternaltablereferringtoaDDICstructureyou
createdearlier:YCL_CH06_CUST_STRUinChapter6.Youwillfillthis
internaltablewithdatafromDDICcustomerprimarytableKNA1.Then,
youcallasubroutinepassingthisinternaltableasaparameterby
reference.WithinthesubroutineyouwillhavetheLOOP
AT...WRITEENDLOOP.Letthefollowingfieldsbeoutput:

SYTABIXSerialNo.0509
KUNNRCustomercode1120
NAME1Name2256
ORT01City5892

Youwillneedwithinthesubroutineaworkareaorstructuretofetchone
rowatatimefromtheinternaltable.Youwilldeclarethestructure
withinthesubroutinereferringtotheDDICstructure
YCL_CH06_CUST_STRU.
ThetextsymbolsforanonstandardpageheadingareshowninFigure7
4.

Figure74.ProgramYCL_CH07_03_ITAB_AS_PARMText
Symbols

Thesourceprogram:

REPORTYCL_CH07_03_ITAB_AS_PARMLINESIZE95LINECOUNT60
NOSTANDARDPAGEHEADING.
************************************************
*SubroutineWithInternalTableAsParameter**
*SimpleCustomerList**
************************************************
************************************************
*declareinternaltable**
***
*reportheading**
*fillinternaltablefromtableKNA1**
*PEFFORM<subroutine>using<internaltable>**
***
*FORM<subroutineusing<internaltable>**
*TYPEANYTABLE.**
*LOOPAT...WRITE...ENDLOOP.**
*ENDFORM**
************************************************
DATA:CUSTOMER_TABTYPESORTEDTABLEOFYCL_CH05_CUST_STRU
WITHUNIQUEKEYKUNNR,

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

9/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

DAT(10)TYPEC.
***********************************************************
TOPOFPAGE.
WRITE:/5TEXT001,DAT,81TEXT002,(3)SYPAGNO.
WRITE:/5(83)SYULINE.
WRITE:/5TEXT003,12TEXT004,24TEXT005,60TEXT006.
WRITE:/6TEXT007,14TEXT008.
WRITE:/5(83)SYULINE.
***********************************************************
STARTOFSELECTION.
CONCATENATESYDATUM+6(2)SYDATUM+4(2)SYDATUM+0(4)INTODAT
SEPARATEDBY'/'.
SELECTKUNNRNAME1STRASORT01PSTLZFROMKNA1INTOTABLECUSTOMER_TAB.
PERFORMOUTPUT_LISTUSINGCUSTOMER_TAB.
***********************************************************
FORMOUTPUT_LISTUSINGCUST_TABTYPEANYTABLE."internaltableparameter
"hastobeassignedtype
DATACUST_STRULIKEYCL_CH05_CUST_STRU."subroutinelocaldata
LOOPATCUST_TABINTOCUST_STRU.
WRITE:/5(5)SYTABIX,CUST_STRUKUNNRUSINGNOEDITMASK,
CUST_STRUNAME1,CUST_STRUORT01.
ENDLOOP.
ENDFORM.

TheoutputisfoundinFigure75.

Figure75.ProgramYCL_CH07_03_ITAB_AS_PARMOutput

HandsOnExercise:SubroutinewithaStructureasParameter
TheprogramYCL_CH07_03_ITAB_AS_PARMhasbeenmodifiedso
thatonlytheWRITEstatementisexecutedinsidethesubroutine.LOOP
AT...ENDLOOPisshiftedtothemainprogram.Thesubroutineis
receivingthestructuredata.Sinceyouwanttoaccesstheindividualfields
ofthestructure,youhavetoassignatypetotheformalstructure
parameter.TheformalparameterisreferringtotheDDICstructure
YCL_CH06_CUST_STRU,andthekeywordSTRUCTUREisused
insteadofTYPEorLIKE.Thisisademonstrativeprogramusedto
demonstratethepassingofastructureparameter.
Thesource:
REPORTYCL_CH07_04_STRU_AS_PARMLINESIZE95LINECOUNT60
NOSTANDARDPAGEHEADING.
************************************************
*SubroutineWithStructureAsParameter**
*SimpleCustomerList**
************************************************
************************************************
*declareinternaltable**
***
*reportheading**
*fillinternaltablefromtableKNA1**
*LOOPAT...PERFORMWRITER...ENDLOOP.**
***
*FORM<subroutineusing<structure>**
*TYPEYCL_CH05_CUST_STRU.**
*WRITE...**
*ENDFORM**
************************************************
DATA:CUSTOMER_TABTYPESORTEDTABLEOFYCL_CH05_CUST_STRU
WITHUNIQUEKEYKUNNRWITHHEADERLINE,
DAT(10)TYPEC.
***********************************************************
TOPOFPAGE.
WRITE:/5TEXT001,DAT,81TEXT002,(3)SYPAGNO.
WRITE:/5(83)SYULINE.
WRITE:/5TEXT003,12TEXT004,24TEXT005,60TEXT006.
WRITE:/6TEXT007,14TEXT008.
WRITE:/5(83)SYULINE.
***********************************************************
STARTOFSELECTION.
CONCATENATESYDATUM+6(2)SYDATUM+4(2)SYDATUM+0(4)INTODAT
SEPARATEDBY'/'.
SELECTKUNNRNAME1STRASORT01PSTLZFROMKNA1INTOTABLECUSTOMER_TAB.
LOOPATCUSTOMER_TABINTOCUSTOMER_TAB.
PERFORMWRITERUSINGCUSTOMER_TAB.
ENDLOOP.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

10/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

***********************************************************
FORMWRITERUSINGCUST_STRUSTRUCTURE"keywordSTRUCTURE
YCL_CH05_CUST_STRU."structureparameter
"hastobeassignedtype
"foraccessingfields
WRITE:/5(5)SYTABIX,CUST_STRUKUNNRUSINGNOEDITMASK,
CUST_STRUNAME1,CUST_STRUORT01.
ENDFORM.

TheoutputwillappearlikeFigure76.

Figure76.ProgramYCL_CH07_03_STRU_AS_PARMOutput

HandsOnExercise:ListofIconsinSAPGUIEnvironment
FieldsEnclosedinBoxesUsingMacroandSubroutine
ThedatabasetableICONcontainstheiconsandtheirparticulars(icon
name,iconid,etc.).Youwilllisttheseiconsparticulars,enclosingeach
fieldinabox.
Amacroisenclosingtheoutputfieldinabox.Themacrooutputsonefield
atatime.ThemacrooutputsafieldwithaSYVLINEontheleftandright
sideofitandSYULINEatthetopandbottom.Onlythefirstfieldbeing
outputonalinerequiresaSYVLINEontheleft.Thesubsequentfields
alreadyhaveaSYVLINEontheleft(therightsideSYVLINEofprevious
fieldservesasleftsideSYVLINEofthenextfield).Similarly,thefirst
lineoftheoutputrequiresanSYULINEatthetop.Subsequentlinescan
usethebottomSYULINEofthepreviouslineastheirtopSYULINE.
Thesethingsarenottakencarebythemacro.Thereisanoccurrenceof
overwriting.Youcan,asanexercise,eliminatetheoverwritingand
refinethemacro.
ThemacroisalsoimpartingcolortotheoutputfieldthroughFORMAT
statement.TheFORMATstatementinthemacrotakesasmacro
parameterswhetherINVERSEisON/OFF,INTENSIFIEDisON/OFF
andcolorname(COL_KEYetal.).Theotherparametersofmacroare
fieldortextsymbolandoutputwidthincolumns.
TheparticularsoftheiconsappearinginSAPGUIenvironmentare
storedinthedatabasetableICON.Thereare13fieldsinthistable.You
outputonlytwofieldsinyourlist.

IDIconpicture
ID+1(2)IconCode(second,thirdcharacterofthefieldID)
NAMEIconName

YououtputfieldIDtwiceandthefullfieldonce(thiswilloutputtheicon
picture)andnextthesecondandthirdcharactersofthefieldID(i.e.,
ID+1(2)thiswilloutputtheiconcode).Alltheiconsareidentifiedbytwo
charactercodesaswellasiconnames.Youhaveusediconnamesin
Chapter5.YouusedtheTypeGroupICONintheChapter5program.The
TypeGroupICONcontainsalltheSAPGUIicondefinitions.Yououtput
iconpicturesintheChapter5programbyreferringtotheiconnameand
usingthekeyphraseASICONwiththeWRITEstatement.Youcanalso
outputtheiconpicturewiththeWRITEstatementbygivingtheiconcode
[email protected]
ICON_SYSTEM_SAVE,thecodeforthisiconis2LandthefieldIDinthe
correspondingrowinthetableICONcontains@[email protected],the
codefortheiconICON_CHECKis38.SothefieldIDinthe
correspondingrowwillcontain@[email protected]
willgeneratethesameoutput.
Yougeneratethelistheaderinthisprogramthroughasubroutinethatis
calledconditionallyandnotthroughtheTOPOFPAGEevent.Themix
oftheTOPOFPAGEeventandthemacrodidnotgeneratecorrectly
formattedoutput.
Youareusingtwonewsystemfieldsinthisprogram:

SYCOLNOCurrentOutputColumnPosition
SYLINNOCurrentLineNumberinaPage(Variesfrom1toSYLINCT)

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

11/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Thesourceprogram:

REPORTYCL_CH07_05_OUTPUT_INBOX_MACRONOSTANDARDPAGEHEADING
LINECOUNT60LINESIZE75.
********************************************************************
*SAPIconListUseMacroToImpartColor&EncloseOutputInBox**
*UseSubroutinetoOutputReportHeaderInsteadofTOPOFPAGE**
*Event**
********************************************************************
*****************************************************************
*retrievedatafromthedatabasetableICON.SELECTENDSELECT**
*outputICONparticularsi.e.ICONNAME(iconname)**
*ICONID(iconid.)**
*&ICON+1(2)(iconcode)**
***
*useamacrotooutputiconparticularsenclosedinboxin**
*specifiedcolor.**
***
*eachtimemacroisinvoked,oneitemofinfo(field)is**
*output.eachfieldisenclosedinabox:SYVLINEonleft&**
*right,SYULINEontop&bottom.**
***
*thecolumnpointerafteroutputpointstothecolumnnextto**
*therightsideSYVLINE.**
*(systemfieldSYCOLNOstoresthecurrentcolumnnumber)**
***
*therowpointerpointstotherowbetweentop&bottom**
*horizontalSYULINE.**
*(systemfieldSYLINNOstoresthecurrentrow)**
***
*coloristhroughtheFORMATstatement.**
***
*macrotakes5parameters(placeholders&1,&2,&3,&4,&5):**
*(1)fieldname/textsymbolid.**
*(2)outputwidthincolumnpositions**
*(3)ON/OFFforINVERSEON/OFF**
*(4)ON/OFFforINTENSIFIEDON/OFF**
*(5)colorname(COL_KEY,COL_POSITIVEetal)**
***
*usageof'SKIPTO..'&'POSITION..'statements.**
***
*Aftereachline,(allfieldsareoutput)twolinesare**
*skipped.columnpositionissetto5.**
*****************************************************************
*****************************************************************
*inthereportheading,thepagenumber(SYPAGNO)is**
*outputaswellasthecolumnheadings.thecolumnheadings**
*areenclosedinboxes&outputthroughthemacroagain.**
*thereportheadingisnotgeneratedusingtheTOPOFPAGE**
*event.itisgeneratedusingasubroutine.thissubroutine**
*iscalledeitherwhenCNTISINITIALORCNTR>=58.**
*youareusingtheNEWPAGEstatementtostartoutputonanew**
*pageeverytimethereportheadingistobeoutput.this**
*washappeningautomaticallywithTOPOFPAGEevent.**
***
*youarenotusingtheTOPOFPAGEeventbecausethemixof**
*TOPOFPAGEevent&macroisnotgeneratingproperly**
*formattedoutput.**
***
*****************************************************************
TABLES:ICON.
DATA:COLTYPESYCOLNO,
LINTYPESYLINNO,
LENGTHTYPEI,
PGTYPESYPAGNO,
CNTRTYPEI,
CNT(6)TYPEC.
****OUTPUTINABOXMACRO***
******************************
DEFINEWRITE_GRID.
COL=SYCOLNO.LIN=SYLINNO."savecurrentcolumn&line/rowno.
FORMATINVERSE&3INTENSIFIED&4COLOR&5.
WRITE:'|'NOGAP,(&2)&1NOGAP,
'|'NOGAP."outputfieldwithleft&rightSYVLINE
LENGTH=SYCOLNOCOL."derivelengthofhorizontalline
LIN=LIN1.SKIPTOLINELIN.POSITIONCOL.
ULINEATCOL(LENGTH)."tophorizontalline
LIN=LIN+2.SKIPTOLINELIN.POSITIONCOL.
ULINEATCOL(LENGTH)."bottomhorizontalline
LIN=LIN1.COL=SYCOLNO2.
SKIPTOLINELIN."setline&columnnofornextoutput
POSITIONCOL.
ENDOFDEFINITION.
********************
********************
STARTOFSELECTION.
SELECT*FROMICONORDERBYNAME.
IFCNTR>=58ORCNTISINITIAL."value58arrivedbytrial&error
PERFORMPHEAD.
ENDIF.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

12/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

CNT=SYDBCNT."CNTTYPECtosuppressthousandseparator/comma
WRITE_GRIDCNT6ONOFFCOL_TOTAL."outputCNTcolumnwidth6
"INVERSEONINTENSIFIEDOFF
"COLORCOL_TOTAL
WRITE_GRIDICONNAME35ONOFFCOL_KEY.
WRITE_GRIDICONID7ONOFFCOL_POSITIVE.
WRITE_GRIDICON+1(2)4ONOFFCOL_HEADING.
SKIP2."oneextralineforbottomhorizontalline
POSITION5.
CNTR=CNTR+2."increaselinecountby2
ENDSELECT.
*************reportheader******************
FORMPHEAD.
NEWPAGENOHEADING.
PG=PG+1.
WRITE59(3)PG.
SKIP2."makeonerowavailablefortophorizontalline
POSITION5."alloutputisstartingasusualfromcolumn5
WRITE_GRIDTEXT0016ONOFFCOL_TOTAL.
WRITE_GRIDTEXT00235ONOFFCOL_KEY.
WRITE_GRIDTEXT0037ONOFFCOL_POSITIVE.
WRITE_GRIDTEXT0044ONOFFCOL_HEADING.
SKIP2.
POSITION5."fornextrowcolumnposition5
CNTR=4."linecountsetto4
ENDFORM.

TheoutputwillappearlikeFigures77and78.

Figure77.ProgramYCL_CH07_05_OUTPUT_INBOX_MACRO
Output

Figure78.ProgramYCL_CH07_05_OUTPUT_INBOX_MACRO
Output

MessagesMaintenanceandIssuinginABAPWorkbench
Notificationsandalertshavetobegiventoauserofasystemforthebasic
manmachineinteraction.Youhaveencounteredthesenotifications
whenyouwerealertedaboutasyntaxerrorinyourABAPprogramand
whenyouactivatedanobjectinWorkbenchenvironmentandsoon.
ThesenotificationsandalertsaredesignatedasmessagesintheABAP
Workbenchenvironment.
MessageTextMaintenance
MessagetextsaremaintainedcentrallyintheABAPWorkbench
environment.Asusual,likeinanyothercontextoftextmaintenance,
themessagetextscanbemaintainedinmultiplelanguages.Messages
canbeissuedinanABAPprogramthroughtheMESSAGEstatement.
ThereisaprovisiontopassruntimeinformationtotheMESSAGE
statementthroughtheconceptofplaceholdersinmessagetexts.Thisis
similartotheplaceholderfacilityinListHeadingcomponentoftext
elementsofanABAPprogram(&0...&9inChapter5).Therecanbea

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

13/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

maximumoffourplaceholders:&1,&2,&3,&4foronemessagetext.
MessagetextsaremaintainedthroughthetransactioncodeSE91.The
messagetextsarecontainedinanentitycalledmessageclassormessage
id.Asinglemessageclasscancontainamaximumofonethousand
messagetexts.Themessagetextsinthemessageclassareidentifiedby
messagenumbers,withthenumbersrunningfrom000to999.Youcan
entertextsarbitrarilyinanyofthesenumberslots.Whenamessageis
issuedwiththeMESSAGEstatement,themessageclass,message
number,andtheruntimeinformationtositintheplaceholdersifany,
hastobegiven.
GotoSE91openingscreen.Enteranameforthemessageclassas
YCL_CH07_MCLASS01.PressCreatebutton/F5,entershorttext,press
thesavebutton,andassignyourusual$TMPpackage.Thescreenwill
looklikethis:

Figure79.MessageClassCreation

Thereisnoexplicitactivationprocessforamessageclass.Thesavingis
enough.
Thenamingconventionsfollowthenamingconventionsofanyother
ABAPWorkbenchobject.Thenamespaceofmessageclassisamaximum
of20characters.
YouareontheAttributestab.ClickontheMessagestab.Thescreenwill
looklikethis:

Figure710.MessageTextsScreen

Youcanenterthetextsagainstthetextidentificationnumbers.Thetext
entrycanbeamaximumof73characters.Therearetheusualbuttonsto
handlemultiplerowscreenentries:namely,select,cut,copy,paste,
delete,etc.Thereareadditionalbuttonstofind,find,andreplace.There
isacheckboxontherightwiththecolumnheadingSelfexplanatory(Self
explanatory).Ifyoudisablethischeckbox,youcancreatealongtextfor
themessage.Whenthenormaltextappearsonmessageissuanceandthe
userdoubleclicksonit,thelongtextofthemessageappears.Inany
case,youcancreatethelongtextforamessage.IfthecheckboxSelf
explanatoryisenabled,aconfirmatorydialogboxwillappearbeforethe
longtextdialogboxappears.IfthecheckboxSelfexplanatoryisdisabled,
noconfirmatorydialogboxwillappearbeforethelongtextdialogbox
appears.ThelongtextcanbecreatedbyclickingtheLongTextbuttonon
theapplicationtoolbar.
MessageIssuance
Lettherebeasimplescenarioforcreationandissuanceofamessage:
MessagesareissuedwiththeMESSAGEstatement.
InanABAPprograminputcustomercodethroughPARAMETERS
statement.Youwillcheckthevalidityofthecustomercode.Ifthe
customerisvalid(shouldbeavailableinthedatabasetableKNA1),you
willissueamessagethattheinputcustomercodeisvalid.Ifthecustomer
codeisinvalid,youwillissueamessagethattheinputcustomercodeis
invalid.Iftheinputcustomerisblank,issueamessagethattheinput
customercodeisblank.Sotherewillbethreemessages.Themessages
reportingvalidityorinvalidityofcustomercodemusthaveruntime
information:theinputcustomercode.
So,ontheSE91screen,inthemessageclassYCL_CH07_MCLASS01,in
theMessagestab,enterthemessages000,001,002asshowninFigure
711.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

14/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure711.MessageTextsMessages000,001,002

Theplaceholder&1inmessages000,001willbereplacedbytheruntime
informationyouwillprovidewiththemessageissuingstatement.
Therearesixtypesofmessages.Youcanuseanyoneofthesemessage
typesdependingonthecontextwhenissuingmessages.Table71lists
themessagetypeswiththeirmeanings.
Table71.MessageTypes

Message

Description

Type

Abort.IssueofthisMessageTypeAbortsthe
Program/Job

Error.IssueofthisMessageTypemayAbortthe
Program/Job

Information.Appearsasadialog

Status

Warning.IssueofthisMessageTypemayAbort
theProgram/Job

Exit.IssueofthisMessageTypeAbortsthe
Program/JobwithaShortDump

Themessagetypedetermineshowthemessageappearsandwhetherthe
programcontinuesexecutionoraborts/terminates.Inonline
documentation,youwillfindelaboratedescriptionsofhowmessages
appearforeachmessagetypeandwhethertheprogramcontinuesor
abortsindifferentcontexts.FormessagetypesIandS,theprogram
continuesexecution.FormessagetypesAandX,theprogram
terminates.
MessageStatementSyntaxes
BeforeyouwriteanABAPprogram,lettheABAPmessageissuing
statementMESSAGEsyntaxbeintroduced.Twosyntaxesarebeing
introduced.Whenyoudoclasses,moresyntaxwillbeintroduced.The
twosyntaxesofamessagestatement:
Syntax1
MESSAGE<messagetype><messagenumber>[(<messageclass>)]
[WITH<dataobject1>...<dataobject4>].

Inthisstatement,youspecifyin
<messagetype>:oneofthetypes:A,E,I,S,W,X.
<messagenumber>:Threedigitmessagenumber.Likeinyourpresent
proposedABAPprogram:000/001/002.
<messageclass>:Inyourpresentcase,thenameofyourmessageclass:
YCL_CH07_MCLASS01enclosedinparentheses.Themessageclasscan
alsobespecifiedintheREPORTorFUNCTIONPOOLstatement.Inthat
case,themessageclassneednotbegivenwiththeMESSAGEstatement,
ifyouwanttousethesamemessageclassspecifiedwithREPORTor
FUNCTIONPOOLstatement.Ifyouwanttouseamessageclassother
thantheoneintheREPORTorFUNCTIONPOOLstatement,you
specifyamessageclasswiththeMESSAGEstatement.Themessageclass
givenwithMESSAGEstatementoverridestheonegiveninREPORTor
FUNCTIONPOOL(localoverridesglobal).Themessageclassisgiven
withtheREPORTorFUNCTIONPOOLwiththekeywordMESSAGEID

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

15/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

followedbythenameofthemessageclass.
WITH:Youspecifydataobject/sfollowingthekeywordWITH.Thisis
optionalbutrequiredifyouwanttopassruntimeinformationtothe
messagetextplaceholders.Thereisamaximumlimitoffour.Inyour
casethiscouldbethefollowing::WITHCUST_CD.CUST_CDwillbe
yourPARAMETERSvariablename.Soifyouwereissuingmessagefora
validcustomer,yourmessagestatementwillbe:
MESSAGES001(YCL_CH07_MCLASS01)WITHCUST_CD.
Syntax2

MESSAGEID<messageiddataobject>TYPE<messagetypedataobject>
NUMBER<messagenumberdataobject>[WITH<dataobject1>..<dataobject4>].

Thissyntaxoffersthefacilityofhavingthemessageclass,type,and
numberasvariables.Theearliersyntaxhardcodedthisinformation.So
appropriatevaluescanbeputinthethreevariables:<messageiddata
object>,<messagetypedataobject>and<messagenumberdataobject>
andthemessageissuedwiththesevariables.
Therearesevensystemfieldsassociatedwiththeissuingofmessages.
ThesesystemfieldsarefilledwithvaluesaftertheMESSAGEstatement
isexecuted:Theyare:
SYMSGID:Thisisfilledwiththemessageclassgivenwiththemessage
statement.
SYMSGTY:Thisisfilledwiththemessagetypegivenwiththemessage
statement.
SYMSGNO:Thisisfilledwiththemessagenumbergivenwiththe
messagestatement.
SYMSGV1,SYMSGV2,SYMSGV3andSYMSGV4:Filledwithvaluesin
thedataobjectsspecifiedafterthekeywordWITHinMESSAGE
statement.Iflessthanfourdataobjectsarespecified,thesesystemfields
willcontainblanks.
MessageStatementAdditionalOptions
Therearetwomoreoptionsyoucanspecifywiththetwosyntaxesof
MESSAGEstatement.Theyare:
[RAISING<exceptionname>]
Thisoptioncanbespecifiedonlyinafunctionmodule.Specifyingthis
optiondoesnotresultinissuingofamessage.Thesystemfieldsarefilled
withthevaluesandthefunctionmoduleterminates.Thisoptionisused
intheforthcomingtopicFunctionmodulesofthepresentchapter.
[DISPLAYLIKE<messagetype>]
Sometimes,youwantamessagetolooklikeanerrormessagebutdonot
wanttheprogramtermination.Thiskindofarequirementcanbe
handledthroughthisoption.Soifamessagehasbeenissuedasastatus
(S)message,youcanusetheoptionDISPLAYLIKEEtogivethe
appearanceoferrortypeEmessage.Theprogramwillnotbe
terminated.Ahandsonexercisedemonstratingmessageissuance
follows.
HandsOnExercise:MessageIssuance
Thesourceprogram:

********************************
*DemonstrateIssuingMessages*
********************************
DATA:KUNNRTYPEKNA1KUNNR.
PARAMETERS:CUST_CDTYPEKNA1KUNNR.
******************************************
STARTOFSELECTION.
SELECTSINGLEKUNNRFROMKNA1INTOKUNNR
WHEREKUNNR=CUST_CD.
IFCUST_CDISINITIAL.
MESSAGES002(YCL_CH07_MCLASS01)DISPLAYLIKE'E'.
ELSEIFSYSUBRC=0.
MESSAGES000(YCL_CH07_MCLASS01)WITHCUST_CD.
ELSE.
MESSAGES001WITHCUST_CDDISPLAYLIKE'E'.
ENDIF.

Theoutputsforavalid,invalid,blankcustomercodeCUST_CDare
shown:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

16/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure712.ProgramYCL_CH07_11_ISSUE_MESSAGE
Output:CustomerCodeValid

Figure713.ProgramYCL_CH07_11_ISSUE_MESSAGE
Output:CustomerCodeInvalid

Figure714.ProgramYCL_CH07_11_ISSUE_MESSAGE
Output:CustomerCodeBlank

FunctionModules,INCLUDEPrograms
FunctionModulesIntroduction
Thefunctionmodulescanbeviewedasgenericorgeneralpurpose
externalsubroutines.TheycanbecalledfrommultipleABAPprograms
reusability.Theyresideinacentrallibrary.Theyarecontainedin
functiongroups(specialABAPprograms):afunctiongroupcancontain
oneormorefunctionmodules.Ifyoucallorinvokeonefunctionmodule
inthegroup,allthefunctionmodulesinthatgroupareloadedintoRAM.
Ifyouhaveasituationwhereyouarecallingmorethanonefunction
moduleinanABAPprogramfrequently,thenyoucanlocatethese
functionmodulesinafunctiongrouptoimproveperformance.Oneother
scenariowhereyouwilllocatemultiplefunctionmodulesinafunction
groupiswhenthefunctionmoduleslocatedinafunctiongroupsharelot
ofcommondataanddataobjects.Inthisscenario,thecommondatacan
belocatedintheglobalareaofthefunctiongroupandsharedbythe
functionmodulesinafunctiongroup.
Thefunctiongroupsandfunctionmodulesaremaintainedinthefunction
builder.ThetransactioncodetonavigatetothefunctionbuilderisSE37.
Thefunctionmoduleshaveaninterfacetodefinetheinput,output
parameters,andtheerrorexceptions.Errorexceptionscanberaisedin
functionmodulesthroughtheMESSAGEstatementaswellasthrough
classbasedexceptions.Inthischaptertheexceptionsraisedthrougha
MESSAGEstatementwillbedescribedanddemonstrated.InChapter11,
classbasedexceptionswillbedescribedanddemonstratedinfunction
modules.
Therearemorethan300,000SAPsuppliedfunctionmodules,mostof
themusedbySAPforitsowninternalpurpose.Alistof50oddfunction
modulesisgivenattheendofthischapter.Goodenoughforabeginner.
ExamineorViewanSAPDeliveredFunctionModule:SPELL_AMOUNT
YouwillexaminetheSAPdeliveredfunctionmoduleSPELL_AMOUNT.
Thisfunctionmoduleconvertsanamountfigureintotextorwords.It
takesfourinputparameters:
AnAmountFigure(DDICDataTypeCURRetc.)Formal
parametername:AMOUNT
ALanguageCode(thelanguageinwhichtoreturnthetextDDIC
DataTypeLANG)Formalparametername:LANUAGE
ACurrencyCode(DDICDataTypeCUKY)Formalparameter
name:CURRENCY
TheSeparatorcharacterorstringbetweenthewords(bydefaulta
space)Formalparametername:FILLER
Thefunctionmoduleoutputparameteristheamountfigureconverted
intotextinthelanguagespecifiedininputparameter.
Abusinessdocument(check,billingdocument,etc.)inmostcountries
musthavetheamountfigurepresentedintextonthebusinessdocument.
ThefunctionmoduleSPELL_AMOUNTisusedtoconvertamountfigure
intotext.
Letthisfunctionmodulebeexamined.Navigatetothefunctionbuilder
openingscreentransactioncodeSE37enterthenameofthefunction
moduleSPELL_AMOUNT.ThescreenwilllooklikeFigure715.

Figure715.FunctionBuilderInitialScreenExamineFunction
ModuleSPELL_AMOUNT

ClickontheDisplaybutton.Thescreenwillshowseventabs:Attributes,
Import,Export,Changing,Tables,Exceptions,andSourcecode...Click
theAttributestab.ThescreeninFigure716willappear.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

17/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure716.ExamineFunctionModuleSPELL_AMOUNT
AttributesTab

FunctionModule:SPELL_AMOUNTAttributesTab
Therearethreetypesoffunctionmodules(threeradiobuttons):
NormalFunctionModule
RemoteEnabledModule:Thisfunctionmodulecanbecalledin
otherapplicationssuchasJava,DotNet,etc.Itcanbecalledfrom
oneserverwhileitisresidentonanotherserver.
UpdateModule:Likeitsnamesuggests,thesearemeanttoupdate
databasetables.Thereisfurthercategorizationofthistypeof
functionmodule.
Onlythenormalfunctionmodulewillbeconsideredinthisbook.Itwas
mentionedearlierthatafunctionmoduleisassignedtoafunctiongroup.
ThefunctiongrouptowhichthisfunctionmoduleisassignedisF017.The
functionmoduleisassignedtoapackageIDCSC.
Next,clicktheImporttab.Theimportorinputparametersarelistedin
thistab.ThescreenisshowninFigure717.

Figure717.ExamineFunctionModuleSPELL_AMOUNT
ImportTab

FunctionModule:SPELL_AMOUNTImportTab
Eachrowwillhaveoneimportformalparameter.Thisfunctionmodule
hasfourimportformalparametersasdescribedearlier.
Thistabhasthefollowingcolumns:
ParameterName:Thenameoftheformalimportparameteris
enteredhere.Theformalparameternamesmuststartwithan
alphabetletterandcancontainalphanumericcharacterswith
embeddedunderscores(_).Themaximumlengthofaformal
parameternamecanbe30characters.
TypeandAssociatedType:Withthesetwocolumnentries,youare
assigningatypetoaformalparameter.IntheTypecolumn,you
canenterthekeywordLIKEorTYPE.IntheAssociatedType
column,youcanentertheABAPelementarypredefinedtypes,(C,
Detal.)anobjectname:eitheraDDICobjectorasystemfieldor
theABAPGenericTypes.(AtablelistingtheABAPGenericTypes
canbefoundintheonlinedocumentation:ABAPByTheme
BuiltInTypes,DataObjectsandFunctions
Types

BuiltInData

GenericABAPtypes).Ifnotypeisassignedtoaformal

parameter,thetypeoftheformalparameterisadoptedatruntime
fromthetypeoftheactualparameter.Ifatypeisassignedtoa
formalparameter,thistypeismatchedwiththetypeoftheactual
parameter.Incaseofmismatch,atypeconflictruntimeerroris
triggered.
TheparameterCURRENCYhasbeenassignedthesystemfieldSY
WAERS.ThesystemfieldSYWAERSisofDDICTYPECUKY.The
systemfieldSYWAERSisclassifiedasobsoleteintheSAPABAP
documents.
Defaultvalue:Underthiscolumn,youcanassignadefaultvalueto
theformalparameter.Ifnovalueisreceivedfromtheactual
parameter,thefunctionmodulewillexecutewiththisdefaultvalue
assignedtotheimportformalparameter.
Optional(checkbox):Youcanindicatewhethertheimport
parameterismandatory(checkboxdisabled)oroptional(checkbox
enabled).
PassValue:Ifyouenablethischeckbox,theimportparameteris
receivedbyvalueorelseitisreceivedbyreference(passbyvalue
orpassbyreference).
Shorttext:Ashortdescriptionabouttheimportparametercanbe
optionallyenteredunderthiscolumn.
LongText:Ifyouclickonthisbutton,theSAPenvironmentword

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

18/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

processorscreenappears,whereyoucanenteranelaborate
descriptionabouttheimportparameter.
Allthefourimportparametersinthisfunctionmodule:AMOUNT,
CURRENCY,FILLERandLANGUAGEisoptional,andallarereceived
orpassedbyvalue.
Next,clicktheExporttab.Heretheexportoroutputparametersare
listed.ThescreenwillappearlikeFigure718.

Figure718.ExamineFunctionModuleSPELL_AMOUNT
ExportTab

FunctionModule:SPELL_AMOUNTExportTab
ThistabhastwocolumnslessthantheImporttab:thecolumnsDefault
valueandOptionalareomitted.Theyareirrelevanttoexport
parameters.IfthecheckboxPassValueisenabled,theparameteris
passedbyvalueandresultelseparameterispassedbyreference.The
meaningofparameterpassingbyvalueandresultisthesameasinthe
contextofsubroutines.Thatis,whenthefunctionmoduleisentered,a
localcopyoftheparameterspassedbyvalueandresultismade.All
operationsontheparametersbyvalueandresultareperformedonthe
localcopy.Ifthefunctionmoduleexitswithoutanerrorexception,the
localcopiesarecopiedbacktotheoriginals,ifthefunctionmoduleexits
througherrorexception,originalvaluesofparametersbyvalueand
resultremainunchanged.
Othercolumnsdonotneedexplanation.
Thereisonlyoneexportparameterinthisfunctionmodule
SPELL_AMOUNT.ThisisIN_WORDS.Theparameterisbeingpassed
byvalueandresult.Itisassignedtoatype,theDDICstructureSPELL.
TheDDICstructureSPELLhasthefollowingfieldswithparticularsasin
Table72.
Table72.ExamineFunctionModuleSPELL_AMOUNTField
ParticularsofDDICStructure:SPELL

Outofthe20fieldsinthisstructure,youwillconcernyourselfwiththe
twofields:WORDDDICDataTypeCHAR,length255andDECWORD
DDICDataTypeCHAR,length128.Thefunctionmodulefillsthefirst
fieldWORDwithtextofthefigureornumberbeforethedecimalandfills
thesecondfieldDECWORDwithtextafterthedecimal.
Next,clicktheChangingtab.Heretheinputoutputparametersare
listed.ThescreenwillappearlikeFigure719.

Figure719.ExamineFunctionModuleSPELL_AMOUNT
ChangingTab

FunctionModule:SPELL_AMOUNTChangingTab
Inthistab,youwillenterparametersthatarereceived,aswellassend
values(i.e.,inputoutputparametersorchangingparameters).Thishas
thesamenumberofcolumnsastheimportparameters.Thereisacolumn
fordefaultvalue.EnablingthePassValuecheckboxistohavethe
parameterpassedbyvalueandresultelsebyreference.
Therearenochangingparametersforthisparticularfunctionmodule.
Next,clicktheTablestab.Heretheinternaltableparametersarelisted.
Thescreenwillappearlikethis:
FunctionModule:SPELL_AMOUNTTablesTab

Figure720.ExamineFunctionModuleSPELL_AMOUNT
TablesTab

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

19/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Youcanentertheinternaltableparametersinthistab.Theinternal
tablescanbepassedthroughothertabsaswell(import,export,
changing).Whenyouenterinternaltableparametershere,theyare
passedbyreference(thereisnoPassValuecheckboxcolumn).Thereis
noDefaultvaluecolumn.
Whenyoupassinternaltablesthroughthistab,youwillimplicitlygeta
headerline(astructureofthesamenameastheformalparameter
name).
Therearenointernaltableparametersforthefunctionmodule.
ClicktheExceptionstab.ThescreenwillappearlikeFigure721.

Figure721.ExamineFunctionModuleSPELL_AMOUNT
ExceptionsTab

FunctionModule:SPELL_AMOUNTExceptionsTab
Asmentionedearlier,errorexceptionscanberaisedinfunctionmodules
througheithertheMESSAGEstatementortheclassbasedexceptions.
Whenyoudevelopandcreateacustomfunctionmodule,youmust
anticipatethepossibleerrorconditionsandprovideexceptionsforthe
possibleerrors.
Theexceptionnamesmuststartwithanalphabetletterandcancontain
alphanumericcharacterswithembeddedunderscores(_).Themaximum
lengthofanexceptionnamecanbe30characters.
ForthefunctionmoduleSPELL_AMOUNT,therearetwoexceptions
listed:
NOT_FOUNDArgumentNotFoundinT015Z
TOOLARGEAmountTooLargetoBeSpelledOut
Allofthenumericaltextusedtoconvertfigureornumberintotextis
storedinthedatabasetableT015Z(seecontentsoftableT015Zasan
exercise).Thefirstexceptionisrelatedtonotabletoretrievetextfora
particularargumentorkeyvalue(theerrorseemstobeabit
hypothetical).
Thesecondexceptionisrelatedtothemaximumupperlimitofthe
numbersubmittedforconversiontotext.Thefunctionmodulesupportsa
maximumoffifteen(15)digitsbeforethedecimal.With15digitsyoucan
representafigureofninehundredninetytrillion...Thisisan
astronomicalfigureinthecontextofthebusinessandcommercialworld.
ClicktheSourcecodetab.ThescreenwillappearlikeFigure722.

Figure722.ExamineFunctionModuleSPELL_AMOUNT
SourcecodeTab(Beginningofthefunctionmodule)

FunctionModule:SPELL_AMOUNTSourcecodeTab
ThefirststatementstartswiththekeywordFUNCTIONequivalenttothe
keywordFORMforasubroutine.Thiskeywordisfollowedbythename
ofthefunctionmodule.
Followingthis,therearethesystemgeneratedcommentlinesdescribing
thefunctionmoduleinterface,thatis,thevariousparametersandthe
exceptions.Ifyouchangethefunctionmoduleinterface,thesecomment
linesareregenerated.
Ifyouscrolldowntotheendofthefunctionmodule,thescreenwilllook
likeFigure723.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

20/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure723.ExamineFunctionModuleSPELL_AMOUNT
SourcecodeTab(Endoffunctionmodule)

ThefunctionmoduleconcludeswiththekeywordENDFUNCTION
equivalenttothekeywordENDFORMofsubroutines.
Allthefunctionmodulestatementshavetobelocatedbetweenthe
keywordsFUNCTIONandENDFUNCTION.Youarenotbotheringabout
theimplementationoflogicinthisfunctionmodule.Touseafunction
module,youdonthavetodoso.Yougenerallytreatthelogic
implementedinanSAPsuppliedfunctionmoduleasanencapsulated
blackbox.Youshouldunderstandwhatthefunctionmoduletakesand
whatitgives:thatis,understandtheparameters.
TheraisingofanexceptioninafunctionmodulewiththeMESSAGE
statementhasthefollowingeffect:
Thesystemfields:SYMSGID,(messageclass/id.)SYMSGNO,
(messagenumber)SYMSGTY,(messagetype)SYMSGV1,(first
placeholder)SYMSGV2,(secondplaceholder)SYMSGV3(third
placeholder),andSYMSGV4(fourthplaceholder)arefilledwith
appropriatevaluesfromtheMESSAGEstatement.Nomessageis
issuedatthisstage.
Furtherexecutionofthefunctionmoduleceases.Thefunction
moduleisexitedandcontrolreturnstotheprogramorprocedure
fromwherethefunctionmodulewascalled.Themessagemaybe
issuedintheprogramcallingthefunctionmoduleusingthesystem
fieldvaluesformessageclass,messagetype,messagenumber,and
theplaceholders.
HandsOnExercise:CALLFunctionModuleSPELL_AMOUNT
Youstillhavetoexaminetherelationshipbetweenfunctiongroups
andfunctionmodulesatthelevelofsourcecode.Thisisbeing
deferred.
Atthisstage,letthefunctionmodule:SPELL_AMOUNTbecalled
orinvokedinanexecutableABAPprogram.Youwillsupplyitwith
theinputs:anumberorfigureinputthroughaPARAMETERS
statementandtherestoftheinputparameters(currencycode,
language,andfiller)asliterals.Thefunctionmodulewillreturn
thetextforinputfigureinthetwofields:WORD,DECWORDofa
structurereferringtoDDICstructureSPELL.Youwilloutputthese
twofieldsifafterreturningfromthefunctionmodule,thevalueof
systemfieldSYSUBRC=0(successful).
Afunctionmodulemayhavemanyparametersanderror
exceptions.Manualcodingofthestatementtocallafunction
moduleinanABAPprogramwillbetedious.TheABAPeditor
enablesthegenerationofthetemplatecodeofcallingfunction
modules.Thistemplatecodehastobecompletedintermsof
providingactualparametersanddecommentingthedesiredlines.
Togeneratethetemplatecodeofcallingfunctionmodules,inthe
ABAPeditor,positionthecursoronthelinefromwhereyouwant
thecallstatementtostart,andclickonthemenuoptions:Edit
Pattern.ThisisshowninFigure724.

Figure724.MenuOptionstoGenerateTemplateCodeofCalling
aFunctionModule

Onselectingthismenuoption,adialogboxwillappearpromptingforthe
statementforwhichtemplatecodeistobegenerated,etc.,asshownin
Figure725:

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

21/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure725.DialogBoxtoGenerateABAPTemplateCodefor
DifferentStatements

Asyouobserveinthedialogbox,thereisprovisiontogeneratetemplate
sourcecodefordifferentABAPstatementssuchasCALLFUNCTION,
MESSAGE,SELECT*FROMetal.Theautogenerationoftemplatecode
worksincaseofCALLFUNCTION(callingafunctionmodule).Inthe
caseofotherstatements,lessofthecodeisgenerated,andmorecodehas
tobeenteredmanually.
Youwantthetemplatecodeforcallingafunctionmodule,sothefirstof
theradiobutton(default)willdo.Enterthenameofthefunctionmodule:
SPELL_AMOUNT.Youcanmakeaselectionfromalist,andasearch
helpisattachedtothisfield(functionkeyF4,etc.).
Thegeneratedtemplatecode,afterpressingthecontinuekeywillbelike
Figure726.

Figure726.TemplateCodeGeneratedforFunctionModule
SPELL_AMOUNT

ObservethatthestatementstartswithCALLFUNCTION...andendswith
aperiodorfullstopappearinginaseparatelinejustabovetheIFSY
SUBRC...statement.ThisisasingleABAPstatementrunninginto
multiplelines.
ThekeywordEXPORTINGisforexportparameters.Theexport
parametersintheCALL...statementaretheimportparametersinthe
functionmodule(callingprogramissendingandfunctionmoduleis
receiving).
ThekeywordIMPORTINGisforimportparameters.Theimport
parametersintheCALL...statementaretheexportparametersinthe
functionmodule(callingprogramisreceivingandtheFunctionmodule
issending).
FollowingthekeywordsEXPORTING,IMPORTING(alsoCHANGING
andTABLES)arenameoftheformalparameters(AMOUNT,
CURRENCY,FILLERetal.)followedbytheequalsign(=).Ontheright
sideoftheequalsign,youshouldprovidetheactualparameter(theequal
sign=shouldbefollowedbyaspaceandthenameoftheformal
parameter).
Thefunctionmoduleexceptionsarelistedwithvalues(NOT_FOUND=
1...).ThesearethevaluesforthesystemfieldSYSUBRC.Youcanmodify
thesevaluesifyouwantto.
Theoptionalformalparameterswiththeexceptionsaregeneratedas
commentlines.Youneedtodecommenttheselines.
ThemessageissuingstatementMESSAGEID...isalsocommented.This
alsoshouldbedecommented.Recallthatwhenanexceptionisraisedin
afunctionmodule,thesystemfieldsSYMSGID,SYMSGNO,SY
MSGTY,SYMSGV1,SYMSGV2,SYMSGV3,andSYMSGV4arefilled
withtheappropriatevalues.Nomessageisissued,andthefunction
moduleisexited.
Thestatementswiththeappropriatemodificationswilllooklikethis:

CALLFUNCTION'SPELL_AMOUNT'"CALLstatementstartshere
EXPORTING
AMOUNT=AMOUNT"amountfigure

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

22/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

CURRENCY='USD'"currencycode
FILLER=''
LANGUAGE=SYLANGU"languagecode
IMPORTING
IN_WORDS=RET_SPELL
EXCEPTIONS
NOT_FOUND=1
TOO_LARGE=2
OTHERS=3
."CALLstatementendshere
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
ENDIF.

Thecompletesourceprogram:
REPORTYCL_CH07_06_CALL_SPELL_AMOUNTLINESIZE170.
*****************************************
*CALLINGFunctionModuleSPELL_AMOUNT**
*****************************************
***************************************************
*inputfiguretobeconvertedPARAMETERSetc.**
*CALLfunctionmoduleSPELL_AMOUNT**
*checkforerror(SYSUBRC<>0)**
*iferror,errormessageelse**
***
*outputSPELLWORD&SPELLDECWORD**
***************************************************
DATA:RET_SPELLTYPESPELL.
PARAMETERS:AMOUNT(16)TYPEPDECIMALS2DEFAULT'87654321.90'.
STARTOFSELECTION.
CALLFUNCTION'SPELL_AMOUNT'"CALLstatementstartshere
EXPORTING
AMOUNT=AMOUNT"amountfigure
CURRENCY='INR'"currencycode
FILLER=''
LANGUAGE=SYLANGU"languagecode
IMPORTING
IN_WORDS=RET_SPELL
EXCEPTIONS
NOT_FOUND=1
TOO_LARGE=2
OTHERS=3
."CALLstatementendshere
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
ELSE.
WRITE/5:RET_SPELLWORD,
RET_SPELLDECWORD.
ENDIF.

YouarecheckingforSYSUBRC<>0(errorcondition),andifthereisno
error,thefieldsRET_SPELLWORDandRET_SPELLDECWORDare
output.TheoutputwilllooklikeFigure727.

Figure727.ProgramYCL_CH07_06_CALL_SPELL_AMOUNT
Output

Thiswasanillustrationofhowafunctionmodulecanbecalledinan
ABAPprogram.
Link,RelationshipbetweenFunctionGroup&FunctionModule
SourceCode(Examine/ViewFunctionModuleSPELL_AMOUNT
Continued)
TheexaminationofthefunctionmoduleSPELL_AMOUNTwillbe
resumed.Therewasadigressiontodemonstratethecallingofthe
functionmoduleSPELL_AMOUNTinanABAPprogram.
FromtheattributestabofthefunctionmoduleSPELL_AMOUNT,you
knowthatthefunctiongroupcontainingthefunctionmodule
SPELL_AMOUNTisF017(refertoFigure710).IntheSE37function
builderopeningscreen,ensurethefieldFunctionModuleisblank,and
selectmenuoptions:Goto

FunctionGroups

DisplayGrouplikeit

isshowninFigure728.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

23/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Figure728.MenuOptionsDisplayFunctionGroup

Thismenuoptionselectionwillpopupadialogboxforinputoffunction
groupnamelikethis:

Figure729.DisplayFunctionGroupEnterName

EnterthenameofthefunctiongroupF017andpressthecontinuebutton.
ThescreeninFigure730willappear.

Figure730.DisplayFunctionGroupF017

ClickontheMainprogrambutton.Thiswilltakeyouto

Figure731.FunctionGroupF017MainProgram:SAPLF017

Whenyoucreateafunctiongroupof,forexample,name
YCL_CH07_GRP01(youwillcreateoneinyournexthandson
exercise),thesystemcreatesanABAPprogramofname
SAPL_YCL_CH07_GRP01oftypeFunctiongroup.(Untilnow,you
havecreatedonlytwotypesofABAPprograms:ExecutableinSE38
andTypePoolinSE11).Thisiscalledasthemainprogram.Recall
fromChapter4thedifferentprogramtypesyoucancreateinABAP
workbench.Observethenamingofthismainprogram.Thesystem
hasprefixedthefunctiongroupnamewithSAPL.Herethefunction
groupnamewasF017thenameofthemainprogramassignedby
thesystemisSAPLF017.
ThemainprogramhastheseprogramlinesofINCLUDE
statements.INCLUDEstatementsincorporatesourceprogram
linesfromotherABAPprogramsthatareofprogramtype
INCLUDE.ObservethenameoftheINCLUDEprograms.Thefirst
INCLUDEprogramnameisLF017TOP,andthesystemhasadded
aprefixofLandapostfixofTOPtothenameofthefunctiongroup.
Similarly,forthenameofthesecondINCLUDEprogram,the
systemhasaddedaprefixofLandapostfixofUXXtothenameof
thefunctiongroup.
ThethirdINCLUDEstatementhasanINCLUDEprogramnamed
LF017F01.ThisINCLUDEstatementwasinitiallyacommented
statement.Inthecommentedstatement,thesystemproposesthe
nameofINCLUDEprograms.
Doubleclickonthestatement:

INCLUDELF017TOP."GlobalData

ThedoubleclickwillnavigateyoutotheINCLUDEprogramLF017TOP.
ThescreenwilllooklikeFigure732.

Figure732.FunctionGroupF017IncludeProgram:LF017TOP

ThisfirstINCLUDEprogramofthefunctiongroupF017hasthe
firststatementFUNCTIONPOOLF017.Thekeyphrase
FUNCTIONPOOLisfollowedbythenameofthefunctiongroup
F017.ThisissimilartoREPORT<nameofprogram>intheABAP
Executableprograms.
ThereareDATA,TABLESstatementsinthisINCLUDEprogram.
ThisINCLUDEprogramwiththefirststatementFUNCTIONPOOL

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

24/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

isafunctiongroupglobaldeclarativearea.Youdeclaredataand
typesthatcanbesharedandreferredinallthefunctionmodules
residinginthisfunctiongroup.
GobacktothepreviousscreenwiththeINCLUDEstatements,thescreen
ofFigure731.NowdoubleclickontheINCLUDEstatement:

INCLUDELF017UXX."FunctionModules

Thescreenwillbelikethis:

Figure733.FunctionGroupF017IncludeProgram:LF017UXX

InthisINCLUDEprogramwithpostfixUXXtherewillbeasmany
INCLUDEstatementsastherearefunctionmodulesinthefunction
group.Initially,whenonlyafunctiongrouphasbeencreatedwithout
anyfunctionmodules,thiswouldbeempty.AsthefunctiongroupF017
containsonlyonefunctionmoduleSPELL_AMOUNTandthereisonly
oneINCLUDEstatement:
INCLUDELF017U01"SPELL_AMOUNT.

ObserveagainthenamingofINCLUDEprogram:PrefixLfollowedby
thefunctiongroupname,followedbythepostfixU01.Ifthereweremore
functionmodules,thesecondfunctionmodulewouldhaveapostfixof
U02andsoon.Thedevelopercanchangethesesystemgeneratednames
withattendanttaskofchangingthesourcecodewhereverareferenceis
madetothesenames.Soitbettertosticktothenamesproposedand
generatedbythesystem.
Ifyounowdoubleclickontheline:

INCLUDELF017U01"SPELL_AMOUNT.

Thesystemwillnavigatetothesourcelinesoffunctionmodule
SPELL_AMOUNT.ThescreenwilllooklikeFigure734:arepeatof
Figure722.

Figure734.FunctionGroupF017IncludeProgram:LF017U01
(SourceLinesofFunctionModuleSPELL_AMOUNT)

ThisisthesourceofthefunctionmoduleSPELL_AMOUNT,withallthe
sourcelinesenclosedbetweenthekeywordsFUNCTIONand
ENDFUNCTION.Itisagoodideatogothroughthesesourcelinesata
laterdate.
Now,gobacktothescreenofFigure731(pressfunctionkeyF3twice).
Doubleclickonthestatement:

INCLUDELF017F01."Subprograms

ThescreeninFigure735willappear.

Figure735.FunctionGroupF017IncludeProgram:LF017F01
(SubroutinesCalledFromFunctionModulesintheFunctionGroup)

ThisINCLUDEprogramcontainsthesubroutinescalledfromthe
differentfunctionmodulesofthefunctiongroup.Ifthereareno
subroutines,thiswillbeempty.Ifasubroutineiscalledfromonlyone
functionmoduleinthefunctiongroup,itcanbelocatedafterthe
ENDFUNCTIONstatementwithinthefunctionmodulecode.Thebetter
choiceistolocateallthesubroutinesinthisINCLUDEprogram.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

25/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Inadditiontothese,adevelopercanalwaysputadditionalINCLUDE
statementsinthemainprogramwiththeircorrespondingINCLUDE
programs.Thisisthelinkorrelationshipbetweenthefunctiongroupand
thefunctionmodulessourcelines.Itmighttakeawhiletogetthehangof
thestructureorlayoutoftheseINCLUDES.Figure736sumsupthelinks.

Figure736.StructureofaFunctionGroupandtheRelationship
betweenthePrograms

HavingexaminedthefunctionmoduleSPELL_AMOUNTinitsentirety,
thenextstageistocreateafunctiongroupofyourown,locateafunction
moduleinthisfunctiongroup,andthencallthiscustomcreatedfunction
moduleinanABAPprogram.
HandsOnExercise:CreateaFunctionModuletoSplitaString
withoutbreakingaWord
ThefunctionmoduleSPELL_AMOUNTtakes:
Anamountfigure
Alanguagecode
Acurrencycode
Afillerstring
andreturnstheamountfigureconvertedintotextinthelanguageof
languagecodesupplied.Ifyouweretooutputthisreturnedtextonahard
copyofabusinessdocumentlikeacheck,customerbill,purchase,etc.
(typicallyonA4size8.5"x11"),itcouldwordwrapasitisonelongstring.
Itwouldbedesirablethatthesingletextorstringreturnedbythe
functionmoduleSPELL_AMOUNTbesplitintomultiplelinesoftext
withoutbreakingaword(i.e.,awordmustnotsplitfromonelineto
another).Yourproposedfunctionmodulewilldojustthis:splitthesingle
linetextintomultiplelinesofspecifiedcolumnlengthwithoutbreakinga
word,ifthereisnotenoughhorizontalspaceforawordonthecurrent
line,itwillautomaticallyshifttothenextline.
Theproposedfunctionmodulewilltakeasimportparameterasingleline
oftext.Itwillreturnthissinglelineoftextintomultiplelinesloadedinto
anonstructureinternaltableorsimplearray.Theelementofthisarray
willbeofABAPtypeCofaspecifiedlength.Thenumberofcolumnsina
linewillbethelengthofthiselement.Ifyouexpresstheprogramcalling
theproposedfunctionmoduleintermsofsemipseudoABAPcode:

****************************************************************************
*ProgramCallingthefunctionmodulesplittingastring/textinto**
*multipleLines**
****************************************************************************
DATA:SPELL_RETTYPESPELL,
TO_SPLIT_STR(300)TYPEC,
STRNG(35)TYPEC,
STRNG_TABLIKESTANDARDTABLEOFSTRNG.
PARAMETERS:AMTTYPEVBRKNETWRDEFAULT'1234567.50'.
STARTOFSELECTION.
CALLFUNCTION'SPELL_AMOUNT'
EXPORTING
AMOUNT=AMT
CURRENCY='INR'
FILLER=''
LANGUAGE=SYLANGU
IMPORTING
IN_WORDS=SPELL_RET
....
CONCATENATESPELL_RETWORDSPELL_RETDECWORDINTOTO_SPLIT_STR
SEPARATEDBY''.
CALL<proposedfunctionmodule>

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

26/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

EXPORTING
INPUT_STR=TO_SPLIT_STR
TABLES
STR_TAB=STRNG_TAB
...
LOOPATSTRNG_TABINTOSTRNG.
WRITE:/5STRNG.
ENDLOOP.

So,youwillhaveintheproposedfunctionmodule:
AnIMPORTparameterofTYPECorTYPESTRING.(willsupport
bothtypes)
ATABLESparameter(nonstructureinternaltable)
Youwillraiseexceptionsforthefailureoffollowingchecksinthe
proposedfunctionmodule:
YouwillcheckthetypefortheIMPORTparameterandraise
anexceptionifIMPORTparametertypeisnotCor
STRING(theDESCRIBEstatementwillreturnCorg).
RefertoTable47ofChapter4.
YoursecondformalparameterwillbedefinedintheTABLES
tabandthesystemwillautomaticallychecktheactual
parametertypeduringcompiletime.Iftheactualparameter
isnotoftypeinternaltable,asyntaxerrorwilloccurandthe
messagewillbeissuedinthecallingprogram.
Asmentionedearlier,whenafunctionmodulehasaTABLES
parameter,thefunctionmoduleautomaticallycreatesa
headerlineofthesamenameastheformalparametername
(inyourcaseofnonstructureinternaltable,thiswillbean
elementarydataitem).Youwillcheckthetypeforthisheader
lineandraiseanexceptionifitisnottypeC.
ProposedFunctionModuleInterface:
Theproposedfunctionmodulewillhavetwoparameters:
1. IMPORTtexttobesplit
2. TABLEStoreturnthesplittext(withoutbreakingaword)

Itwillhavetwoexceptions:
1. TheIMPORTparameterisnotofTYPECORSTRING.
2. TheheaderlineofTABLESparameterisnotofTYPEC.
TaskstoCreate,CALL,andTesttheProposedFunctionModule
Havingidentifiedtheproposedfunctionmoduleinterface(parameters
andexceptions),letthetasksbeidentifiedandcarriedouttocreate,call,
andtesttheproposedfunctionmodule.
Createafunctiongroup,performconsistencycheckandactivate.
Createtwomessagetextsforthetwoexceptionsinthealready
createdmessageclassYCL_CH07_MCLASS01(transactioncode
SE91).
Createtheproposedfunctionmoduleassignittothefunction
groupcreatedintheprecedingstep.
Enterparameters
Enterexceptions
Entersource
Doconsistencycheck,activatethefunctionmodule

CreateanABAPprogramtocallthefunctionmodule.Inthis
program,inputtheamountfigurethroughtheparameters
statement.
CallthefunctionmoduleSPELL_AMOUNT
CheckforSYSUBRCerror:iferrorexit,elsecontinue
Calltheproposedfunctionmodule
CheckforSYSUBRCerror
Ifnoerror,outputtheunsplitandsplitstring.
CreateaFunctionGroup
OntheSE37functionbuilderopeningscreen,ensureablankinthefield
FunctionModuleandclickonmenuoptionsGoto

FunctionGroups

CreateGroup.
Thismenuselectionwillpopupadialogboxpromptingforthenameof

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

27/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

thefunctiongroupandshorttext.Enterthenameofthefunctiongroup:
YCL_CH07_GROUP01andshorttext.Theusualnamingrulesthatapply
tootherWorkbenchobjectsapplytothefunctiongroupaswell.Thename
spaceforfunctiongroupis26characters.Save.Thesystemwillprompt
forapackage.Assignasusualthe$TMPpackage.Thefunctiongroupis
created.
Thefunctiongroupcreatedisnotinactivestatus.Youneedtoactivatethe
functiongroup.SoagainclickonmenuoptionsGoto
Groups

Function

ChangeGroup.Thesystemwillagainpromptforthenameof

thefunctiongrouptobechanged.Enterthename.Ascreenasshownin
Figure737willappear.

Figure737.FunctionGroup:YCL_CH07_GROUP01Attributes

ClickontheMainprogrambutton.Thiswilldisplaythemainprogram
screeninFigure738.

Figure738.FunctionGroup:YCL_CH07_GROUP01Main
Program

Onthisscreen,clickontheactivatebuttonorthekeycombination
<Ctrl>+<F3>.Theobjectactivationlistwillappear:
ActivateMainProgramandGlobalData
Ensurethatboththemainprogram(SAPLYCL_CH07_GROUP01)and
globaldataprogram(LYCL_CH07_GROUP01TOP)areselectedfor
activationlikeitisshowninFigure739.Afteractivation,goback
(functionkeyF3).ThiswilltakeyoubacktotheChangeFunctionGroup
screeninFigure740.

Figure739.FunctionGroup:YCL_CH07_GROUP01Activation

Figure740.FunctionGroup:YCL_CH07_GROUP01Activated

DonotclickontheSavebutton.Thiswillcreateanewinactiveversion.
ClickonthecancelbuttontonavigatebacktotheSE37openingscreen.
ItisbettertocreatefunctiongroupsinthetransactioncodeSE80.Inthe
transactioncodeSE80,youdonothavetogothroughatediousprocedure
ofactivation.Thefunctiongroupisactivatedasitiscreated.Youwilluse
transactioncodeSE80tocreateWorkbenchobjectsinChapter14.
CreateMessages
GototransactioncodeSE91.Enterthenameofmessageclass:
YCL_CH07_MCLASS01.
SelecttheMessagesradiobutton,andclickontheChangebutton/F6.
Entertextformessagenumbers006,007.Thesetwomessagesare
meantforthetwoexceptionsinthefunctionmodule.Save.Thescreen
willappearlikethatinFigure741.

Figure741.MessageClass:YCL_CH07_MCLASS01Messages

Youhavecompletedthecreationofmessages.
CreateFunctionModule
OnthetransactioncodeSE37openingscreen,enterthenameofthe
functionmoduleas:YCL_CH07_SPLIT_STRING.ClickontheCreate
button/F5.Thesystemwillpromptforthefunctiongroupandtheshort
text.Entertheshorttextandfunctiongroupnameorassignafunction
groupfromtheselectionlist.PresstheSavebutton.Thesystempopsup
aninformationmessage(themainprogramandfunctionpooldonot
startwithY/Z).ThescreenshouldlooklikeFigure742.

Figure742.FunctionModule:YCL_CH07_SPLIT_STRING
AssignFunctionGroup

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

28/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

NextclickontheImporttab.Entertheimportparameter(nspace:30
characters).ClickonthePassValuecheckboxtohavetheparameter
passedbyvalue.ThescreenwilllooklikeFigure743.

Figure743.FunctionModule:YCL_CH07_SPLIT_STRING
ImportParameter

ClickontheTablestab.Enterthetableparameter.Thescreenwillbelike
Figure744.

Figure744.FunctionModule:YCL_CH07_SPLIT_STRING
TablesParameter

Clickontheexceptionstab.Enterthetwoexceptions(namespace30
characters).Thescreenforexceptions:

Figure745.FunctionModule:YCL_CH07_SPLIT_STRING
Exceptions

WhenyouclickontheSourcetab,thesystemwillgeneratethestatements
FUNCTIONandENDFUNCTIONaswellasthecommentsofthe
interfacedescription(parametersandexceptions).Allthefunctionsofan
ABAPeditorareavailablehere.ThisisshowninFigure746.

Figure746.FunctionModule:YCL_CH07_SPLIT_STRING
InitialSourceScreen

ThesourcecodeoffunctionmoduleYCL_CH07_SPLIT_STRINGis
listed.Thelogicemployediselaboratedinthecommentsatthe
beginning:
FUNCTIONYCL_CH07_SPLIT_STRING.
*"
*"*"LocalInterface:
*"IMPORTING
*"VALUE(STRING_TO_SPLIT)
*"TABLES
*"STABLE
*"EXCEPTIONS
*"IMPORT_PARAMETER_TYPE_INVALID
*"RETURN_TABLE_ELEMENT_NOT_TYPEC
*"
**********************************************************
*note:theparameterSTABLEisbeingpassedasTABLES.**
*inyourcaseitisexpectedtobeanunstructured**
*internaltable.infunctionmodulesparameterspassed**
*asTABLESimplicitlygenerateaheaderline.**
*soinyourfunctionmodule,therearetwodataobjects**
*ofthesamenameSTABLE:(i)STABLEunstructured**
*internaltable(ii)STABLEelementarypredefined**
*TYPEC.**
*youarereferringtointernaltableasSTABLE[]and**
*elementarypredefinedTYPEasSTABLE.Strictly**
*speaking,thisisnotnecessary/mandatory.**
***
*youareoperatingdirectlyontheIMPORTparameter**
*STRING_TO_SPLIT.thisisbeingpassedbyvalue.so**
*operationsareonlocalcopy.originalremainsintact**
**********************************************************
**********************************************************
*declaredata.**
***
*check&RAISEexceptions**
***
*REFRESHSTABLE[](removeexistingrows)**
***
*determinelengthofelement&assigntoLEN,CLEN**
*thisisthemaxnumberofcharactersineachrowof**
*splitstring/textbeingreturned**
*LENafterthisassignmentwillremainconstant**
***
*CLENvaluereflectsavailablecharactersinarow**
*atanytime.duringstartofrowCLEN=LEN**
***
*thelogicis:inaloopextractonewordatatime**
*fromSTRING_O_SPLIT(source)andconcatenate/assignto**
*STABLEelementary.(destination)**
***
*ifcolumnsareavailableinSTABLEelementary,**
*CONCATENATEtheextractedword.**
***
*ifcolumnsarenotavailabletoaccommodateextracted**
*word,APPENDSTABLETOSTABLE[].assignwordto**
*STABLEelementary.**
***
*continuethisprocesstillallthewordsare**
*extractedandtransferredtofinaldestinationi.e.**
*unstructuredinternaltableSTABLE[]**
***
*setupunconditionalloopDO.**
*checkifallwordsextractedfromSTRING_TO_SPLIT**

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

29/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

*i.e.STRING_TO_SPLIT=''ifsoEXITloop.**
***
*youareextractingonewordatatimefrom**
*STRING_TO_SPLITintoWORDthroughSEARCH'..'i.e.**
*searchforembeddedblanki.e.morethanonewordin**
*theSTRING_TO_SPLIT.**
***
*ifthisSEARCHissuccess/**
*SYSUBRC=0,SPLITSTRING_TO_SPLITINTOWORD**
*STRING_TO_SPLITi.e.getthefirstwordinWORD,**
*residualtextbackinSTRING_TO_SPLIT.**
***
*ifSEARCHSYSUBRC<>0i.e.onlyonelastwordin**
*theSTRING_TO_SPLIT.assigni.e.WORD=STRING_TO_SPLIT**
***
*determinelengthofWORDandstoreinWLEN**
***
*checkwhetherWLEN<=CLEN.ifsoCONCATENATEWORDto**
*STABLE.**
***
*ifVLENnot<=CLEN,CONDENSESTABLE.APPPENDSTABLE**
*TOSTABLE[].STABLE=WORD.CLEN=LEN**
***
*adjustCLENi.e.CLEN=CLENWLEN1**
*ENDDOendloop**
***
*ifSTABLE<>''APPENDSTABLETOSTABLE[]**
***
**********************************************************
DATA:WORDTYPESTRING,"storeextractedword
TYP(1)TYPEC,"storevariableTYPE
LENTYPEI,"storelengthofstring
CLENTYPEI,"storeavailablecharacters/columns
WLENTYPEI."storeextractedwordlength
************************************
DESCRIBEFIELDSTRING_TO_SPLITTYPETYP.
IFTYP<>'C'ANDTYP<>'g'.
MESSAGES006(YCL_CH06_MCLASS01)RAISING
IMPORT_PARAMETER_TYPE_INVALID.
ENDIF.
DESCRIBEFIELDSTABLETYPETYP."STABLEreferencetotheelementary
"dataitem,STABLE[]referencetoitab
IFTYP<>'C'.
MESSAGES007(YCL_CH06_MCLASS01)RAISING
RETURN_TABLE_ELEMENT_NOT_TYPEC.
ENDIF.
REFRESHSTABLE[]."clearinternaltableofexistingrows
DESCRIBEFIELDSTABLELENGTHLENINCHARACTERMODE."getlengthofelement
CLEN=LEN.
DO.
IFSTRING_TO_SPLITISINITIAL.
EXIT.
ENDIF.
SEARCHSTRING_TO_SPLITFOR'..'."SEARCHforembeddedblank
IFSYSUBRC<>0."lastwordinthetext
WORD=STRING_TO_SPLIT.
STRING_TO_SPLIT=''.
ELSE.
SPLITSTRING_TO_SPLITAT''INTOWORDSTRING_TO_SPLIT.
ENDIF.
WLEN=STRLEN(WORD).
IFSYINDEX=1.
STABLE=WORD.
ELSEIFWLEN<=CLEN.
CONCATENATESTABLEWORDINTOSTABLESEPARATEDBY''.
ELSE.
APPENDSTABLETOSTABLE[].
STABLE=WORD.
CLEN=LEN.
ENDIF.
CLEN=CLENWLEN1.
ENDDO.
IFSTABLE<>''.
APPENDSTABLETOSTABLE[].
ENDIF.
ENDFUNCTION.

TheMESSAGEstatementtoraiseexceptionsissupportedonlyinsidea
functionmoduleandmethodofaclass.ThisformofMESSAGEstatement
isnotacceptableinanexecutableABAPprogram.
CreateanABAPProgramtoCallFunctionModule
TheprogramcallingthefunctionmoduleYCL_CH07_SPLIT_STRINGis
YCL_CH07_CALL_SPLIT_STRING.Thesourcecodeof
YCL_CH07_CALL_SPLIT_STRING:

REPORTYCL_CH07_07_CALL_SPLIT_STRINGLINESIZE150.
**************************************************

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

30/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

*CallingFunctionModuleYCL_CH07_SPLIT_STRING**
**************************************************
***********************************************
*noteonMESSAGEstatement:**
***
*exceptionsraisedinfunctionmodulehas**
*messagetype'S'orstatus.ifyouraise**
*exceptionwithmessagetype'E'orerror**
*theprogramexitsafterreturnfrom**
*functionmodule,onissuingthemessage.**
*youdonotwanttheprogramtobeexit,**
*yetyouwantthemessagetoappearlike**
*anerrormessage.thatiswhyyouhave**
*addedthephraseDISPLAYLIKE'E'withthe**
*messagestatementafterreturnfrom**
*functionmodule'YCL_CH07_SPLIT_STRING'.**
***********************************************
***********************************************
*declaredata.**
*inputamountfigurethroughPARAMETERS**
***
*CALLFUBCTION'SPELL_AMOUNT'..**
*checkSYSUBRCetc.**
*CONCATENATESPELLWORDSPELLDECWORDINTO**
*ISTRSEPARATEDBY''**
***
*CALLFUNCTION'YCL_CH07_SPLIT_STRING'...**
*checkSYSUBRCetc.**
*outputISTR,STRGA(LOOP...ENDLOOP.)**
***********************************************
DATA:STRG(40)TYPEC,
STRGALIKESTANDARDTABLEOFSTRG,
ISTRTYPESTRING,
*ISTRD(300)TYPEN,
SPELLTYPESPELL.
**************************************************
PARAMETERS:AMT(7)TYPEPDECIMALS2DEFAULT
'987654321.50'.
STARTOFSELECTION.
CALLFUNCTION'SPELL_AMOUNT'
EXPORTING
AMOUNT=AMT
CURRENCY='INR'
FILLER=''
LANGUAGE=SYLANGU
IMPORTING
IN_WORDS=SPELL
EXCEPTIONS
NOT_FOUND=1
TOO_LARGE=2
OTHERS=3
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4.
EXIT.
ENDIF.
CONCATENATESPELLWORDSPELLDECWORDINTOISTR
SEPARATEDBY''.
CALLFUNCTION'YCL_CH07_SPLIT_STRING'
EXPORTING
STRING_TO_SPLIT=ISTR
*STRING_TO_SPLIT=ISTRD
TABLES
STABLE=STRGA
EXCEPTIONS
IMPORT_PARAMETER_TYPE_INVALID=1
RETURN_TABLE_ELEMENT_NOT_TYPEC=2
OTHERS=3
.
IFSYSUBRC<>0.
MESSAGEIDSYMSGIDTYPESYMSGTYNUMBERSYMSGNO
WITHSYMSGV1SYMSGV2SYMSGV3SYMSGV4
DISPLAYLIKE'E'.
ELSE.
WRITE:/5ISTR.
SKIP2.
LOOPATSTRGAINTOSTRG.
WRITE:/5STRG.
ENDLOOP.
ENDIF.

Youwillexecutethecallingprogramandtherebytestthatthefunction
moduleisworking.
Lettheexceptionalconditionsbetestedfirst.Thefirstexceptionchecks
thetypeofinputparameter:itshouldbeeithertypeCorSTRING
(DESCRIBEstatementreturnsgfortypeSTRING).Forthistesting,you
candecommentthedatadeclarationofvariableISTRDintheDATA
statement.IntheCALLFUNCTION
YCL_CH07_SPLIT_STRING...statement,youcancommenttheline
STRING_TO_SPLIT=ISTRanddecommenttheSTRING_TO_SPLIT=
ISTRD.ISTRDistypeNandwillresultinexception:
IMPORT_PARAMETER_TYPE_INVALID.Executetheprogram.The
PARAMETERstatementpromptwillappearonthescreen,andpressthe

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

31/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

executebutton/F8.Thescreenwiththeerrormessageonthestatusbar
willappearlikethis:

Figure747.Program:YCL_CH07_CALL_SPLIT_STRING
ExceptionI

Thesecondexceptionchecksforthereturninternaltableelementtypeto
beC.Restorethesourceprogramtostatuspriortotestingoffirst
exception.MaketheSTRGsomeothertypethanC.Runtheprogram.
Thesecondexceptionwillberaised,andthescreenwiththeerror
messageonthestatusbarwillappearlikethis:

Figure748.Program:YCL_CH07_CALL_SPLIT_STRING
ExceptionII

RestorethetypeofSTRGtoC.Executetheprogram.Thedefaultinputof
987654321.50hadbeenchangedto7777777777.50.Theoutputwill
appearlikeFigure749.

Figure749.Program:YCL_CH07_CALL_SPLIT_STRING
Output

ReducethelengthofSTRGfromitsexistingvalueof50to40.Execute
theprogramagain.TheoutputwillappearlikeFigure750.

Figure750.Program:YCL_CH07_CALL_SPLIT_STRING
Output,ReducedLineWidth

Withthereducednumberofcharactersorcolumnsinalinefrom50to
40,theoutputhasextendedfrom3linesinthefirstinstanceto4linesin
thesecondinstance.
Sonowyouhavecreatedandtestedyourownfunctionmodule,whichis
ofsomepracticalusage.
YoucouldhavecreatedsomeDDICobjectsandassignedatypetothe
functionmoduleparametersbyreferencetotheDDICobjects.Butthat
wouldnothavegivenyouscopeforexceptionhandling.Inapractical
scenario,assigningatypetofunctionmoduleparametersbyreferenceto
DDICobjectsshouldbethedesiredprocedure.Here,youhavenotdone
so,inordertousetheexceptionhandingfeature.
Normally,afunctionmoduleisnotcreateddirectly.Thefunctionality
andlogicofproposedfunctionmoduleiscreatedinanormal,executable
ABAPprogram.Thisprogramistestedthoroughly.Itisthentransferred
andfittedintothefunctionmodule.Thisisespeciallytrueoffunction
modulesrequiringsubstantialdatafortesting.
Thefunctionmodulehasitsowntestingenvironment.Youcan,asan
exercisetryouttestingthisfunctionmoduleinSE37testenvironment.
YouhavetestedthefunctionmodulebycallingitinanexecutableABAP
program.
SpecialFunctionModulesConversionRoutines
ConversionRoutinesBackground
InthefirsthandsonexerciseinChapter5(WRITEstatement...)while
havingthefieldKUNNR(customercode/number)outputfromthetable
KNA1,youhadanadditionUSINGNOEDITMASK.Asanexplanation,it
hadmentionedthatthisadditionwastooutputKUNNRwithleading
zeroes:bydefault,theWRITEstatementoutputsKUNNRfieldwith
suppressedzeroes.ItwasalsomentionedthatintheSAPenvironment,
theinternalstorageofdataindatabasetablesisdifferentfromthewayit
presentedonthescreenorprinter.
Soanumericcustomercode(KUNNR)isstoredinthedatabasetablewith
leadingzeroes(acustomercodecanbealphanumericaswell).Thefield
KUNNRisDDICDataTypeCHARandlength10.Whenitisoutput,the
zeroesaresuppressedbydefault.Theideaistosavethelaborofentering
theleadingzeroesbytheenduserduringinput.Anendusercanjust
enter1forthecustomer0000000001onaninputscreenandthe
systemwillautomaticallyinserttheleadingzeroesforinternalstorage.
ConversionRoutinesAssignment
Thebehindthescenesactionofinsertingandsuppressingzeroesis
performedbytheconversionroutinefunctionmodules.Theconversion
routinefunctionmodulesareattachedtodomains.Ifyouopenthescreen
forthedomainKUNNR(fieldKUNNRintableKNA1isassignedthedata
elementKUNNRanddataelementKUNNRinturnisassignedthe
domainKUNNR),youwillseeintheOutputCharacteristicsareaofthe

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

32/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

DefinitiontabandthevalueALPHAenteredinthefieldConvers
Routine.ThisisshowninFigure751.

Figure751.Domain:KUNNRConvers.RoutineALPHA

ConversionRoutineAttributes
Thefullnameofthefunctionmodulesare:
CONVERSION_EXIT_ALPHA_INPUT
CONVERSION_EXIT_ALPHA_OUTPUT
Theconversionroutinefunctionmodulesexistinpairs:aninputversion
andanoutputversion.Theconversionroutinefunctionmoduleshavethe
prefix:CONVERSION_EXIT_followedbythefivecharacter
identification(inyourchosencontextALPHA)followedbythepostfixof
eitherINPUTorOUTPUT.
Atthedomainlevel,onlythefivecharacteridentificationisspecified,
andtheprefixandpostfixareimplicit.InthecaseofALPHA,thefunction
moduleendingwithinputinsertszeroesandtheoneendingwithoutput
suppressesthezeroes.TheALPHAisalsoattachedtothedomainLIFNR
(thedomainassociatedwithvendorcode).Lookthisup,aswellasjust
lookupthefunctionmodules:
CONVERSION_EXIT_ALPHA_INPUT
CONVERSION_EXIT_ALPHA_OUTPUT
Theconversionroutinefunctionmoduleshaveonlytwoparameters:one
importparameternamedINPUTandoneexportparameternamed
OUTPUT.Ifyoucreateyourcustomconversionroutinefunction
modules,youcandefineonlytwoparameters:oneimportparameter
namedINPUTandoneexportparameternamedOUTPUT.
Ifyouarehavingadatabasetablefieldwiththesamecharacteristicsas
KUNNRorLIFNRTYPECHAR,length10,youwantthesameactionto
happen:automaticzeroinsertion/suppression.Youcanusethesame
domainorcreateadomainandassignALPHAtotheconversionroutine
fieldofthedomain.
Fromwhathasbeendescribed,theconversionroutinefunctionmodules
aregettinginvokedbehindthescenes.Youcanalsocalltheconversion
routinefunctionmodulesexplicitlylikeanyotherfunctionmodule.
YouusedtheadditionUSINGNOEDITMASKintheChapter5WRITE
statementtoskiporbypasstheexecutionofconversionroutine
CONVERSION_EXIT_ALPHA_OUTPUT,whichgetsexecutedby
default.ThereisanadditionwhichistheoppositeofUSINGNOEDIT
MASKi.e.USINGEDITMASK<conversionroutineid>.Throughthis
additionwiththeWRITEstatement,youcanhaveforthefieldtheoutput
versionoftheconversionroutineexecuted.Thesyntaxofthestatement:

WRITE:/5......<fieldname>USINGEDITMASK'==<conversionroutineid>...

Aforthcominghandsonexerciseisdemonstratingthis.
Youcanalsodeterminetheconversionroutineassociatedwithafield
withtheDESCRIBEFIELDstatementcoveredearlierinChapter4.
Theexactsyntaxis:DESCRIBEFIELD<fieldname>EDITMASK<edit
maskname>.
Ifyouexecutethefollowinglines:
DATA:KUNNRTYPEKUNNR,
EMASKTYPESTRING.
DESCRIBEFIELDKUNNREDITMASKEMASK.
WRITE:/5'EditMaskofKUNNR:',EMASK.

Itwilloutput:
EditMaskofKUNNR:==ALPHA
TheDESCRIBEstatementreturnstheconversionroutinenameprefixed
by==.
ConversionRoutineHandsOnExercise:1
Inthisprogram,thereisaninputofthefieldCUST_CD.
TheinputfieldisdefinedreferringtothedataelementKUNNR.Soyou
areassuredoftheconversionroutineALPHAinactionforthisfield.
Theusercanenteranumber:forexample,1(just1withoutleading
zeroes).Afterenteringthenumber,pressexecutebutton/F8.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

33/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

ThestatementsfollowingtheeventSTARTOFSELECTIONstartgetting
executed.YouareassigningtheinputfieldCUST_CDtoanotherfield:
STRING10.TheinputfieldCUST_CDwillcontaininternally
0000000001astheconversionroutineALPHA
(CONVERSION_EXIT_ALPHA_INPUT)willinserttheleadingzeroes.
SothefieldSTRING10havingbeenassignedtoCUST_CDwillalso
contain0000000001.
ThefieldSTRING10isdeclaredastypeCandlength10.Thoughthe
fieldsCUST_CDandSTRING10havethesamecharacteristicsoftypeC
andlength10,STRING10isnotassociatedwithdomainKUNNR.So
conversionroutineALPHAisnotinactionforthefieldSTRING10.
YououtputboththefieldsCUST_CDandSTRING10twice.
CUST_CDisoutputwithouttheadditionUSINGNOEDITMASK.This
willoutputwithleadingzeroessuppressedas
CONVERSION_EXIT_ALPHA_OUTPUTisexecutedthroughthe
associationwithdomainKUNNR.
CUST_CDisoutputwiththeadditionUSINGNOEDITMASK.Thiswill
outputwithleadingzeroesasexecutionof
CONVERSION_EXIT_ALPHA_OUTPUTisbypassed.
STRING10isoutputwithouttheadditionUSINGEDITMASK.Thiswill
outputwithleadingzeroesasSTRING10hasnoassociationwithdomain
KUNNR.
STRING10isoutputwiththeadditionUSINGEDITMASK.Thiswill
outputwithleadingzeroessuppressedbecausetheadditionUSINGEDIT
MASKwillexecuteCONVERSION_EXIT_ALPHA_OUTPUT.
Thesourcecode,input,andoutputareshownunder:
REPORTYCL_CH07_08_TEST_CONV_ROUT01.
DATASTRING10(10)TYPEC.
**************************************************
*FunctionmodulesCONVERSION_EXIT_ALPHA_INPUT**
*CONVERSION_EXIT_ALPHA_OUTPUT**
*inaction**
**************************************************
********************************************************
*input:PARAMETERS:CUST_CDTYPEKUNNR**
*assignCUST_CDtoSTRING10(TYPEClength10)**
***
*outputCUST_CD,**
*CUST_CDUSINGNOEDITMASK**
*STRING10**
*STRING10USINGEDITMASK**
********************************************************
PARAMETERS:CUST_CDTYPEKUNNR.
STARTOFSELECTION.
STRING10=CUST_CD.
WRITE:/5'CUST_CD:',CUST_CD,
"outputwithoutleadingzeroes
/5'CUST_CD(USINGNOEDITMASK):',CUST_CDUSINGNOEDITMASK.
"outputwithleadingzeroes
SKIP2.
WRITE:/5'STRING10:',STRING10,
"outputwithleadingzeroes
/5'STRING10(USINGEDITMASK):',STRING10USING
EDITMASK'==ALPHA'.
"outputwithoutleadingzeroes

Figure752.Program:YCL_CH07_08_TEST_CONV_EXIT01
Input

Figure753.Program:YCL_CH07_08_TEST_CONV_EXIT01
Output

ConversionRoutineHandsOnExercise:2and3
Inthishandsonexercise,youwillcreateyourownpairofconversion
routines.Theyare:

CONVERSION_EXIT_ICOMA_INPUT
CONVERSION_EXIT_ICOMA_OUTPUT

ThetwofunctionmodulesinsertandsuppresscommasfornumericTYPE
Pfields.Theinternalstorageofnumericfieldshasbeendescribed
earlier.Youhavealsobeenfamiliarizedwiththedefaultoutputof
numericfieldsandthethousandseparatorsorcommaappearingafter
thousand,million,billion,etc.Thisistomakelargenumericfigures
easilyreadable.

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

34/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Theconversionroutineintroducedaboveinsertsacommacharacteras
pertheIndianbusinesspractice.IntheIndianbusinesspractice,you
havethefirstcommaafterthousandasecondcommaafterhundred
thousandcalledLakh/Lacandathirdcommaaftertenmillioncalled
Crore.Youarestoppingatthis.Sincethisisademonstration,the
functionmodulessupportamaximumfigureof99,99,99,999(i.e.,99
crore,99lac,99thousand...).
Youlocatethetwofunctionmodules
CONVERSION_EXIT_ICOMA_INPUTand
CONVERSION_EXIT_ICOMA_OUTPUTinthesamefunctiongroup
(thisismandatory).ThefunctiongroupisYCL_CH07_GROUP02.
Youwillusetwosubroutinesinthefunctiongroupthatarebeingcalled
fromanoutputconversionroutine.Youwilllocatesomedatainthe
globaldataarea.Thiswasnotessentialbutdonetodemonstrate
declarationandusageofdataintheglobaldataarea.
Thelogicusedmightnotbethebest.Thefocusisoncreationof
conversionroutine,locatingdataintheglobaldataarea,using
subroutinesinthefunctiongroup,anddeployingtheconversion
routines.
ThevariouscomponentsofthefunctiongroupYCL_CH07_GROUP02:
1. MainprogramSAPLYCL_CH07_GROUP02
2. GlobaldataareaLYCL_CH07_GROUP02TOP
3. FunctionmodulesLYCL_CH07_GROUP02UXX
1. LYCL_CH07_GROUP02U01
2. LYCL_CH07_GROUP02U02
4. Includeprogramforsubroutines
1. LYCL_CH07_GROUP02F01

CopythesourceprogramlinesofglobaldatadefinitionsfromtheE
resourceintothefunctiongroupglobaldataarea
LYCL_CH07_GROUP02TOP.Activatethefunctiongroup.
Whenyoudoubleclickontheincludestatementof
LYCL_CH07_GROUP02F0,thesystemwillalertthattheprogramdoes
notexist.Createtheprogram?Thismessagewillappearonthestatusbar
andnotasapopup.Pressthe<Enter>keytocreatetheincludeprogram.
CopythesourcelinesofsubroutinesfromtheEResourceintotheinclude
programLYCL_CH07_GROUP02F01.Activatetheincludeprogramas
wellasthemainprogram.
Toinvokeanddemonstratethefunctionmodules,theABAPexecutable
programs:YCL_CH07_09_TEST_CONV_ROUT02and
YCL_CH07_10_TEST_CONV_ROUT03arecoded.Thesourcecodeof
thefunctiongroup,functionmodulesandexecutableprogramsis
availableintheEResource.CopythesourcelinesfromtheEResource.
TesttheABAPprogramsandthefunctionmodules.
INCLUDEPrograms
Includeprogramshavenotbeenelaboratedupon,forthereasonthat
thereisnotmuchofconceptualityassociatedwiththem.Buttheyare
handyand,likemacros,amodularizationaidatsourcecodelevel.They
helpunclutteringaprogramaswellenablereusability.Youcanmaintain
includeprogramsinSE38ordoubleclickingontheprogramnameofthe
INCLUDEstatement.InSE38,intheprogramattributes,whereyou
wereassigningallthewhileprogramtypeasexecutable,youneedto
assignprogramtypeasIncludeforincludeprograms.Aninclude
programcannotincludeitself.
Thereisnoindependentsyntaxcheckforincludeprograms.Thesource
linesintheincludeprogramundergosyntaxcheckingonlyatthetimeof
syntaxcheckoftheprogramwhereincludeprogramlinesareincluded.
FunctionModulesTidbits
Onthefunctionbuilderopeningscreen,youhavetheusualsetofbuttons
availableonanyoftheABAPWorkbenchobjectmaintenancescreens
andsomemorerelevanttofunctionmodulesandfunctiongroupssuchas:
Checkforconsistencyandactivationbuttons.
Executethebuttonforexecutionofthefunctionmoduleinthe
functionmoduletestenvironment.
Deleteafunctionmodulebutton.
Renameafunctionmodulebutton.
Deletionandrenamingshouldbedonewithcaution.Thesystemchecks
forstaticcallstothefunctionmoduleandwilldisallowdeletionor
renamingifafunctionmoduleisstaticallybeingcalledelsewhere.But
therecannotbeacheckfordynamiccalls.Youhavecalledfunction
moduleswiththeCALLstatement,specifyingthefunctionmodulename

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

35/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

asaliteral(astaticcall).ThereisavariationoftheCALLstatementthat
acceptsavariablecontainingthefunctionmodulename(adynamiccall).
Thesystemcannotchecksuchdynamiccalls.
Copyfunctionmodulebutton.
Reassignafunctionmoduletoanotherfunctiongroup.
Fromthemenu,youcannavigatetotheglobaldata(program:
L<functiongroupname>TOP>)theprogramwiththefirst
statementas:FUNCTIONPOOL,whereyoucandeclareglobal
(globaltothefunctiongroup)typesanddata.
Fromthemenu,youcangotothemainprogram(program:
SAPL<functiongroupname>).AlltheINCLUDEstatementsarein
thismainprogram.
Youcanfromthemenuandnavigatetothedocumentationifitis
available.Thereisseparatedocumentationforthefunctiongroup
andfunctionmodules.
Exceptfordelete,rename,copy,andreassign,otheroptionsare
availableinsidethefunctionmoduleeditorscreenaswell.
ListofaFewFunctionModules
Afew(50odd)SAPStandardfunctionmodulesarelistedinTable73.
Theyarecategorizedundervariousheads.Someofthese,youwillbe
usinginyourhandsonexerciseofforthcomingtopics.Thefunction
modulesnamesinitalicscanbetriedoutasexercisesimmediatelybefore
proceedingtothenextchapter.Contrivescenariostocallthesefunction
modules.Gothroughthefunctionmoduleinterface.Youneednotpassall
optionalparametersalways.
Table73.ListofaFewSAPSuppliedFunctionModules

FunctionModuleName

PopUptoDecide

POPUP_TO_CONFIRM

Description

A2/3Buttonsdialog
Popup

POPUP_TO_INFORM

APopuptoInform

POPUP_TO_CONFIRM_DATA_LOSS

APopuptoConfirm
AbortandLoseData

PopUptoSelect

F4_CLOCK

APopuptoSelect
Time

F4_DATE

APopuptoSelect
Date

POPUP_TO_SELECT_MONTH

APopuptoSelect
Month

POPUP_TO_DECIDE_LIST

APopuptoMake
Single/Multiple
Selections

POPUP_WITH_TABLE_DISPLAY

APopupSelection
fromanInternal
Table,ReturnsRow
NumberSelected

FITRV_CALCULATOR

APopUpCalculator

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

36/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

ConversionRoutines

CONVERSION_EXIT_ALPHA_INPUT

Suppress,Insert
LeadingZeroesin

CONVERSION_EXIT_ALPHA_OUTPUT

CustomerCodeand
VendorCode(Data
TypeCHAR,Length
10)

CONVERSION_EXIT_MATN1_INPUT

Suppress,Insert
LeadingZeroesin

CONVERSION_EXIT_MATN1_OUTPUT

MaterialCode(Data
TypeCHAR,Length
18)

Conversions

ROUND_AMOUNT

RoundingAmount
asperCompany
CodeCurrency

CURRENCY_CODE_SAP_TO_ISO

ConvertCurrency
Code:SAPtoISO

CURRENCY_CODE_ISO_TO_SAP

ConvertCurrency
Code:ISOtoSAP

UNIT_OF_MEASURE_ISO_TO_SAP

UnitofMeasure
CodeISOtoSAP

UNIT_OF_MEASURE_SAP_TO_ISO

UnitofMeasure
CodeSAPtoISO

SPELL_AMOUNT

ConvertAmount
FigureintoText

SO_SPLIT_FILE_AND_PATH

SplittheFullFile
NametoDrive,
Directories,and
FileName

CONVERT_ABAPSPOOLJOB_2_PDF

ConvertSpool
OutputtoPDFFile

Date&Time

ADD_TIME_TO_DATE

UsedinMM
Moduleto
DetermineDateof
ExpiryfromShelf
Life

HR_SGPBS_ADD_TIME_TO_DATE

UsedinHRModule
todetermineEnd
DatebyAdding
Days/Months/Years
toaDate

COMPUTE_YEARS_BETWEEN_DATES

YearsbetweenTwo
Dates

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

37/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

DAYS_BETWEEN_TWO_DATES

DaysBetweenTwo
DatesforInterest
Calculation

MONTH_NAMES_GET

GetAlltheMonth
Namesinan
InternalTablein
SpecifiedLanguage

MONTH_PLUS_DETERMINE

Add/Subtract
MonthstoGet
Forward/Backward
Date

WEEKDAY_GET

GetAlltheWeek
DaysinanInternal
TableinSpecified
Language

Strings

STRING_CENTER

CenteraString

STRING_MOVE_RIGHT

MoveStringRight

STRING_REVERSE

ReverseaString

Files

GUI_DOWNLOAD

DownloadInternal
TabletoaFileon
PresentationServer

GUI_UPLOAD

UploadaFileon
PresentationServer
intoanInternal
Table

F4_FILENAME

DisplaysaDialog
BoxforFile
Selectionfrom
PresentationServer

TMP_GUI_BROWSE_FOR_FOLDER

DisplaysaDialog
BoxforFolder
Selectionfrom
PresentationServer

TMP_GUI_GET_FILE_EXIST

CheckFile
Existenceon
PresentationServer

Lists

SAPGUI_PROGRESS_INDICATOR

Progress
Meter/Indicatorfor
aProcess

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

38/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

Miscellaneous

CLOI_PUT_SIGN_IN_FRONT

GettheSignonLeft

RS_VARIANT_VALUES_TECH_DATA

Retrievevariant
values

RS_VARIANT_EXISTS

Checkvariant
existence

SAP_CONVERT_TO_XLS_FORMAT

Convertinternal
tabledataintoExcel

RS_COPY_SELECTION_SETS

Copyvariantfrom
oneprogramto
another

MG_FIELDNAME_TEXT

Retrievetextsfrom
dataelements

ICON_CREATE

Transfericonname
andtexttoscreen
field

ALV

REUSE_ALV_GRID_DISPLAY

SimpleALVgrid
typedisplay
(Three
Dimensional)

REUSE_ALV_LIST_DISPLAY

SimpleALVlisttype
display
(TwoDimensional)

REUSE_MINIALV_LIST_DISPLAY

ALVgrid(noevent
support)

REUSE_ALV_FIELDCATALOG_MERGE

Createdefaultfield
catalog
(ALVusingfunction
modules)

LVC_FIELDCATALOG_MERGE

Createdefaultfield
catalog
(ALVusingclasses)

REUSE_ALV_COMMENTARY_WRITE

ALVoutputheader
attopofpage

REUSE_ALV_EVENTS_GET

Getpossibleevents
ofanALVlist

REUSE_ALV_BLOCK_LIST_APPEND

AppendALVlisttoa
block

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

39/40

1/5/2016

Chapter7:ModularizationSAPABAP:HandsOnTestProjectswithBusinessScenarios

REUSE_ALV_BLOCK_LIST_DISPLAY

OutputALVBlock

RandomNumbers

QF05_RANDOM

Randomnumber
generator

QF05_RANDOM_INTEGER

Randomnumber
generatorinteger

Conclusion
Intheforthcomingchapters,youwilluseafewoftheSAPsupplied
functionmodules.Youwillnotcreateanycustomfunctionmodules,
though.Goingforwardinthisbook,wheneverthecontextwarrantsa
subroutineandINCLUDEprogram,theywillbecreatedandused.

PREV

Recommended
/ Queue
/ Recent / Topics / Tutorials / Settings / Blog / Feedback / Sign Out
Chapter 6: Internal
Tables
2016 Safari.
Terms of Service / Privacy Policy

NEXT

Chapter 8: Open SQL Data Retrieval

https://www.safaribooksonline.com/library/view/sapabaphandson/9781430248040/9781430248033_Ch07.xhtml

40/40

You might also like