ABAP OO for HCM

download ABAP OO for HCM

of 65

Transcript of ABAP OO for HCM

  • 7/30/2019 ABAP OO for HCM

    1/65

    For SAP int er nal u seP a g e | 1

    A B A P O O f o r H CM

    Auth ors: Gabr ie l Henr ich and Eduardo Bal le.

    1 Contents2 Ver sion h isto ry ........................................................................................................................................... 3

    3 In tr od uct ion ................................................................................................................................................ 4

    3.1 M o t iva t ion .......................................................................................................................................... 6

    3.2 M isu sing ab ap -ob jec t s ....................................................................................................................... 7

    3.3 Furt he r read ing on ob ject or ient at ion ............................................................................................. 83.3 .1 No t es .......................................................................................................................................... 8

    4 Pro ced ur al vs. OO in HCM ......................................................................................................................... 9

    5 Use U M L Class d iagr am s fo r d esign ing ................................................................................................... 10

    6 Test th e b usine ss logic imp lem en tin g Un it te sts ................................................................................ 10

    7 Sep ar at ion o f con cer n s ............................................................................................................................ 11

    8 GLOBAL ob ject s VS loca l ob ject s ............................................................................................................. 12

    9 Local classes in rep o rt s ............................................................................................................................ 12

    10 Class po o ls in glo ba l classes ................................................................................................................ 13

    10 .1 De sign classes w it h a re ason ab le size ............................................................................................ 14

    10 .2 Use Loca l Classes t o M od u lar ize Class Poo ls ................................................................................. 14

    11 Designin g classes w ith cor rect dat a encap sulatio n ........................................................................... 15

    12 M em o ry usage ..................................................................................................................................... 15

    12 .1 W he ne ver po ssible , use Lazy In stan tiat ion .................................................................................... 16

    12.2 Do not mod i fy g loba l da ta in m ethods........................................................................................... 17

    12 .3 Access Att rib u te s in M et ho ds via Selecto rs ................................................................................... 17

    13 In h erit an ce an d p ol ym o rp h ism ........................................................................................................... 18

    14 Stat ic m et ho ds vs. Sin glet on ............................................................................................................... 20

    14 .1 Relat ed gu id elin es............................................................................................................................ 20

    15 In t er fac e com p osit io n.......................................................................................................................... 22

    15 .1 Ad di ti o nal gu ide lin es on in te rf aces ................................................................................................ 23

    15 .1.1 Use Inh er it an ce M od er at ely ................................................................................................... 24

    16 Dat a Types w ith in classes and m et ho d pa ram et ers .......................................................................... 24

    16 .1 Do n ot use ob sole t e Param et er Kind s ............................................................................................ 26

    16 .2 Do no t u se ob sole t e Param et er Typ ings ........................................................................................ 27

  • 7/30/2019 ABAP OO for HCM

    2/65

    For SAP int er nal u seP a g e | 2

    16 .3 Typ e Param et er s as Sp ecif ic as Possible ........................................................................................ 27

    17 Local ty pe s and im plem ent at ion inc lud es of glob al classes ...................................................... 28

    18 Glo bal class w it h m ult iple im ple m ent at ion s ...................................................................................... 30

    19 U sing ev en ts ......................................................................................................................................... 34

    20 Frien d classes ....................................................................................................................................... 35

    20 .1 Ho w to reu se local o bj ect s ou t side th e globa l class ...................................................................... 37

    21 Case stu d y............................................................................................................................................. 38

    21 .1 Case stu dy req uir em en ts: ............................................................................................................... 38

    21 .2 So lu t io n ............................................................................................................................................. 38

    21 .3 Ap pl icat ion lo g im p lem en t at io n: .................................................................................................... 39

    21 .4 Tax on w aget yp es ............................................................................................................................ 39

    21 .5 W o rk f low : ......................................................................................................................................... 39

    21 .6 Result of w o rk f lo w ........................................................................................................................... 40

    21 .6.1 Class d iagra m ........................................................................................................................... 40

    21 .6.2 Sou rce cod e o f classes ............................................................................................................ 41

    21 .6.3 Payr ol l fu n ct io n sou rc e co de ............................................................................................... 46

    22 Ad di t ion al gu ide lin es ........................................................................................................................... 48

    22 .1 Cod ing sty le ...................................................................................................................................... 48

    22 .2 ABAP Ob ject s, M od ula rizatio n, and Pro gram Flow ....................................................................... 5022 .3 Som e Gen eral Hin t s on M od ula rizatio n ......................................................................................... 50

    22 .4 Declar at ion o f t h e Instan ce Con stru ct or ........................................................................................ 52

    22.5 Con tro l Struct ures............................................................................................................................ 54

    22 .6 Han dle Expo rt ing Param et er s Passed by Ref eren ce App rop riat ely ............................................. 55

    22 .7 Jum p Ou t o f M et ho d s On ly via RETURN ........................................................................................ 56

    22 .8 Do no t use CALL M ETHOD fo r sta t ic in vo ke ................................................................................... 57

    22 .9 Typ e an d Dat a Dec larat ion s ............................................................................................................ 57

    22 .10 Reuse Only Data Types th at Exact ly M at ch You r Need s ........................................................... 58

    22 .11 Use th e dat a t yp e ABAP_BOOL as Boole an data ty p e .............................................................. 59

    22 .12 Decl ar e Dat a Ob ject s On ly in Classes ......................................................................................... 59

    22 .13 Use th e TABLES Stat em ent On ly fo r Dyn p ro Str uct u res ........................................................... 60

    22.14 Refer to Data Object s w hen Appro pr iate, ref er to Data Types Oth erw ise ............................. 60

    23 Erro r Han d lin g ...................................................................................................................................... 61

    Exceptions................................................................................................................................................. 61

    23 .1 Asser t io ns ......................................................................................................................................... 64

  • 7/30/2019 ABAP OO for HCM

    3/65

    For SAP int er nal u seP a g e | 3

    23 .2 M essages .......................................................................................................................................... 65

    2 Version h istory Version 1, July 2011: Released

    Version 2, August 2011:

    a . Rev iew o f chap te r Global class w i th m u l t i p le imp lemen ta t ionsb . Rev iew o f chap te r s ing le ton vs sta t i c m e thods w i th code examp le

    c . New chap te r l oca l t ypes / imp lemen ta t ion i nc ludes o f g lobal c lasses

  • 7/30/2019 ABAP OO for HCM

    4/65

    For SAP int er nal u seP a g e | 4

    3 Int roduct ion

    This is a guide to assist on designing n ew HCM appl icat ions or enhancing exist ing f unct ion al i t ies based on ob ject or iented pro gramm ing. This guide w as bu i l t based on recom m endation s from SAP

    deve lopm ent gu ide l ines docum ent and on t he ar t ic le Sta te-o f - the-Ar t ABAP1 in o rder to suppor t bestpract ices on soft ware developm ent bet w een HCM team s. This guide is a lso helpfu l on solving com m on

    issues and even b ad pract ices on ap pl icat ion developm ent .

    Cur rent ly th e great m ajor i ty o f HCM app l ica t ions are im p lemented based on p rocedura l p rogramm ingstyle mainly by r eading and f i l l ing inter nal tables in order t o achieve a speci f ic resul t . There are som e

    reasons why th e procedural programm ing is so com m on amo ng HCM appl icat ions, for examp le:

    The great m ajor i ty of H CM appl icat ion s are processes w h ich m ust be execut ed in batch for ala rge num ber o f emp loyees resu l t ing on m in imum user in te ract ion ; the repor ts a re schedu le to

    run in backgroun d m ode, resul ts are sto red in database or f i les, logs are pr int ed t o systemspools. In m any cases, the on l ine execut ion serves just for t est ing p urpo ses.

    The m ain user int eract ion appl icat ion (pract ical ly the only on e in HCM ) is th e emp loyeem asterdat a tran saction (PA30, PA40, etc), and is bui l t on a mo du le pool fram ew ork. In anycase, the m ain tenance and new deve lopm ents on t h is a rea are not so f requ ent o r no t so

    prob lemat ic .

    M ost o f th e HCM app l ica t ions and foundat ions were deve loped w hen th e on ly abap

    programm ing m ode l ava ilab le w as the procedura l one.

    In m ost cases, the qu ery be tw een emp loyee m asterdata , resu l ts and custom izing tab les is th e

    necessary procedure to achieve a report ing resul t .

    Curren t issues of p rocedural style:

    So lut ion d esigno W hen developing a new bu siness ru le or repo rt t he developer is guided by st ep-by-step

    in terna l tab le opera t ions ( loop ing a t t h is tab le , what has to be do ne fo r each entry?).

    This leads to th e basic recipe: concatenate som e intern al table loop s unt i l a certa in

    level, ma ke som e IFs o r CASEs, and fina lly handle each special case w ith a p rocedu re.o At the end, the n um ber o f simi la r o r redundant FORM S (procedures) is b ig.

    Main tenanceo W hen a repo rt is fresh new , the code loo ks clean and simple. One year later i t is f i lled

    w it h IFs, ELSEIFs an d CASES

    o The procedural style usual ly leads to t he creation o f long repor ts fu l l of g lobal data;

    w hen p er fo rm ing a cor rect ion , i t i s necessary t o study the pract ica lly a l l im p lement a t ionin order t o ensure tha t t h is cor rect ion w i ll no t in f luence - o r b e in f luenced by - o ther

    pro cedures managing t he sam e global data.o Since there are several FORM rou tines wit h sim i lar code w ith in a repor t, you cannot

    for get to check i f your cor rect ion needs to be repl icated in simi lar Form s

    Readabil i ty

    1State-o f- the-Art ABAP: Guidel ines for W rit ing Robust, Understandable, and M ainta inable ABAP Program s. Andreas

    Blument hal, Horst Kel ler - SAP NetW eaver Applicat io n Server ABAP Preprint from a ser ies of art ic les publ ished in t hreesubsequen t issues of th e SAP Profession al Jou rnal, start ing January/ February 20 06

  • 7/30/2019 ABAP OO for HCM

    5/65

    For SAP int er nal u seP a g e | 5

    o Usually th e bu siness ru les for HCM are long and fu l l o f special cases. I t is then di f f icul t tounder stand the basics of a report / fun ct ion, as per th e fo l low ing reasons:

    Repor ts are very lon g; no d ist inct ion bet w een hand l ing special cases fromgeneral cases;

    W hen the FORM procedur es are not very long, usual ly th e cal l stack gets very

    deep.

    W hat are t he advantages of t he OOP in respect to t he issues of pr ocedural style ? Here are a few o f

    t h e m :

    So lut ion d esigno The developm ent of a bu siness ru le or repo rt is guided by m odel ing objects; these

    ob jects can be reused betw een di f ferent app l icat ions.o Class diagrams are a visual part of the d esign docum ent , it f aci l itat es the und erstand of

    the funct iona l ity

    Main tenanceo The general solut ion m odel w i l l remain stable. Speci f ic case changes are m inor

    compared to the so lu t i on m ode l

    o Cor rect ing a general funct ional i ty on th e super class w i l l aut om atically correct a l l chi ldclasses.

    Readabil i tyo Funct ional i ty m od el ing is simp ler

    o th e purpose o f t he funct iona l ity is ev ident due t o i ts pub l ic in te r face(m ethods)

    o Comb inat ion betw een ob ject abstract ion and ob ject po lymorph ism makes the purpose

    und erstanding much m ore easy and sim ple, especially for developers used w ith ot her

    cont em po rary develo pm ent lan guages (java, C++, C#, etc...)

    A n a l o g y b e t w e e n p r o c ed u r a l a n d o b j e c t o r i e n t e d p r o g r a m m i n g

  • 7/30/2019 ABAP OO for HCM

    6/65

    For SAP int er nal u seP a g e | 6

    3.1 Mot ivat ion

    This is chapt er has been extracted from t he art ic le state-of- t he-art-ABAP and serves as a mo tivat ion

    for the u sage o f o b ject -or ien ted p rogram m ing:

    ABAP suppo rts a hybr id p rogram m ing mod el. You can use an object -or iented ( OO ) programm ing

    m o d e l based on classes and in terfaces, and you can use th e m ore classic procedural and event-dr iven

    programm ing mo del based on funct ion m odu les, subrou tines, d ia log m odules, and event b locks. Bot h

    m od els can b e u sed in p arallel. You can u se classes inside classic pr ocessing b locks or you can call classicprocedures f rom m ethods.

    In ABAP Objects, SAP has imp lemen ted a cleanup o f t he ABAP language. W ith in t he scop e of th islanguage cleanup , str icter synt ax checks are perfo rm ed in classes that restr ict t he u sage of ob soletelanguage elem ents. The str icter syntax checks usual ly resul t in a syntax w hich should also be u sed

    outs ide o f ABAP Objects bu t w here the o ld versions cou ld no t be fo rb idden fo r compat ib i l ity reasons.

    The str icter syntax check com prise

    Proh ib i t ing many obso le te s ta tem ents and add i t ions

    Requir ing m any im pl ici t syntax com plet ion s to be expl ici t

    Detect ing and prevent ing potent ial ly incor rect da ta hand l ing

    You can f ind a comp lete l ist o f a l l obsolete language element s t hat are fo rbidden in ABAP Objects in the

    ABAP keyword documenta t ion .

    RecommendationThe ob ject -or ien ted p rogramm ing mod e l p rov ided by ABAP Objects is super io r to th e procedura l

    programm ing mode l , s ince i t o f fe rs be t te r m eans fo r

    1 . D at a e n cap su l at i on

    2 . Exp li ci t ob ject instan t i at i on

    3 . Improved code reuse v ia inhe r i tance

    4 . St an d a lo n e i nt e r fa ce s

    5 . Exp li ci t even t ra i si ng and hand l ingIn add i t ion t o t hese general reasons fo r using ABAP Objects, three mo re speci f ic reasons apply:2

    1. ABAP Objects is simp ler to learn and use than procedura l and event-dr iven ABAP

    2. ABAP Objects has a st r ic te r syn tax check tha t p revents the use o f obso lete language e lem ents

    2 You can f ind a deta i led d escr ipt ion o f these e ight reasons and a com parison o f ABAP Objects to procedural ABAP in N ot Yet

    Using ABAP Objects? Eight Reaso ns Wh y Every ABAP Program m er Sho uld Give it a Second Loo k (SAP Pro fessional Journa l,

    Septem ber/ October 2004). As stated in that art ic le, we b el ieve that pro gramm ing with ABAP Objects m eans programm ing in

    a modern sty le that explo its the benefi t s of a paradigm th at w as invented to solve the pro blems of comp lex soft ware pro jects ob ject o ri en tat io n .

  • 7/30/2019 ABAP OO for HCM

    7/65

  • 7/30/2019 ABAP OO for HCM

    8/65

    For SAP int er nal u seP a g e | 8

    FORM check.

    ENDFORM.

    FORM get_more_data.

    ENDFORM.

    FORM update_ztable.

    ENDFORM.

    But t hat s beside the po int ( I even fou nd a w orse piece of code w here everyt hing was defined as stat ics,

    w h ich actua l ly seems t o be a qu i te com m on pract ice am ong ABAP programm ers w ho are t o ld to use OObut don t understand one b i t o f i t ) . Anyw ay, the po in t is, I was work ing on anoth er p iece o f code w h ich

    requ i red t he funct iona l ity w r i t ten ins ide the check m ethod. But b ecause i t i s wr i t ten ins ide a loca lclass, I cou ld not access th is fu nct ionalit y. It w as not reusable .

    I f th is program w ou ld have been wri t ten w ith a decent OO design and global classes, I w ould have been

    able to u se a dom ain or appl icat ion service class to p erform the check.

    3.3 Furt her reading on object or ientation

    There are many books about ob ject o r ien ta t ion , ob ject -or ien ted p rogram m ing languages, ob ject -

    or ien ted analysis and design, project m anagement for OO p rojects, pat tern s and fram ewo rks, and so

    on. This is a sm al l select ion of goo d boo ks cover ing the m ost im port ant t opics:

    Scot t Am bler, The Object Prim er, SIGS Books & M ult im edia (1996), ISBN: 1884842178A very good in t roduct ion t o ob ject o r ien t a t ion fo r p rogramm ers. It p rov ides compr ehensive

    explanations of a l l essent ia l OO concepts, and cont ains a procedur e m odel fo r learning OO quickly

    and th orou ghly. It is easy to r ead and pract ical, bu t st i l l theor et ically- founded . Grady Booch, Object Solut ions: M anaging the Object-Oriented Project, Add ison-We sley Pub

    Co (1995 ), ISBN: 08053 05947A good book about a l l o f the non - techn ica l aspects o f OO that a re equa lly impo r tan t fo r e f f ect ive

    object-o r iented p rogram m ing. Easy to read and fu l l of pract ical t ips.

    M art in Fow ler, UM L Dist i l led: App lying the Standard Object M odeling Language, Addison-

    W esley Pub Co (1997), ISBN: 0201325632An excel lent b oo k about U M L (Unif ied M odel ing Language - th e new standard ized OO language and

    nota t ion fo r mod e l ing) . Assum es know ledge and exper ience o f ob ject o r ien ta t ion .

    Erich Gam m a, Richard Helm , Ralph Johnson an d Joh n Vlissides, Design Patt erns. Elem ent s of

    Reusable Object -Orient ed Soft w are, Addison-W esley Pub Co (1998), ISBN: 0201634988Provides a pat tern, show ing ho w recurr ing design p roblem s can be solved using objects. This is thef i rst b ig pa t t e rn boo k, cont a in ing many examples o f good OO d esign .

    Jam es Rum baugh, OM T Insights: Perspect ives on M odeling from th e Journal o f Object -Orien t ed Programm ing, Prent ice Hall (1996), ISBN: 0138469652

    A col lect ion of ar t ic les addressing the man y questions and prob lems of OO an alysis and design,

    imp lementa t ion , dependency managem ent , and so on. H igh ly recomm ended.

    3.3.1 Notes

    I f you are n ew to ob ject -or ien ta t ion , you shou ld read Scot t Amb lers The Object Pr imer and then

    acquire some p ract ical exper ience of your o wn . You shou ld defin i t e ly use the CRC techniqu es

  • 7/30/2019 ABAP OO for HCM

    9/65

    For SAP int er nal u seP a g e | 9

    descr ibed by Amb ler and Fow ler for o bject-or ient ed analysis and design. After t h is, you shou ld learnUM L, since th is is the un iversal OO analysis and design no tat io n. Final ly, you should read at least on e

    book about pa t te rns.At the beg inn ing o f a la rge OO p ro ject , th e quest ion imm edia te ly a r ises as to th e sequence in w h ichth ings shou ld be d one, wh ich phases shou ld b e f in ished a t w hat t ime, how to d iv ide up and or gan ize

    the deve lopm ent w ork, how t o m in imize r isks, how to assemble a good team, and so on and so fo r th .M any o f th e best p ract ices o f p ro ject m anagement have had to b e redef ined fo r t he ob ject -or ien tedw or ld , and th e oppor t un i t ies tha t th is has produced are sign i f icant . For fu r th er in fo rmat ion about

    how to use OO in pro ject managem ent , see Grady Brooch s book Ob ject so lu t ions , o r th e chapter

    ent i t les An out l ine d evelopmen t process f rom M ar t in Fow ler s boo k.

    There are , o f course , many o t her good b ooks about ob ject o r ien ta t ion . The above l i st d oes not c la im

    eith er to be com plete, or necessar i ly to recomm end th e best books avai lable.

    4 Procedural vs. OO in HCM

    I t i s d i f f i cu l t and c loset fu l t o adapt ex is t ing legacy fun ct iona l i ty and t ransform i t in t o ob jects, how evernew funct ional i ty branches or new appl icat ions shou ld be designed and implem ent ed as objects. As perSAP standard guidel ines, the creat ion of new FORM s and Function M odules are to b e avoided (exceptfo r very specific cases, see guid elines). Of cour se, th e creatio n of FORM S are actually sti l l a good

    pract ice for m aintain ing corr ect ions of legal funct ion s, w here th e exist ing pro gramm ing and coding style

    shou ld be kept .

    For new funct ional i t ies, the bu siness ru les mu st be designed and imp lemen ted as obj ects; it m ust be

    avo ided the usage o f p rocedural p rogramm ing (and t here fore , no FORM s and no Funct ion m odu les) .W hen designing funct ional i t ies, it m ust be fore seen wh ere these objects m ight be reused, i t is very

    comm on for examp le , tha t a se t o f da ta is needfu l bo th in a payro l l funct ion and in lega l repor ts .

    Now adays, the u sual pract ice of reusing pro cedures on di f feren t p laces is to e i th er use a funct ion

    m odu le or to co py and paste a FORM (or even PERFORM IN PROGRAM !). The copy and p aste of FORM S

    is evident ly harmful , as for t he usage of Funct ions require both t he comp lete instant iat ion of th efunct ion group in to th e session s memo ry and enforces the p rocedura l p rogramm ing sty le ; the sam e is

    valid fo r PERFORM IN PROGRAM .

    The u se of Function m odu les for code reuse is obsolete. The r eason is simp le: a funct ion t hat has to

    suppor t a d i f fe rent n um ber o f scenar ios or behaviors is requ i red to expose a b ig paramet er in te r face(m any of t hem as op tion al) and treat al l cases int ernally chainin g CASES and IFs. M aint enance onfunct ions easi ly creates side effects on ot her funct ional it ies out of t he m aintenances scope.

    New classic report s - according to SAP st andard guidel ines -shou ld be avoided. The recom m endation is

    to bui ld t ransactions cal l ing m ethod s direct ly; select ion screens are - since a long t im e - obsolete;Dynpros should be created on funct ion groups and al l business logic imp lemen ted as objects using M VC

    concept.Except ions fo r these cases are fo r repor t s wh ich m ust be a lso run in b ackground m ode ( the great par t o f

    th e HCM repor ts) or report s w hich use a com plex logical database ( the HCM case).

  • 7/30/2019 ABAP OO for HCM

    10/65

    For SAP int er nal u seP a g e | 10

    Curren tly i t is not p ossib le to af ford ignor ing (rew ri t ing) the fu nct ional i t ies that PNP offers: select ionscreen fram ewo rk w ith HR repo rt ing class, auth or izat ion cont rol and select ion o f emp loyee master data.

    There fore , the recom m endat ions are : New repor ts fo r HCM wi th se lect ion screens are a llowed.

    W henever necessary a new repor t , use i t ju st as a conta iner fo r the o b ject o r ien ted funct iona l ity

    Do not create new includes!

    Do no t creat e new funct ion group s (on ly for m aintenance view s and very special cases, l ike RFCconnect ion)

    In any case, th e creation o f INCLUDES and shar ing includes is to b e forb idden. M odu lar izat ion m ust

    fo l low OO parad igm .

    5 Use UML Class diagr ams for designingClass diagrams are a very useful design t oo l . It f aci li tat es the creation of d esign docum ents and, m ost

    im port ant, faci li tat es th e comp rehension of th e solut ion by oth er col leagues. In m any cases the classd iagram can serve as th e de ta i led design par t o f the d esign document .

    This pract ice also faci li tates the im plem entat ion phase w here a developer can create th e def in i t ion (and

    not th e im p lementa t ion) o f the o b jects fo l lowing th e c lass d iagram, and as soon as the def in i t ions arecreated, the un i t t ests can be w r i t ten . The rea l imp lementa t ion o f m ethods can b e le f t as the last step

    ( test d r iven deve lopm ent) .

    6 Test the business logic implementing Unit t ests

    Unit t ests are the f astest w ay to create aut om ated t est and also serve as regression t ests since th e

    execut ion o f these are automat ical ly in tegra ted wi t h th e Checkman too l on test and consol idat ion

    system s. SAP wants t o increase th e cur rent u t i l i za t ion o f un i t tests w i th in t he standard so f tw are

    (now adays the Ecatts are the m ain aut om ated t est strategy).

    There are some h in ts and gu ide lines on the deve lopment o f u n i t t ests as fo l low s:

    The un i t t ests shou ld n ot depend on custom er custom izing ( tab les type C , o r fea tures)

    The un i t t ests shou ld n ot depend on masterdata nor app l ica t ion tab le en tr ies

    You can bui ld a uni t t est class that inher i ts or is def ined as a fr iend of t he object you w ant t o

    test, in th is w ay you can overw ri te/ bypass/ sim ulate the real database interact ion of t he objectunder t est ing

    In case you need a set o f int ernal tables for use in t he test case, you can use a test dataconta iner instead o f f i ll ing t he in t erna l tab les wi th hardcoded entr ies.

    Un i t tests are th e basis fo r test d r iven deve lopment , wh ere you imp lement t he tests be fore the p ro ject

    imp lemen ta t i on .

    Un i t t ests he lp you t o p ro t ect your code aga inst fu tu re m ain tenance thus avo id ing bugs!

  • 7/30/2019 ABAP OO for HCM

    11/65

    For SAP int er nal u seP a g e | 11

    7 Separati on of concer ns

    The business logic shou ld be separated fro m presentat io n o r logging fun ct ional i ty.The aim is to increase th e reuse of b usiness logic on t he backend side, a l low ing the b usiness logic to b ereused by ot her techno logies (or even fut ure t echnologies)

    Curr ently t he abap repo rts do n ot o ffer any reu se. The usage of t he bu siness logic is l imi ted to th e R3

    repor t s; th e com munica t ion be t ween t he bu siness log ic w i th in r epor ts to externa l serv ices is no tpossible.

    There fore , wh en deve lop ing new funct iona l ity , t ry t o separa te t he ob ject m ode ls f rom the b us iness

    log ic mo de ls and f rom th e user in t e r face , so tha t th ey can be reused w hen appropr ia te .For fu r ther in fo rmat ion on separa t ion o f concerns, you can s tudy th e concepts o f M VC pat te rn .

    Guidel ine fr om SAP standard guidel ines docum ent regarding separat ion o f concerns:

    Prior i ty

    Stro ngly Recomm endedRule

    You should a lways fo l low th e concept o f separat ion of concerns : M odel your appl icat ions str ict ly

    service-or ient ed: a lways disentan gle th e logics for p resent at ion, appl icat ion, and database access. Asoft war e layer should never produ ce data t hat i t con sum es. Especia l ly n o databa se accesses are a l low ed

    in th e layers for p resent at ion o r appl icat ion and vice versa, the persistency and t he appl icat ion layer are

  • 7/30/2019 ABAP OO for HCM

    12/65

    For SAP int er nal u seP a g e | 12

    not a l low ed to carry ou t an o w n user d ia log. Instead, reusable services that are app ropr iate and rel iablem ust be cal led .

    Rationale Separa t ion o f concerns is the b asic program m ing m ode l fo r suppor t ing stab i l ity and m ain ta inab i li ty

    because i t a l low s programm ing of r eusable services and test ing o f bu siness logic by using isolated u ni t

    tests.

    Know n ProblemsNone

    Exceptions

    None

    8 GLOBAL objects VS local objects

    One of t he mo st com mo n im pedim ent s of creating objects for each single business ru le is th at, as a

    com m on b el ief, each single object m ust be created as a global class in SE24. This w ould resul t into anenorm ous quant i ty o f ob jects fo r each sub ject and loca liza t ion . In add i t ion , the ob jects w ou ld a l l be

    scatt ered int o th e sam e package (PB__ and PC__) making i t very di f f icul t t o iden ti fy group s of objectsthat b elong to th e sam e functional i ty or dep endency betw een th em (since al l ob jects are global they al l

    can com mun ica te w i th each o ther d i f fe rent ly than o n Java) .

    The f o l low ing sect ions explains how to structur e th e objects betw een local and global def in i t ions as aw ay to balance visib i l i ty and reu sabi l ity bet w een funct ional i t ies

    9 Local classes in repor ts

    New repor ts m ust conta in no bu siness log ic d i rect ly im p lement ed on i ts body (v ia fo rm s or funct ions, o r

    bu siness lo gic on it s screen s).

    I t is a good pract ice to define local objects wi th in the repor t t o cont rol screen events and out put resul ts.

    For examp le, cal ling a metho d in each report event and t h is meth od w i l l delegate act ion s to sub ob jects.

    As a ru le, com m on r eusable repo rt ing funct ion al i t ies shou ld be encapsulate in g lobal objects and reused

    in di f fer ent r eport s. For exam ple, i t is po ssib le that certa in localizat ion ha s a group o f param eters,search helps and bu tt on s with the same consistency and select ion lo gic in d i f f erent re por ts ( today, viacopy and paste code), th is can be reu sed i f imp lemen ted as objects.

    I t is a bad pract ice to lo cal ly def ine fu nct ional i t ies in a r eport , in case these funct ional i t ies cou ld be

    reused in sim i lar reports.

    Speci f ic report ing logic, wh ich canno t b e reusable in ot her fu nct ion al i t ies, may b e defined as localob jects in th e repor t i tse l f . No new Forms.

  • 7/30/2019 ABAP OO for HCM

    13/65

    For SAP int er nal u seP a g e | 13

    In case you d ont see the im m ediate necessity t o def ine the ob ject as global, you m ay def ine i t lo callyw ith in a repor t, and w hen necessary, migrate i t to a global object (SE24 has an m igrat ion assistan t f or

    local objects in i ncludes)

    M igrating local obj ects to glob al w ith SE24

    10 Class pools in global classes

    Global classes are t he classes def ined in t ransaction SE24; th ey are globally visible w ith in th e system

    sim ilar to a DDIC obj ect (dat a elemen ts, stru ctu res, etc...). There is no technical package dep endency

    betw een objects like in Java, th erefore i t is im po rtant to check if you are author ized to u se the ob jectsfro m t hat specif ic package (di f ferent packages present on a SAP developm ent system m ay not b einstal led on cust om er system s).

    I t is a good p ract ice t o defin e business logic as a global class and b reak dow n th e funct ional i ty int o

    several smal ler ob jects def in ing subclasses into th e bod y of th e global class.The m etho ds and att r ibut es (at least t he pub l ic on es) of a g lobal class are exploi table by ot her o bjects or

    repo rts, how ever, the local objects - def ined int o t he global class are not .

    The global class shou ld expose a l im ited and reasonable num ber of me th ods to the external w or ldand be in t ernally m odular ized w i th a reasonable number of ob jects.

    I t is a good p ract ice to m ake usage of polym orph ism to m odu lar ize th e local objects of t he global class

    a l low ing them to share comm on p roper t ies o f funct iona l it ies.

    I t mu st be taken in to account t ha t impor tan t ob jects m ay not b e ab le to be def ined as local ob jects ,

    since th ey are no t easily reusable in ot her g lobal classes or repor ts. There is on ly one w ay to reuse theimp lemen tat ion of lo cal object s out side t he global class; th is is som ehow useful (see explanation in

    chapter be low) .

    Exam ple of globa l class int erna lly m od ular ized w ith subclasses:

  • 7/30/2019 ABAP OO for HCM

    14/65

    For SAP int er nal u seP a g e | 14

    One t h ing to take care is that local classes of a global class canno t b e stat ically accessed ou tside even in

    inhe ritin g classes or on global fr iend s classes.

    As a conclusion, you can use local classes in a global class to apply int ernal m odu lar izat ion t hus avoiding

    tw o comm on bad pract ices: Global classes with m any m eth ods (publ ic and p r ivate)

    M etho ds wi th large numb er o f code l ines (a m ethod shou ld n ot exceed 50 l ines o f code, as itbecom es un readable and avoids intern al modu lar izat ion / code reuse; see SAP developm ent

    guidelines)

    Two add it iona l gu ide lines linked to th is sub ject ext racted f rom the s ta te-o f - the-ar t abap p rogramm ing :

    10.1 Design classes wi th a reasonable sizeYou shou ld design classes (and fu nct ion grou ps w here ne eded) w i th r easonable size ( that is num ber o f

    m ethods or funct ions) .Rationale

    Classes (or fun ct ion grou ps) shou ld be ded icated to a we l l def ined pu rpose, so t hat n o large class( funct ion group) has to be loaded w h i le on ly one s ing le comp onent ( funct ion m odu le) o f i t i s used.

    10.2 Use Local Classes to Modular ize Class PoolsFor purp oses of int ernal m odular izat ion you m ay use local classes in class pools.

    RationaleThis is prefer able to pr ivate m eth ods of the global class because i t keep s your m ain classes sl im and

    th eir interf aces readable.

  • 7/30/2019 ABAP OO for HCM

    15/65

  • 7/30/2019 ABAP OO for HCM

    16/65

    For SAP int er nal u seP a g e | 16

    In th is way, the m emo ry consum pt ion is reduced imm edia te ly and avo id wa i t ing fo r th e garbageco l lector to do m ost o f the job .

    12.1 Whenever possible, use Lazy Instant iation

    The concept of Lazy Instant iat ion is that m emo ry should on ly be al located w hen n ecessary. In ABAP, t h is

    type o f concept requ i res a d i f fe rent approach, since most o f t he t ime w e have tab les and s t ructurescon tained in classes.

    For handl ing dat abase t able ent r ies, decreasing m em ory usage and in creasing processing speed, abuf fe r o f on ly requ i red ent r ies shou ld b e imp lemented. The p rocess shou ld be th e fo l low ing:

    Th is way, on ly th e data t ha t has been used a t least once is sto red in t he a t t r ibu te , and fu r ther access to

    th e Database isn t required f or t he same ent ry. Of course th is solut ion is only feasib le in th e cases thatat least t he Buff er ized Key is speci f ied com pletely.

    Two guidel ines extracted f rom SAP standard guidel ines docum ent:

  • 7/30/2019 ABAP OO for HCM

    17/65

    For SAP int er nal u seP a g e | 17

    12.2 Do not modify global data in methodsPrior ity

    Recommendat ionRule

    You shou ld rest r ic t th e m odi f ica t ion o f da ta tha t a re g loba l fo r a m ethod (a t t r ibu tes o f t he ow n c lass,pub l ic a t t r ibu tes o f o ther c lasses, g loba l da ta o f the ABAP program) to a m in imum ins ide t he m ethod. I f

    you m odi fy da ta tha t a re g loba l fo r a m ethod ins ide a m ethod, avo id th e mod i f ica t ion o f such g loba l

    data in to o m any m etho ds and. use only dedicated m etho ds that can be recognized, e.g., v ia their

    naming (set_methods) .Rationale

    A met hod should be free of side effects.Know n Problems

    Exceptions

    None

    12.3 Access Att r ibutes in Methods via SelectorsPrior ity

    HintRule

    You m ight u se the appropr iate selectors for accessing att r ibute s of the same class inside the m etho d.Rationale

    Dist ingu ish a t t r ibu tes f rom the m ethod s loca l da ta , if nam ing convent ions are not fo l low ed or no tsuff ic ient.

    Know n ProblemsReadabi l it y of code

    ExceptionsNam ing convent ions are su f f ic ien t fo r th e d ist inct ion .

    Bad Exam pleMETHOD meth.

    DATA lv_var TYPE ...

    mv_attr1 = gv_attr2 + lv_var.

    ENDMETHOD.

    Good Examp leMETHOD meth.

    DATA lv_var TYPE ...

    me->mv_attr1 = class=>gv_attr2 + lv_var.

    ENDMETHOD.

  • 7/30/2019 ABAP OO for HCM

    18/65

    For SAP int er nal u seP a g e | 18

    13 Inher it ance and polymorphism

    Inher i tance and po lymo rphism are perhaps th e ma in advantage of OOP in respect to classic proceduralprogramm ing. These aspects are com m only know n and used in a l l so f tw are deve lopm ent industry . I t i s

    also a key concept fo r code and fun ct ional i ty reu se (see example b elow ).

    This concept is fu l ly suppo rted in ABAP OO and t here is noth ing special to b e taken care of w i th respect

    to o ther p rogramm ing languages (except tha t ABAP does not suppor t m u l t ip le inher i tance) . Deve lopers

    shou ld be encouraged and mo t iva ted t o app ly th e OO design pat te rn s and u se it appropr ia te ly .

    There are some pr ogramm ing pr incip les that can be considered in o rder to assist on o bject m odel ingsuch as: Case- less programm ing and DRY ( don t repeat yo ursel f ; th is pr incip le has been form ulated by

    Andy Hunt and Dave Thom as in their boo k The Pragmatic Program m er; a recom m ended reading).

    Example:

    Bellow , an usual example o f pr ocessing int ernal tables chained w ith a CASE sw itch and call ing a speci f icFORM (com pensation_(x)) fo r each specif ic case. The general reusable FORM rout ine(balance_deb it_cr edit ) also has a specific logic fo r only one case:

    Procedural style:

    .LOOP AT mt_rules INTO ls_rule.

    DO.

    LOOP AT lt_credits INTO ls_credits WHERE tax_code = ls_rule-tax_code1.

    LOOP AT lt_debits INTO ls_debits WHERE tax_code = ls_rule-tax_code2.

    CASE ls_rules-section.

    WHEN 'A'.

    PERFORM compensation_a CHANGING ls_credits ls_debits.

    PERFORM balance_debit_credit CHANGING ls_credits ls_debits.

    WHEN 'B'.

    " similar to 'a' above, just a copy and past with a few differences

    PERFORM compensation_b CHANGING ls_credits ls_debits.

    PERFORM balance_debit_credit CHANGING ls_credits ls_debits.

    WHEN 'C' OR 'D' OR 'E'.

    "similar to the ones above, just a copy and past with a few differences

    PERFORM compensation_c CHANGING ls_credits ls_debits.

    PERFORM balance_debit_credit CHANGING ls_credits ls_debits.

    WHEN OTHERS.

    "...

    ENDCASE.

    PERFORM append_result USING ls_credits ls_debits.

    ENDLOOP.

    ENDLOOP.

    ENDDO.

    ENDLOOP.

    Not ice below , th e special case fo r sect ion = E . th is case is only n ecessary f or o ne sect ion, b ut is passed

    by fo r each oth er sect ion cases. This is a com mo n si tuat ion on ERP appl icat ions implem entingprocedu ral style.

  • 7/30/2019 ABAP OO for HCM

    19/65

    For SAP int er nal u seP a g e | 19

    *&---------------------------------------------------------------------*

    *& Form balance_debit_credit

    *&---------------------------------------------------------------------*

    FORM balance_debit_credit CHANGING p_credit p_debit.

    IF p_credit-amount > p_debit-amount.

    IF p_credit-section = 'E'.

    "something specific for section E

    RETURN.

    ENDIF.

    "do something

    ELSE.

    "do something else

    ENDIF.

    ENDFORM. "balance_debit_credit

    The sam e log ic cou ld be w r i t ten in a c leaner and mo re reusab le s ty le by app ly ing t he OO po lymorph ism:

    LOOP AT mt_rules ASSIGNING .

    DO.

    lr_credit = mr_credits->read_entry( iv_sectn = -sectn1

    iv_tax_code = -tax_code1 ).

    IF lr_credit IS INITIAL.

    EXIT.

    ELSE.

    lr_debit = mr_debits->read_entry( iv_sectn = -sectn2

    iv_tax_code = -tax_code2 ).

    ls_result = lr_credit->compensate( lr_debit ).

    Log(ls_result )

    ENDDO.

    ENDLOOP.

    In th is case, each ob ject (deb it o r credit of typ e A, B, C, D or E) is a child of ob ject o f a m ore genera l tax

    code, inher i t ing the general prop ert ies and overwr i t ing each specific need.

    A cor rect ion or change in t he imp lementa t ion o f one o f these ch i ld ob jects wi ll no t cause a side e f fecton t he ot hers; at the sam e t im e, it is easy to create a side effect on di f feren t t ax codes by m odifying th eFORM balance_debit_credit

    The object or iented pr ogramm ing paradigm is a vast t heory and developers may require t im e to

    becom e a real user of a l l its t echniques and advantages. For exam ple, th e fo l low ing l ink l ist s a var iety o fdesign pat tern s for o bjects:

    h t t p : / / en .wik iped ia .org /w ik i/D esign_pat te rn_(com puter_sc ience)

    h t tp : / /en .wik iped ia .org /wik i /Ob ject -or ien ted_programming

    http://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)
  • 7/30/2019 ABAP OO for HCM

    20/65

    For SAP int er nal u seP a g e | 20

    14 Static methods vs. SingletonAnother very comm on p ract ice now adays is the creat ion o f serv ice m ethods as sta t ic m ethods in g loba l

    classes. For examp le, i t is com m on to see stat ic m ethod s for reading data f rom database tables. Thisappears usefu l s ince th e m ethod can b e ca lled f rom anywhere and a lso a l low s in t ernal bu f f e r ing

    (defin ing stat ic data w ith in m eth ods) avoiding redundan t access to d atabase or recalculat ions.

    A m uch bett er approach t han standalone stat ic met hod s is to use singleton ob jects. Singleton s are

    com m on also in oth er program m ing languages. In abap, a singleton ob ject is character ized for h aving a

    pr iva te constructor and a s ta t ic pub l ic m ethod t ha t re t urns an instance o f t he ob ject ; the f i rst t ime t h ism ethod is ca l led , i t s to res the instance in a s ta t ic at t r ibu te . Th is sta t ic m ethod is comm only know n as

    fac to ry me thod .

    Examp le of singleton f actory m ethod ( t h is case is actual ly considered a m ult i ton since more th an one

    instance can be created accord ing to t he taxcode t ype):

    METHOD get_instance.

    FIELD-SYMBOLS TYPE lty_s_instance.

    DATA ls_instance TYPE lty_s_instance.

    READ TABLE mt_instances ASSIGNING

    WITH KEY taxcode = iv_taxcode.

    IF sy-subrc 0.

    CASE iv_taxcode(1).

    WHEN 'A'.

    CREATE OBJECT lr_tax_code_impl TYPE lcl_taxcode_a.

    WHEN 'B'.

    CREATE OBJECT lr_tax_code_impl TYPE lcl_taxcode_b.

    WHEN OTHERS.

    * RAISE exception cx_invalid_taxcode.

    ENDCASE.

    ls_instance-taxcode = iv_taxcode.

    CREATE OBJECT ls_instance-instance EXPORTING p1, p2, p3...

    APPEND ls_instance TO mt_instances ASSIGNING .

    ENDIF.

    rr_instance = -instance.

    ENDMETHOD.

    There are m any benef i ts on u sing the s ing leton approach; t he m ain one is the contro l o f instan t ia t ion : i ti s poss ib le to instan t iate d i f fe rent instances based on th e key proper t ies o f t he ob ject and keep t r ack o f

    al l instances by using a stat ic internal tab le declared local ly in t he stat ic m eth od ( factor y me tho d). In t h isw ay, w hen th e facto ry m ethod is ca lled f rom a program or ob ject w h ich a l ready instan t ia ted t he

    singleton , i t just retu rns the ref erence of th e exist ing instance instead o f creating a new instance.

    Another b enef i t o f sing le ton compar ing to s tanda lone s ta t ic metho ds is tha t the serv ice m ethod h asaccess to a l l of the ot her ( instance) m eth ods in th e class (since i t is no m ore stat ic) . This is anot her p oint

    tha t he lps the ob ject to be bet t e r mode led w ith in abap workbench.

    A c lass w i th m any sta t ic m ethods w i ll p robab ly share s ta t ic a t t r ibu tes betw een i ts meth ods, lead ing to asim i lar g lobal var iables app roach, wh ich w i l l lead to procedu ral program m ing style w i th in th e

    me thods .

    14.1 Related guidelines(Extracted f rom th e sta te-o f - the-ar t ABAP programm ing ar t ic le ) :

  • 7/30/2019 ABAP OO for HCM

    21/65

    For SAP int er nal u seP a g e | 21

    Consider using pr ivate instantiat ion for your classes (CREATE PRIVATE) and o f fe r

    appropr ia te factory method s5. Th is a l low s you to :

    o Cont ro l the instan t ia t ion o f your c lass f rom w i th in t he c lass

    o Cont ro l th e parameters passed t o t he constructor

    o Handle th e instances of your class w ith in t he class

    o Share the instances of your class effect ively by passing the same object reference to

    d i f fe rent c l ien ts w hen appropr ia te .

    o Release cl ient s from activat ing and d eactivat ing even t h andlers

    Oth er recomm endation s for the p ract ical use of ABAP Objects that g ive your program s an adequatest ructure :

    For pur poses of internal mo dular izat ion , exploi t local classes in class poo ls. This is preferable to

    pr ivate methods of the global class. With that, you can keep your main classes sl im and theirinter faces readable.

    For in te rna l m odu lar iza t ion o f a c lass poo l , p re fer instance m ethods in loca l singletons6 versusstat ic methods of local classes. Two important reasons to prefer instantiat ion over the direct

    use of classes via stat ic m eth ods are

    o That you can u se inher i tance and m ethod redef in i t ions7, i f needed, and

    o That you can contr o l the m om ent o f t he instan t ia t ion and the l i fe t ime o f th e ob ject .

    5 A factory m ethod is a meth od no rm ally stat ic of a c lass that creates an o bject of th at c lass and retu rns a reference that

    po in ts to tha t o b ject .6

    A singleton is an object-or iented pat tern. A c lass def ined accord ing to t he s ingleton p attern is imp lemented in such a way t hatexact ly one o bject can be instant ia ted fro m that c lass. A po ssib le w ay to do so is to def ine a c lass with pr ivate instant ia t ion and

    to use the CREATE OBJECT statem ent in the stat ic constructo r only.7

    Rem emb er, that you cannot redefine stat ic method s in ABAP Objects.

  • 7/30/2019 ABAP OO for HCM

    22/65

  • 7/30/2019 ABAP OO for HCM

    23/65

    For SAP int er nal u seP a g e | 23

    15.1 Addi ti onal guidelines on int erfaces

    W hen you are addressing objects of classes that im plem ent standalone int erfaces, you should general ly

    do so by using interface reference var iables for accessing the interface components (using iref-

    >comp) . I f the class provides an al ias for an interface component, th is component counts as a classcomp on ent and you m ight address i t v ia a class reference var iable and th e al ias nam e. But p lease not e

    that the in ter face component se lector (~) should never be used by the outside user to address an

    interface component of an object via a class reference var iable (don t use cref->intf~comp). The

    reason is th at t he ou tside user s view o f a class should be defined by t he pub l ic inter face off ered by th e

    class. The publ ic interface of a class consists of i ts own class components and can be enhanced byin ter faces. The enhancement o f the pub l ic in te r face o f a c lass wi th in te r face components does not

    in t roduce a new h ierarchy leve l. A l l com ponen ts o f the c lass lie on the same level bu t a re o f fe red f ro m

    different parts of the publ ic interface. This is expressed, by using the two- level-expression iref-

    >comp instead of the three- level cref->intf~comp, w here iref an d cref deno te wh ich par t o f

    the publ ic interface is addressed. Therefore, iref->comp i s m o r e t h an ju st a sh o r tcu t f o r cref->intf~comp. Accessing a class via an interface reference variable always expresses that you areint erested in t he aspect o f t he class that is offered by t he int erface. (See sidebar: Accessing Inter face

    Components.)

    Th is example shows how the in ter face compon ents o f ob jects ( i.e ., the com ponents o f ob jects th a t a recom pon ents of som e interface im plem ent ed by th e object s class) can be accessed and w hich access is

    recomm ended. The in ter face method imeth of t he ob ject re ferenced by cref1 should be accessed

    via an interface reference var iable only. In the object referenced by cref2, i t can be accessed

    alternat ively via i ts a l ias nam emeth. In a l l cases, th e u sage of th e interf ace com ponen t selecto r ~ is no t

    recom mended, because i t in t ro duces a h ie rarch ica l v iew on compon ents tha t t ha t a re par t o f th e same

    level.

    INTERFACE intf.

    METHODS imeth.ENDINTERFACE.

    CLASS c1 DEFINITION.

    PUBLIC SECTION.INTERFACES intf.

    ENDCLASS.

    CLASS c1 IMPLEMENTATION.METHOD intf~imeth....

    ENDMETHOD.

    ENDCLASS.

    CLASS c2 DEFINITION.PUBLIC SECTION.INTERFACES intf.ALIASES meth FOR intf~imeth.

    ENDCLASS.

    CLASS c2 IMPLEMENTATION.METHOD intf~imeth....

    ENDMETHOD.ENDCLASS.

    DATA: iref TYPE REF TO intf,

  • 7/30/2019 ABAP OO for HCM

    24/65

    For SAP int er nal u seP a g e | 24

    cref1 TYPE REF TO c1,cref2 TYPE REF TO c2.

    ...

    CREATE OBJECT: cref1,cref2.

    iref = cref1.

    iref->imeth( ). "recommendedcref1->intf~imeth( ). "not recommended

    iref = cref2.

    iref->imeth( ). "recommendedcref2->meth( ). "recommendedcref2->intf~imeth( ). "not recommended

    15.1.1 Use Inher itance ModeratelyPrior ity

    Recommended

    Rule

    You shou ld u se inher i tance mo derat ely. Especial ly you should avoid d eep inher i tance trees. In case of

    doub t, prefer int erfaces to achieve polymo rphism. For th e reuse of int erfaces, exploi t the concept o finter face comp osit ion in favor to inher i tance.

    RationaleI t i s a lm ost im possib le to change (main ta in ) o t her t han pr iva te compon ents o f superc lass w i th m any

    subclasses. This is especially tr ue f or classes in f ram ew or ks havin g subclass in d iffer ent system s.Know n Problems

    None

    Exceptions

    Appl icat ion is th orou ghly mod eled fo l low ing accept ed and robu st OO-design rules.

    16 Data Types wi thin classes and method parameters

    In m ost occasions, it is necessary t o h andle int ernal t ables with in classes. The abap-objects enforces theusage of tab le types (local or g lobal) on m etho ds signat ures and on att r ibut es.

    It is no t recomm ended to create a DDIC tab le type fo r each single in te rna l tab le tha t you need to

    m anage in t he class. The fo l low ing guidel ines can be fo l low ed:

    For pr iva te / pro t ected a t t r ibu tes and method p aram eter types (valid f or all re leases):

    o I f the in terna l tab le is no t to be pub l ic exposed you shou ld def ine i ts tab le type as an

    local type (see p ictu re be low) :

  • 7/30/2019 ABAP OO for HCM

    25/65

  • 7/30/2019 ABAP OO for HCM

    26/65

    For SAP int er nal u seP a g e | 26

    Take care that on re lease 46c, the changes on t ype pools are not supported by correct ion instru ct ions!

    Som etim es you w i l l need t o ref er to classes defin i t ion s befor e th ey are declared ( inside the localde f in i t ion o f g loba l class fo r examp le); Read t he abap keyw ord do cumenta t ion fo r t he bot h comm andsbe low

    Def in it ion defer red

    Defin i t ion load

    16.1 Do not use obsolete Parameter Ki ndsPrior ityManda to ryRule

    I f you create new f unct ion m odu les or add paramet ers to ex ist ing funct ion m odu les you m ust no t u se

    the parameter k ind TABLES.

    Rationale

    TABLES is an obsolete param eter kind f or int ernal tables w ith h eader l ines.Know n ProblemsNone

    Exceptions

    You add parameters to ex ist ing fun ct ion m odu les tha t a l ready conta in TABLES parameters.Bad Exam pleFUNCTION func.

    *"--------------------------------------------------------------

    *" TABLES

  • 7/30/2019 ABAP OO for HCM

    27/65

  • 7/30/2019 ABAP OO for HCM

    28/65

    For SAP int er nal u seP a g e | 28

    The m ore general ly a parameter is typed, the m ore carefu l you mu st be w hen u sing it in o rder to avo id( run t ime er rors) . On ly com ple te typ ing o f fo rm al param eters guarantees tha t you r code a lways behaves

    in th e sam e way and t hat i t can be t ested local ly.Know n Problems

    None

    Exceptions

    NoneBad Exam pleCLASS cl_class DEFINITION ...

    PUBLIC SECTION.

    METHODS meth IMPORTING iv_p TYPE any.

    ENDCLASS.

    CLASS cl_class IMPLEMENTATION.

    METHOD meth.

    FIND REGEX ... IN iv_p ...ENDMETHOD.

    ENDCLASS.

    Good Examp leCLASS cl_class DEFINITION ...

    PUBLIC SECTION.

    METHODS meth IMPORTING iv_p TYPE csequence.

    17 Local types and implementat ion includes of global classes

    On releases 620 to 701 (SAP HR 470 604), th ere are tw o separate in cludes available fo r defin ing localclasses (or t ypes) and fo r im plem entin g local classes (on release 46c both defin i t ion and im plem entat ionmu st b e done in th e include loca l types ) .

    This separat ion w as actual ly a recom m endation ; SAP has review ed th e recom m endation, stat ing thatbot h includes serve both f or def in i t ion and imp lement at ion o f local classes; In fact the screen oftran saction SE24 has been changed o n basis re lease 7.1 in o rder to clar i fy t he di f f erence betw een t hesetw o inc ludes:

    Re lease 701: But tons to jump to local types and imp lementa t ion inc ludes

  • 7/30/2019 ABAP OO for HCM

    29/65

    For SAP int er nal u seP a g e | 29

    Release 7 .1 : the fo rm er bu t t on imp lementa t ion s is now renamed in order to comply wi th t he new

    recom m endation (see for examp le system EH5).

    Release 7.1: The include local typ es can be f ound at th e Got o m enu and has also b een renam ed.

    The fo l low ing inform ation is d isplayed w hen th ese includes are accessed fo r th e f i rst t im e in tr ansaction

    SE24 in n ew releases:

    New comm ents ins ide include Loca l Def in i t ions/ Imp lem enta t ions:

    * "* use this source f i le for the def ini t ion and implem entat ion of

    * "* local helper classes, interface def ini t ions and t ype

    * " * decla ra t ions

  • 7/30/2019 ABAP OO for HCM

    30/65

    For SAP int er nal u seP a g e | 30

    New com m ent on include Class-Relevant Local Defin i t ion s:

    * "* use this source f i le for any type of declarat ion s (class* "* def ini t ions, interfaces or type declarat ion s) you need for

    * "* components in the pr ivate sect ion

    There are a few technical reasons for w hy is i t b ett er t o def ine local classes in th e form er imp lemen ta t i on i nclude :

    Classes defined in th is include can inher i t and have access to the global class attr ibut es andm etho ds; th is a l low s to explore add i t ional design pattern s (see next chapter)

    Changes on t h is include do not tr igger a fu l l recomp i lat ion of t he global class

    The inc lude o f loca l types can b e used, f rom now on, m ain ly fo r p r iva te da ta t ypes declara t ion and

    def in i t ion / imp lementa t ion o f c lasses re levant on ly fo r the pr iva te sect ion o f the g loba l c lass.

    No thing has been changed from th e com pi l ing poin t-of-view be tw een th e releases (since 470), i t

    regards on ly a be t t e r recomm endat ion on ho w to u se these inc ludes ( the code you deve loped in aspeci f ic include of the global class wi l l a lw ays be suppo rt ed in h igher re leases).

    18 Global class wit h mult iple implementations

    The u sage o f p o lymo rph ism can be s im pl if ied in t e rm s o f numb er o f g loba l ob jects by im p lement inglocal classes ( in a global class) wh ich inher i t fro m the global class i tself . This avoids defin ing on e global

    (reusable) object per each redefin i t ion .

    For examp le : tax codes, conta in ing an amo unt , m ay behave d i f fe rent ly depend ing on t he tax code s type.

    In the examp le below t he global class zcl_taxcode is instant iated as tax code A1 and later as B1 .Both rece ive an amo unt o f 6000,00 w h ich is added to a pr iva te amount a t t r ibu te . However , the

    implem enta t ion fo r t ax code A1 is des igned t o l imi t th e amount to 5000,00 ( the at t r ibu te m ay never

    exceed 5000,00)

    Af te r th e execut ion o f t he s tatem ents be low , th e amount a t t r ibu t e o f tax code A1 wi l l resu l t in 5000,00and B1 w i l l resul t in 6000 ,00

  • 7/30/2019 ABAP OO for HCM

    31/65

    For SAP int er nal u seP a g e | 31

    See below th e technical propert ies and source code f or th is examp le:

    The global class must b e defined as Abstract (abstract constructo r)

    The global class has a (publ ic) constructor for in i t ia l izing pr ivate att r ibutes; There is no prob lemto define t he constructo r as publ ic since the class canno t b e instant iated from out side (abst ract)

    The global class has a pub l ic factory m etho d defined as stat ic that co nt rols th e inst antiat ion o fth e redefined local classes and ret urns th e re levant instance. This met hod can also serve fo rs ing le ton / mu l t i ton im p lementa t ion in t he case you w ant to create on ly one instance o f a tax

    code and retu rn th at instance i f al ready created ( the instance(s) must b e st ored in a pr ivatesta t ic a t t r ibu t e / in t e rna l tab le)

    The g loba l class has a pub l ic method add_amou nt wh ich adds an amount parameter t o t hetaxcode am ount .

    The rea l imp lem enta t ions o f tax codes inher i t f ro m the abstract tax code.

    Class (and lo cal classes) so ur ce code :

    class ZCL_TAXCODE d ef init ion

    pub l icabstract

    create pub l ic .pub l ic sect ion.

    methods CONSTRUCTORimpor t i ng

    ! IV_LGART ty pe LGART .met hods ADD_AM OUNT

    impor t i ng

    ! IV_AMOU NT type F .

    m eth ods GET_AM OUNTre tu rn ing

    value(RV_AM OUNT) type M AXBT .class-met ho ds GET_INSTANCE

    impor t i ng! IV_LGART ty pe LGART

    re tu rn ing

    REPORT z_test.

    DATA lr_taxcode TYPE REF TO zcl_taxcode.

    START-OF-SELECTION.

    lr_taxcode = zcl_taxcode =>get_instance( iv_taxcode = 'A1' ).

    lr_taxcode->add_amount( iv_amount = 6000 ).

    lr_taxcode = zcl_taxcode =>get_instance( iv_taxcode = 'B1' ).

    lr_taxcode->add_amount( iv_amount = 6000 ).

  • 7/30/2019 ABAP OO for HCM

    32/65

    For SAP int er nal u seP a g e | 32

    valu e(RR_INSTAN CE) t yp e r ef to ZCL_TAXCODE .

    pro t ected sect ion .data M V_AMOUNT type M AXBT .

    dat a M V_LGART typ e LGART .

    pr ivate sect ion .end class. " ZCL_TAXCODE d efin itio n

    * "* loca l c lass imp lem enta t ion

    M ETHOD ADD_AMO UNT.m v_amoun t = m v_amoun t + i v_amoun t .

    ENDM ETHOD.

    M ETHOD get_amount .r v_amoun t = mv_amoun t .

    ENDM ETHOD.

    M ETHOD get_instance.CASE iv_lgart (1).

    W HEN 'A' .

    CREATE OBJECT rr_instance

    TYPElcl_taxcode_a

    EXPORTINGiv_lgart = iv_lgart.

    W HEN 'B' .CREATE OBJECT rr_instance

    TYPE

    lcl_taxcode_b

    EXPORTINGiv_lgart = iv_lgart.

    W HEN OTHERS.* RAISE except ion cx_invalid_ta xcode.

    ENDCASE.

    ENDM ETHOD.

    method CONSTRUCTOR.

    m v_lgart = iv_lgart.endmethod .

    endclass. "ZCL_TAXCODE imp lem ent atio n

    * ----------------------------------------------------------------------*

    * CLASS lcl_t axcod e_a DEFINITION* ----------------------------------------------------------------------*

  • 7/30/2019 ABAP OO for HCM

    33/65

    For SAP int er nal u seP a g e | 33

    ** ----------------------------------------------------------------------*

    CLASS lcl_t axcod e_a D EFINITION INH ERITING FROM zcl_taxco de.PUBLIC SECTION .

    M ETHODS add _am ou n t REDEFINITION.

    END CLASS. " lcl_t axcod e_a DEFINITION

    * * ----------------------------------------------------------------------** * CLASS lcl_t axcod e_b DEFINITION

    * * ----------------------------------------------------------------------*

    * ** * ----------------------------------------------------------------------*

    CLASS lcl_t axcod e_b DEFINITION INH ERITING FROM zcl_taxco d e.PUBLIC SECTION .

    M ETHODS add _am ou n t REDEFINITION.

    END CLASS. " lcl_t axcod e_b DEFINITION

    * ----------------------------------------------------------------------** CLASS lcl_t axcod e_a IM PLEM ENTATION

    * ----------------------------------------------------------------------**

    * ----------------------------------------------------------------------*CLASS lcl_t axcod e_a IM PLEM ENTATION.

    M ETHOD add_amoun t .

    supe r->add_am ount ( EXPORTING iv_amoun t = iv_amoun t ) .

    IF m v_am ount > 5000.mv_amoun t = 5000 .

    ENDIF.ENDMETHOD. "add_amount

    END CLASS. " lcl_t axcod e_a IM PLEM ENTATION* ----------------------------------------------------------------------*

    * CLASS lcl_t axcod e_b IM PLEM ENTATION

    * ----------------------------------------------------------------------*

    ** ----------------------------------------------------------------------*

    CLASS lcl_t axcod e_b IM PLEM ENTATION .M ETHOD add_amoun t .

    supe r->add_am ount ( EXPORTING iv_amoun t = iv_amoun t ) .

    IF m v_am ount < 0 .mv_amoun t = 0 .

    ENDIF.

    ENDMETHOD. "add_amount

    END CLASS. " lcl_t axcod e_b IM PLEM ENTATION

  • 7/30/2019 ABAP OO for HCM

    34/65

  • 7/30/2019 ABAP OO for HCM

    35/65

    For SAP int er nal u seP a g e | 35

    20 Fr iend classes

    Friend classes are al low ed to access and m odify t he pr ivate att r ibut e or cal l pr ivate m etho ds of th eot her class (defined as Fr iend). This pract ice is not recom m ended in general since i t m ay easi ly lead to a

    procedura l p rogramm ing mo de l, w here t he a t t r ibu tes o f c lasses are g loba l da ta and m ethods representt he classic FORM S.

    The t ext be low was ext racted f rom the BC401 handbook:

    In som e cases, classes have to w ork to gether so closely th at one or bot h classes need access to the

    others pro tected and p r iva te component s.

    Sim i lar ly, the y need t o b e able to create instances of th ese ot her classes regardless of t he visib i li ty of

    th e constructo rs. To avoid m aking these option s avai lable to a l l users, you can use th e concept o f classfr iendship. A class can pr ovide fr iendship t o ot her classes and int erfaces (and hence al l c lasses that

    imp lemen t th e in ter face) .

    This is the p urpo se of th e FRIENDS addi t ion of th e CLASS statem ent and t he Fr iends tab in th e Class

    Bui lder. There, a l l c lasses and int erfaces that grant fr iendship are l isted. In p r incip le, granting fr iend shipis one-sided: A class granting fr iendship is no t aut om atically a fr iend o f i t s fr iends. If a class granting

    fr iendship w ants to access th e non-publ ic compo nent s of a fr iend , th is fr iend m ust a lso expl ici t ly grantf r iendsh ip to i t .

    Figure 160 : Defin i t ion of Fr iendship Relat ionships

    The f r iend pr opert y is inher i t ed: Classes that inher i t fro m fr iends and inter faces contain ing a fr iend (as acomp on ent int erface) a lso becom e fr iends. Therefore, extrem e caut ion is advised wh en grant ing

  • 7/30/2019 ABAP OO for HCM

    36/65

  • 7/30/2019 ABAP OO for HCM

    37/65

    For SAP int er nal u seP a g e | 37

    20.1 How to r euse local objects outside the global class

    In case you need a general object w i th m any redefined ob jects ( for examp le: tax groups w ith simi larcalculat ion ) you m ay redef ine th is object as local classes and use th ese local classes instances outs ide

    th e global class as long as the genera l object is def ined as global (th e local classes mu st inher it a globalint erface(s) of global class).

    This is possib le bu t no t n ecessar i ly th e best p ract ice among o bject m odel ing. This pract ice can b e useful

    m ainly on cases in wh ich th ere is a restr ict ion on creating a large num ber of g lobal classes.

  • 7/30/2019 ABAP OO for HCM

    38/65

    For SAP int er nal u seP a g e | 38

    21 Case study

    The case s tudy demo nstra tes the usage o f ob ject o r ien ted p rogram m ing fo r a payro l l funct ion .The business logic in th is example do es not repr esent an y real logic, but o nly i l lustrat ive calculat ions

    that cou ld be confron t ed w i th rea l cases.

    The ob jectives in t his case stu dy are:

    M odel bu siness logic as object or ient ed

    Reuse of fun ct ional i ty

    Separation of concerns regarding app l icat ion log (user interf ace)

    Technical t argets o f t h is case stud y:

    M odel ing objects and pr ocesses

    Good u sage of int erfaces Inher i tance

    Polymorphism

    Exploit ing Event s

    Data en capsulat ion

    21.1 Case study r equir ements:

    Business logic requirements:

    I t is necessary to calculate a f ew speci f ic taxes over certa in incom e w agetypes8 w hen th ese are

    tran sferred to ta ble RT

    9

    . There are tw o kinds of t axes:

    o The usual tax is calculated based on 20 % of th e to ta l taxable incom e

    o The s tate t ax is ca lcu la ted a lso based o n 20% o f t he t o ta l taxab le incom e, however

    th is tax is l imi t ed to 100,00.

    The taxab le income is ident i f ied b y a l l wagetypes tha t a re nam ed star t ing wi t h characters /1 .

    App l icat ion speci f ic requirem ents:

    The app l icat ion shou ld present a Trace log show ing all calculat ions perform ed step by step

    By som e technical reason, th e payrol l consul tant s w ant th e stat e tax to be blocked form od if icat ion s in fur t her processing whenever i ts amou nt reached th e legal l imi t o f 100,00.

    21.2 Solut ion

    The implementa t ion o f th is case s tudy is com posed b y th e fo l low ing ob jects :

    W agetype: each w agetype represent an emp loyee speci f ic amou nt , like incom e, tax, deduct ions,etc.. ; th e wagetyp e is basical ly compo sed by i ts name and an am oun t.

    8Em plo yees relat ed salaries, incom es, deductio ns, et c...

    9During payro l l calcu lat io n, tab le RT con ta ins f ina l amo unts, w hich are no m ore m odif ied during payro l l execution .

  • 7/30/2019 ABAP OO for HCM

    39/65

    For SAP int er nal u seP a g e | 39

    Tax wa getype: inher i ts fro m th e general wagetyp e, but has an speci f ic bu siness logic to

    determ ine its tax amount based on 20% of income

    Stat e-tax wagetype: inher i ts from th e tax wagetype, having an addi t ional logic to l imi t i ts taxam oun t to 100,00 and lock i ts m od if icat ion aft er reaching the 100,00 l imit .

    Table RT: an ob ject t hat r epresents a col lect ion o f w agetyp es

    Log hand ler : an ob ject to hand le th e app l ica t ion log

    Interf ace loggable : any objects that inher i t th is interf ace becom e loggable by th e loghandler. In th is case, a ll waget ypes and t he RT table w i l l log on th e appl icat ion .

    Payrol l funct ion : an ob ject to cont rol t he calculat ion f low ; For keeping the examp le simp le, i tw i l l be a local class w ith in a repo rt.

    21.3 Appl ication log implementation:

    The loggab le in t e r face o f fe rs an event in w h ich o b jects can not i fy wh en a cer ta in act ion o ccur red; th isevent im port s a few p aram eters l ike th e m essage text, object nam e, message typ e.

    The wagetyp e objects (and also RT table) ra ise events to n ot i fy th e log when the certa in act ion soccur red, l ike wh en a wagetype was created, o r w hen an amoun t w as added to t he wagetype.

    The log handler cal ls the approp r iate UI service ( in t h is case it is simply a w r i te in th e screen).

    21.4 Tax on wagetypesThe tax on t ax wagetypes are deter m ined by a handler that l isten s to w hen a taxable incom e is added t oRT.

    21.5 Work flow:The fo l low ing tax w agetypes are instan t ia ted :

    Tax / 600 wi th am ount = 0

    State tax wi th am ount / 650 = 0 .

    The wagetypes incom e wagetyp es are instant iated:

    / 1 01 : w it h am oun t 100 0 ,00

    / 102 : w it h am ou n t 200 0,00

    / 103 : w it h am ou n t 300 0,00

    Later, th e amo unt 1000,00 is added t o / 103 , and then t hese incom e wagetyp es are added to RT.

    Final ly the tax w agetypes are added to RT and th e processing is f in ished.

  • 7/30/2019 ABAP OO for HCM

    40/65

    For SAP int er nal u seP a g e | 40

    21.6 Result of workf lowThis is the log wr i t ten by th e funct ion fo r the w orkf low above:

    / 600 - I - w t cr ea ted - 0.0 0

    / 650 - I - w t cr ea ted - 0.0 0

    / 101 - I - w t cr ea ted - 1000 .00

    / 600 - I - am oun t ad ded - 200 .00

    / 650 - I - am oun t ad ded - 200 .00

    / 650 - I - add t o t ax - am o un t lim it ed t o 100 an d lo ck ed

    / 101 - I - w t ad ded t o RT - / 101 10 00 .00

    / 102 - I - w t cr ea ted - 2000 .00

    / 600 - I - am oun t ad ded - 400 .00 / 650 - I - add t o t ax - w ag et yp e is l ock ed an d cannot b e m od if ie d

    / 102 - I - w t ad ded t o RT - / 102 20 00 .00

    / 103 - I - w t cr ea ted - 3000 .00

    / 103 - I - am oun t ad ded - 1000.0 0

    / 600 - I - am oun t ad ded - 800 .00

    / 650 - I - add t o t ax - w ag et yp e is l ock ed an d cannot b e m od if ie d

    / 103 - I - w t ad ded t o RT - / 103 40 00 .00

    / 650 - I - add t o t ax - w ag et yp e is l ock ed an d cannot b e m od if ie d

    / 600 - I - w t ad ded t o RT - / 600 14 00 .00

    / 650 - I - add t o t ax - w ag et yp e is l ock ed an d cannot b e m od if ie d

    / 650 - I - w t ad ded t o RT - / 650 10 0.00

    21.6.1 Class diagram

  • 7/30/2019 ABAP OO for HCM

    41/65

    For SAP int er nal u seP a g e | 41

    21.6.2 Sour ce code of classesAll sou rce code can be accessed in d evelopm ent system L7D, program zgh_teste2. The source cod ebe low was pr in ted f rom the SE24 t ransact ion ; there are som e uppercase/ low ercase fo rm at t ing

    di f ferences.

    2 1 .6 .2 .1 I n te r fa ce Z I F_LO GGAB LE

    interface ZIF_LOGGABLE

    public .

    events LOGPOINT_ADDED

    exporting

    value(IV_MESSAGE_TEXT) type CLIKE optional

    value(IV_MSG_TYPE) type MSGTY optional

    value(IV_EVENT_NAME) type CLIKE optional

    value(IV_OBJECT_NAME) type CLIKE optional .

    endinterface.

  • 7/30/2019 ABAP OO for HCM

    42/65

    For SAP int er nal u seP a g e | 42

    2 1 .6 .2 .2 W a g e t y p e o b j e ct

    class-poo l .

    class ZCL_W T def in i t ion

    publ ic

    create pu bl ic .

    publ ic sect ion.

    interfaces ZIF_LOGGA BLE .da ta M V_LGART typ e LGART read-only .

  • 7/30/2019 ABAP OO for HCM

    43/65

    For SAP int er nal u seP a g e | 43

    * "* local class imp lement at ion

    M ETHOD add_amoun t .DATA lv_t ext TYPE strin g.

    m v_amo un t = mv_am oun t + i v_amoun t .lv_ text = iv_amoun t .

    RAISE EVENT logpoin t_added

    EXPORTING iv_message_text = lv_textiv_m sg_type = ' I '

    i v_event_nam e = 'amoun t added 'iv_object_nam e = m v_lgar t .

    RAISE EVENT amount_added EXPORTING iv_amoun t = iv_amount .

    ENDM ETHOD.

    me t h o d ADD_WT.add_amoun t ( i r_wt ->mv_amoun t ) .

    endmethod .

    M ETHOD constructor .

    DATA lv_t ext TYPE strin g.m v_lgart = iv_lgart.

    m v_amoun t = iv_amoun t .l v_tex t = m v_amoun t .RAISE EVENT logpoin t_added

    EXPORTING iv_message_text = lv_text

    iv_m sg_type = ' I 'i v_event_nam e = 'wt created '

    iv_object_nam e = m v_lgar t .RAISE EVENT wt_created EXPORTING ir_wt = me.

    ENDM ETHOD.

    me t h o d GET_AM OUNT.

    rv_amoun t = mv_amoun t .

    endmethod .

    endclass. "ZCL_ W T im plem entat ion

    2 1 .6 .2 .3 R T c l a ss

    class-poo l .

    TYPES: BEGIN OF lty _s_rt,

    lgart TYPE lgart,o_ w t TYPE REF TO zcl_w t,END OF l ty _s_rt.

    TYPES lty _t _rt TYPE TABLE OF lty_ s_rt .

    class ZCL_RT def in i t ion

    publ ic

  • 7/30/2019 ABAP OO for HCM

    44/65

    For SAP int er nal u seP a g e | 44

    create pub l ic .

    publ ic sect ion.

    interfaces ZIF_LOGGA BLE .events WT_INSERTED

    export ingvalue(IR_WT) typ e ref to ZCL_WT .

    m etho ds INSERT_WTimpor t i ng

    !IR_W T type ref to ZCL_W T .

    m ethod s GET_WT

    impor t i ng!IV_LGART type LGART

    re tu rn ing

    value(RR_WT) typ e ref t o ZCL_W T .

    private sect ion.aliases LOGPOINT_AD DED

    fo r ZIF_LOGGABLE~LOGPOINT_A DDED .

    dat a M T_WTS typ e LTY_T_RT .ev en t s W T_ACCESSED

    export ingvalue(IR_WT) typ e ref to ZCL_WT .

    endclass. "ZCL_RT de finit ion

    * "* local class imp lement at ion

    M ETHOD inser t_wt .DATA ls_wt LIKE LINE OF m t_w ts.

    DATA lv_amou nt TYPE m axbt.DATA lv_t ext TYPE strin g.FIELD-SYM BOLS LIKE LINE OF m t_ w ts.

    lv_am ount = i r_wt ->get_amoun t( ) .

    READ TABLE m t_w ts ASSIGNING W ITH TABLE KEY lgart = ir_w t->m v_lgart .IF sy-sub rc = 0.

    -o_wt ->add_wt ( ir_wt ) .ELSE.

    ls_w t- lgar t = i r_wt ->mv_lgar t .

    l s_wt -o_wt = i r_wt .APPEND ls_wt TO m t_w ts.

    ENDIF.

    RAISE EVENT w t_in serte d EXPORTING ir_w t = ir_ w t.lv_ text = lv_amoun t .

    CONCATENATE ir_w t->m v_lgart lv_text INTO lv_text

    SEPARATED BY space .RAISE EVENT lo gpoin t _added

    EXPORTING iv_m essage_t ext = lv_te xt

    iv_m sg_type = ' I '

    iv_event _name = 'WT added to RT'

    iv_object_nam e = i r_wt->m v_lgar t .

  • 7/30/2019 ABAP OO for HCM

    45/65

    For SAP int er nal u seP a g e | 45

    ENDM ETHOD.

    me t h o d GET_WT.

    FIELD-SYM BOLS LIKE LINE OF m t_ w ts.DATA ls_wt LIKE LINE OF m t_w ts.

    READ TABLE m t_w ts ASSIGNING W ITH TABLE KEY lgar t = iv_ lgart.

    IF sy-sub rc = 0.r r_wt = < l s_wt>-o_wt .

    RAISE EVENT WT_accessed EXPORTING ir_w t = -o_w t.ELSE.

    "raise...

    ENDIF.endmethod .

    endclass. "ZCL_RT im plem entat ion

    2 1 .6 .2 .4 l o g h a n d l er c l a ss

    class-poo l .

    class ZCL_LOG_HANDLER def in i t ion

    publ icf ina l

    create pu bl ic .

    publ ic sect ion.

    me t h o d s HA ND LE_M ESSAGEfo r even t LOGPOINT_A DDED o f ZIF_LOGGABLE

    impor t i ng

    !I V_M ESSAGE_TEXT!IV_ M SG_TYPE

    !IV_EVENT_NAM E!IV_ OBJECT_NAM E .

    endclass. " ZCL_LOG_HAN DLER defin ition

    * "* local class imp lement at ion

    M ETHOD handle_message.

    W RITE iv_object_name.W RITE ' - ' .

    W RITE iv_msg_type.

    W RITE ' - ' .W RITE iv_event_name.

    WRITE ' - ' .W RITE iv_message_text.NEW-LINE.

    ENDM ETHOD.endclass. "ZCL_LOG_HANDLER implementation

  • 7/30/2019 ABAP OO for HCM

    46/65

    For SAP int er nal u seP a g e | 46

    21.6.3 Payr oll function source code

    This report source code represents the payrol l funct ion.The classes for t axes are defined local ly w i th in th e report ( to keep th e examp le simp le).

    *&---------------------------------------------------------------------*

    *& Report Z_TESTE2

    *&

    *&---------------------------------------------------------------------*

    *&

    *&

    *&---------------------------------------------------------------------*

    REPORT z_test.

    TYPE-POOLS: abap.

    *----------------------------------------------------------------------*

    * CLASS lcl_tax_wt DEFINITION

    *----------------------------------------------------------------------*

    *

    *----------------------------------------------------------------------*

    CLASS lcl_tax_wt DEFINITION INHERITING FROM zcl_wt.

    PUBLIC SECTION.

    METHODS add_to_tax FOR EVENT wt_inserted OF zcl_rt IMPORTING ir_wt.

    ENDCLASS. "lcl_tax_wt DEFINITION

    *----------------------------------------------------------------------*

    * CLASS lcl_state_tax_wt DEFINITION

    *----------------------------------------------------------------------*

    *

    *----------------------------------------------------------------------*

    CLASS lcl_state_tax_wt DEFINITION INHERITING FROM lcl_tax_wt.

    PUBLIC SECTION.

    METHODS add_to_tax REDEFINITION.

    PRIVATE SECTION.

    DATA mv_locked TYPE abap_bool.

    ENDCLASS. "lcl_state_tax_wt DEFINITION

    *----------------------------------------------------------------------*

    * CLASS lcl_tax_wt IMPLEMENTATION

    *----------------------------------------------------------------------*

    *

    *----------------------------------------------------------------------*

    CLASS lcl_tax_wt IMPLEMENTATION.

    METHOD add_to_tax.

    DATA lv_tax TYPE maxbt.

    IF ir_wt->mv_lgart(2) = '/1'.

  • 7/30/2019 ABAP OO for HCM

    47/65

    For SAP int er nal u seP a g e | 47

    lv_tax = ir_wt->get_amount( ) * '0.2'.

    me->add_amount( lv_tax ).

    ENDIF.

    ENDMETHOD. "add_to_tax

    ENDCLASS. "lcl_tax_wt IMPLEMENTATION

    *----------------------------------------------------------------------*

    * CLASS lcl_state_tax_wt IMPLEMENTATION

    *----------------------------------------------------------------------*

    *

    *----------------------------------------------------------------------*

    CLASS lcl_state_tax_wt IMPLEMENTATION.

    METHOD add_to_tax .

    IF mv_locked = abap_true.

    RAISE EVENT logpoint_added

    EXPORTING iv_message_text = 'wagetype is locked and canot be modified'

    iv_msg_type = 'I'

    iv_event_name = 'add to tax'

    iv_object_name = mv_lgart.

    RETURN.

    ENDIF.

    super->add_to_tax( ir_wt ).

    IF me->mv_amount > 100.

    me->mv_amount = 100.

    RAISE EVENT logpoint_addedEXPORTING iv_message_text = 'amount limited to 100 and locked'

    iv_msg_type = 'I'iv_event_name = 'add to tax'

    iv_object_name = mv_lgart.

    mv_locked = abap_true.

    ENDIF.

    ENDMETHOD. "add_to_tax

    ENDCLASS. "lcl_state_tax_wt IMPLEMENTATION

    DATA lr_rt TYPE REF TO zcl_rt.

    DATA lr_wt TYPE REF TO zcl_wt.

    DATA lr_log TYPE REF TO zcl_log_handler.DATA lr_tax_wt TYPE REF TO lcl_tax_wt.

    DATA lr_state_tax_wt TYPE REF TO lcl_state_tax_wt.

    START-OF-SELECTION.

    CREATE OBJECT lr_rt.

    CREATE OBJECT lr_log.

    SET HANDLER lr_log->handle_message FOR ALL INSTANCES.

    CREATE OBJECT lr_tax_wt

    EXPORTING

  • 7/30/2019 ABAP OO for HCM

    48/65

    For SAP int er nal u seP a g e | 48

    iv_lgart = '/600'

    iv_amount = 0.

    SET HANDLER lr_tax_wt->add_to_tax FOR lr_rt.

    CREATE OBJECT lr_state_tax_wt

    EXPORTING

    iv_lgart = '/650'

    iv_amount = 0.

    SET HANDLER lr_state_tax_wt->add_to_tax FOR lr_rt.

    "-----------------------------

    CREATE OBJECT lr_wt

    EXPORTING

    iv_lgart = '/101'

    iv_amount = 1000.

    lr_rt->insert_wt( lr_wt ).

    "-----------------------------

    CREATE OBJECT lr_wt

    EXPORTING

    iv_lgart = '/102'

    iv_amount = 2000.

    lr_rt->insert_wt( lr_wt ).

    "-----------------------------

    CREATE OBJECT lr_wt

    EXPORTING

    iv_lgart = '/103'

    iv_amount = 3000.

    lr_wt->add_amount( 1000 ).lr_rt->insert_wt( lr_wt ).

    "adding taxes to RT:

    lr_rt->insert_wt( lr_tax_wt ).

    lr_rt->insert_wt( lr_state_tax_wt ).

    22 Additi onal guidelines

    22.1 Coding style

    Program cod e must be readable and understandable by everyone w ho kno w s ABAP. If pro gramsor par t o f p rograms are not understandab le by read ing the source code i tse l f and i ts

    docum enta t ion , you m ust use comments. Com m ents should be in Engl ish and d escr ibe w hat aprogram, procedure , o r par t o f a program is do ing. If necessary, you shou ld a lso comm ent o n

    how the code produces i t resu l ts , e .g . , by inc lud ing c i ta t ions to l i te ra ture i f you imp lementgeneral a lgor i thm s.

  • 7/30/2019 ABAP OO for HCM

    49/65

    For SAP int er nal u seP a g e | 49

    In add i t ion to the naming rules prescr ibed by the syntax in Unicode-enabled classes (start aname with a letter fo l lowed by a sequence of letters, d ig i ts and underscores), we suggest no

    str ic t naming convent ions fo r in te rna l names. Never the less, we st rong ly recommend tha tnam es be meaningful to Engl ish-speaking readers and th at you use naming convent ions where

    approp r iate t o m ake coding clearer (see examp le in sect ion 22.3).

    Respect th e styl e of yo ur col leagues. If you mu st change or m ain ta in cod ing o f o ther deve lopers,

    you m ust respect t he given coding style.

    For external nam es ( reposito r y ob jects) a smal l set o f special nam ing convent ions is va lid t ha t

    shou ld not be used fo r o ther reposi to ry ob jects:

    o CL_ for glob al classes

    o IF_ for g lobal interfaces

    o CX_ fo r except ion classes

    o CL_OS_, IF_OS_, CX_OS _ f or in te rfac es and cla sses of Ob ject Ser vices

    o CL_BADI_, IF_BADI_, CX_BADI_ for int er faces and classes fo r BAdIs

    o and so on

    Use on ly th e re lat ional operator s (=, , , =) , w hich are more readable than th eir

    respective old-fashion ed character f orm s (EQ,NE, LT, GT, LE, GE).

    I f avai lable, use the addi t ionNOT inside predicates of locigal expressions10 (e.g., dobj IS

    NOT INITIAL) instead of the Boolean operatorNOT in front of the logical expression (e.g.

    NOT dobj IS INITIAL) . The reason is tha t you natura l ly do the same for compar isons(dobj1 dobj2 instead ofNOT dobj1 = dobj2) , don t you?

    Use on l y t he sho r t fo rmmeth( ) fo r a me thod ca ll . Use CALL METHOD meth fo r dynamic

    in vo ca tio n o nly. W it h t h e sh o rt f or m yo u avo id t h e p ollu t io n o f y ou r so u rce co de w it hsyntact ical noise. This is especial ly important in object-or iented programming, where method

    invocations are more frequently used than, for example, funct ion cal ls in proceduralprogramming. Fur thermore , you then use the same syntax fo r normal method ca l ls as fo r

    funct iona l m ethod cal ls in op erand p osit ions.

    Use the keyword LENGTH len in type and data declarat ions with TYPES an d DATAetc.

    instead of (len). The