+ All Categories

Abap

Date post: 06-May-2015
Category:
Upload: santhosh-kumar
View: 1,589 times
Download: 5 times
Share this document with a friend
30
Abap coding standards — Document Transcript 1. Coding Standard – ABAP 2. Coding Standard – ABAP 3. Coding Standard – ABAP TABLE OF CONTENTSEXECUTIVE SUMMARY .................................................................................... ................6DOCUMENT OBJECTIVE................................................................................... ...................................6DOCUMENT SCOPE....................................................................................... ....................................6TARGET AUDIENCE.................................................................................... ........................................6ACTION & ADHERENCE................................................................................... .................................6GENERAL COMMUNICATION .............................................................................. ...............................6THE DEVELOPMENT LIFE- CYCLE.................................................................................7PREPA RATION OF A FUNCTIONAL SPECIFICATION .............................................................................. .........7FUNCTIONAL SPECIFICATION SIGN- OFF......................................................................................... ..........7THE TECHNICAL SPECIFICATION .............................................................................. .............................7 DEVELOPMENT OF PROGRAM CODE........................................................................................ .......7UNIT TESTING & DOCUMENTATION .............................................................................. ........................8SYSTEM TESTING..................................................................................... ..........................................8USER ACCEPTANCE TESTING..................................................................................... ...........................8PROGRAM SIGN- OFF......................................................................................... ..............................8TYPES OF ABAP PROGRAM..................................................................................... ........8DATA CONVERSION PROGRAMS.................................................................................... .......................9BATCH INTERFACES.................................................................................. .........................................9INBOUND INTERFACES.................................................................................. ....................................9OUTBOUND INTERFACES.................................................................................. ...............................10ALE INTERFACES.................................................................................. .........................................10REPORTS.......................................... ............................................................................................ 10BASIC LIST........................................................................................ ..........................................11INTERACTIVE REPORT...................................................................................... ...............................12 ALV......................................................................................... ...........................................12TRANSACTIONS (DIALOGUE
Transcript
Page 1: Abap

Abap coding standards — Document Transcript

1. Coding Standard – ABAP

2. Coding Standard – ABAP

3. Coding Standard – ABAP TABLE OF CONTENTSEXECUTIVE

SUMMARY ....................................................................................................6DOCUMENT

OBJECTIVE......................................................................................................................6DOCUMENT

SCOPE...........................................................................................................................6TARGET

AUDIENCE............................................................................................................................6ACTION &

ADHERENCE....................................................................................................................6GENERAL

COMMUNICATION .............................................................................................................6THE DEVELOPMENT

LIFE-CYCLE.................................................................................7PREPARATION OF A FUNCTIONAL

SPECIFICATION .......................................................................................7FUNCTIONAL SPECIFICATION SIGN-

OFF...................................................................................................7THE TECHNICAL

SPECIFICATION ...........................................................................................................7 DEVELOPMENT OF

PROGRAM CODE...............................................................................................7UNIT TESTING &

DOCUMENTATION ......................................................................................................8SYSTEM

TESTING...............................................................................................................................8USER ACCEPTANCE

TESTING................................................................................................................8PROGRAM SIGN-

OFF.......................................................................................................................8TYPES OF ABAP

PROGRAM.............................................................................................8DATA CONVERSION

PROGRAMS...........................................................................................................9BATCH

INTERFACES...........................................................................................................................9INBOUND

INTERFACES......................................................................................................................9OUTBOUND

INTERFACES.................................................................................................................10ALE

INTERFACES...........................................................................................................................10REPORTS.............

.........................................................................................................................10BASIC

LIST..................................................................................................................................11INTERACTIVE

REPORT.....................................................................................................................12

ALV....................................................................................................................................12TRANSACTIONS

(DIALOGUE PROGRAMMING)..........................................................................................12USER

EXITS..................................................................................................................................13

BADI’S...............................................................................................................................13

SAPSCRIPTS............................................................................................................................13 SMART

FORMS........................................................................................................................13FUNCTIONAL

SPECIFICATIONS...................................................................................13WHAT IS A FUNCTIONAL

SPECIFICATION................................................................................................14WHY WRITE FUNCTIONAL

SPECIFICATIONS..............................................................................................14WHAT SHOULD BE IN A

FUNCTIONAL SPECIFICATION?................................................................................14THE TECHNICAL

SPECIFICATION...............................................................................14WHAT IS A TECHNICAL

SPECIFICATION?................................................................................................15CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 2 of 66

4. Coding Standard – ABAPWHY WRITE TECHNICAL

SPECIFICATIONS?.............................................................................................15WHAT SHOULD BE IN A

TECHNICAL SPECIFICATION?..................................................................................15ABAP CODING

STANDARDS...........................................................................................15GENERAL

PRINCIPLES......................................................................................................................16ERROR

HANDLING..........................................................................................................................18GENERAL.................

....................................................................................................................18CONVERSIONS & INTERFACES

ERROR HANDLING...............................................................................18DIALOG

PROGRAMMING..................................................................................................................19GENERAL.................

....................................................................................................................19NAMING.........................................

..............................................................................................19REPORT

Page 2: Abap

PROGRAMS........................................................................................................................19PROGRAM

STRUCTURE......................................................................................................................20READABILITY.............

....................................................................................................................20AUTHORIZATIONS &

SECURITY............................................................................................................21PERFORMANCE

CONSIDERATIONS........................................................................................................21DATABASE

SELECTIONS..................................................................................................................21ABAP

STATEMENTS.......................................................................................................................24COMPUTE AND

MOVE STATEMENT...................................................................................................24COMPARE

OPERATORS ..................................................................................................................24AVOID ‘HARD CODING’

...................................................................................................24CASE VS. IF/ELSE: WHICH TO USE WHEN

BOTH WOULD WORK?....................................................25BREAK LEVELS IN LOOP

STATEMENTS..............................................................................................26INTERNAL

TABLES............................................................................................................................27ABAP LIST

VIEWER.......................................................................................................................29ABAP

QUERIES...........................................................................................................................30SAPSCRIPT CODING

STANDARDS......................................................................................................30STANDARDS FOR ALL

ENHANCEMENT USER EXITS......................................................................................31CUSTOM BAPI

DEVELOPMENT..........................................................................................................32LOGICAL

DATABASES......................................................................................................................33 SELECTION SCREEN

PARAMETERS........................................................................................................33PROGRAM

DOCUMENTATION......................................................................................33PROGRAM FOLDER

OVERVIEW...........................................................................................................33SOURCE CODE

DOCUMENTATION.......................................................................................................34ON-LINE

HELP..............................................................................................................................35PROGRAM

ATTRIBUTES...................................................................................................................35PROGRAM

MODIFICATIONS..............................................................................................................35PROGRAM

TESTING.........................................................................................................................36TEST

CONDITIONS........................................................................................................................36 TEST

PLAN................................................................................................................................37TEST

DATA..................................................................................................................................37EXPECTED

RESULTS.......................................................................................................................37ACTUAL

RESULTS.........................................................................................................................37NAMING

CONVENTIONS..................................................................................................................37PROGRAM

DOCUMENTATION TEMPLATES................................................................................................37PROGRAM

HEADER........................................................................................................................38PROGRAM

CHANGE........................................................................................................................38INCLUDE PROGRAM

HEADER...........................................................................................................39CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 3 of 66

5. Coding Standard –

ABAPSUB-ROUTINE/FORM......................................................................................................................39FUNCTI

ON MODULE.......................................................................................................................40FUNCTION MODULE

– EXCEPTION HANDLING....................................................................................40APPLICATION OSS

NOTES..............................................................................................................41ABAP PROGRAM

TEMPLATES............................................................................................................44BASIC REPORT

LIST......................................................................................................................44INTERACTIVE ABAP REPORT

LIST..................................................................................................46BATCH INPUT

PROGRAM.................................................................................................................48PROGRAM PERFORMANCE

TUNING TECHNIQUES...............................................50TECHNIQUE 1: USING SELECT

STATEMENTS......................................................................................50TECHNIQUE 2: SELECTING ORDERED

RECORDS FROM A TABLE...............................................................50 TECHNIQUE 3: READING LARGE INTERNAL

TABLES WITHOUT USING BINARY SEARCH............................51TECHNIQUE 4: MOVING DATA FROM INTERNAL

TABLE 1 TO INTERNAL TABLE 2....................................51TECHNIQUE 5: APPENDING DATA FROM INTERNAL

TABLE 1 TO INTERNAL TABLE 2................................51TECHNIQUE 6: DELETING DATA FROM INTERNAL

TABLES....................................................................52ABAP CODE REVIEW

CHECKLIST..............................................................................53ABAP

OBJECTS..................................................................................................................53INTRODUCTION .................

............................................................................................................53NAMING

CONVENTIONS .................................................................................................................54GENERAL

Page 3: Abap

CONVENTIONS..................................................................................................................54CLASS

CONVENTIONS ....................................................................................................................55FIXED METHOD

NAMES ..................................................................................................................55METHOD

CONVENTIONS .................................................................................................................56WORK

FLOW......................................................................................................................58INTRODUCTION...................

...........................................................................................................58NAMING

CONVENTION...................................................................................................................581.1WORKFLOW

TEMPLATES / TASK.................................................................................................581.2BUSINESS

OBJECT....................................................................................................................591.3BUSINESS OBJECT –

PROGRAM...................................................................................................59PREFERRED APPROACHES /

PRACTICES:.................................................................................................60A. WORKFLOW IMPLEMENTING

APPROACH:........................................................................................60B. WORKFLOW SCENARIO

DEVELOPMENT:.........................................................................................60PERFORMANCE

TIPS:........................................................................................................................62ERROR

HANDLING:.........................................................................................................................62 CHECKLIST FOR

WORKFLOW DEVELOPMENT:..................................................................................63QA

SUMMARY ...................................................................................................................63OBJECTIVE.....................

..............................................................................................................63SCOPE..................................................

......................................................................................63TARGET

AUDIENCE..........................................................................................................................63ACTION &

ADHERENCE...................................................................................................................63CS_ABAPCDS –

Version 2.0Select the document classification as per the defined classification in the master list of documents’

for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 4 of 66

6. Coding Standard – ABAPQA PROCESS

OVERVIEW................................................................................................................64CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 5 of 66

7. Coding Standard – ABAPExecutive Summary Document ObjectiveThis document has been prepared to

outline the development approach followed by theWipro Technologies ABAP development group. Document

ScopeThis is a definition of the base standards relating to applications development work

andrecommendations for efficient programming techniques for all custom development workcarried out by

the Wipro Technologies ABAP development group. It describes progressionfrom functional specification,

through technical specification to code development, withassociated Quality Assurance and documentation.

Details of performance improvementmeasures and technical information are also included. Target

AudienceThe target audience for this document according to the purpose is as follows: Action & Adherence

Project Managers Technical Team leads Technical Team members General Communication All Core & Country

Team Leaders & Members (Process & Technical)CS_ABAPCDS – Version 2.0Select the document classification

as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 6 of 66

8. Coding Standard – ABAPThe Development Life-cycle During the life cycle a number of deliverables are

expected and checkpoints reached (seediagram below). The ABAP Development Life Cycle ABAP

Development Team Formal Functional Sign-off Specification Technical Specification Code and User Unit Test

Acceptance Program Testing System Test Preparation of a Functional SpecificationThe Project Implementation

team members, located on-site, are responsible for preparingFunctional Specifications. These will describe

the development requirement and contain adescription of the functionality of the proposed custom ABAP

program. During production ofthese specifications it may be necessary for the business teams to gain input in

the form ofFunctional Specification assistance from ABAP team members. Functional Specification Sign-

offEach functional specification, once complete, will be subject to review and approval by theABAP team

leader. In addition, the ABAP team leader assesses the complexity and cost ofthe proposed development -

any changes to the original assessment are subject to writtenapproval of both parties. The Technical

SpecificationThe functional requirements will be translated to a technical specification. This will subject

tointernal ABAP team quality assurance. Once complete, it will be signed off internally by theABAP

development team leader. Any changes between the technical and functionalspecification will be made in

writing and subject to the written approval of both parties. Development of Program CodeProgram coding

then occurs from the technical specification.CS_ABAPCDS – Version 2.0Select the document classification as

per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 7 of 66

Page 4: Abap

9. Coding Standard – ABAP Unit Testing & DocumentationOnce complete, the program will be tested by the

programmer, who will also produce thefollowing testing documentation:• Unit Test Conditions• Unit Test

Plan• Test Data• Actual Results System TestingAt regular intervals (e.g. 2 months) a number of developments

are subject to system testing.This will be to verify inter-dependencies between reports. User Acceptance

TestingThe ABAP reports will be tested and accepted by reference to whether they conform in allmaterial

respects to the Functional Specifications (as signed off by both parties) and inaccordance with the following

procedure: • Functional Designer prepares Test Plan. • Client Project Manager nominates suitable User for

acceptance testing • User conducts testing as detailed in plan. • Client Project Manager reviews UAT test plan

and results to verify validity of results and completeness of testing. Program Sign-OffFollowing a successful

User Acceptance Test, the program will then be signed-off by bothparties.After development technical

specifications are updated to reflect any programmodifications requested during the life cycle. Approval to

implement any modifications notcovered in the original functional specification will be obtained in writing & a

copycontained within the program folder.Types of ABAP ProgramThere are a number of different types of

ABAP program, as listed below. The type ofprogram to be developed affects which details are required in the

functional specification.It is important that the different types of program are understood before detailing

therelevant requirements.• Data Conversion• Batch Interface• ALE Interface• Report• Transaction• User

Exit• SAPScript (output)• Smart Forms• BADI’sCS_ABAPCDS – Version 2.0Select the document classification

as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 8 of 66

10. Coding Standard – ABAP Data Conversion ProgramsData conversion programs can be written to upload

data from external legacy systems intoSAP. There are a number of standard SAP programs specifically

designed to meet thisrequirement. These use one of two methods to upload the data:• Direct Input• Batch

InputDirect input programs tend to be around ten times faster than batch input programs.However custom

ABAP developments are only supported if they use the batch inputmethod. Batch input programs read a file

from either the presentation or application serverand upload it into SAP by simulating the actions of a user

stepping through the screens of therelevant transaction. This means that the SAP transaction validates that

the data being inputis valid so the custom ABAP program does not have to do this.The Batch input program

creates a ‘session’, which can be thought of as a collection ofinformation relating the transaction fields to the

data to be uploaded. The database is notupdated until the ‘session’ is processed. This can be done either

manually or automatically.If the session should be processed automatically this should be specified. Any

invalid recordsencountered by SAP are not uploaded into the database and they result in the session being‘in

error’. All valid records will be loaded, the remaining erroneous records will be retainedand this session can

be re-processed manually. This allows a user to correct the records on-line. Batch InterfacesInterfaces are

used to transfer data between SAP and an external system. There are twotypes of interface:• Inbound -

transfers data from the external system to SAP• Outbound - transfers data from SAP to the external

systemThe transfer of data is usually facilitated by either reading from or writing to a file on theapplication

server that has been created or is subsequently read by the external application. Inbound InterfacesFor an

inbound interface (data being put into SAP), the program first reads the data from thesource file, performs

any conversions, calculations and formatting that is required for the SAPtransaction. The program can then

write the data out either as a set of table entries or to aflat file if the data needs to be stored for audit reasons

although if this approach is adoptedarchiving strategies must also be considered. Obviously a flat file carries

fewer overheads interms of maintenance, but there are also benefits of interface controls and audit

throughintermediate tables that in some instances outweighs this. The program then uses theconverted data

and creates a SAP batch input session to load it into SAP via the relevanttransactions (If writing to a table this

may be a second program).CS_ABAPCDS – Version 2.0Select the document classification as per the defined

classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 9 of 66

11. Coding Standard – ABAP First Stage Extract Calculate Convert Format Second Stage Map Load Outbound

InterfacesAn outbound interface will typically consist of only one program. This will retrieve the relevantdata

from SAP tables and write it to an output file. Conversion and formatting will be carriedout by the destination

interface. Again, some use of tables may be adopted to provide arecord of interface operation. ALE

InterfacesApplication Link Enabling (ALE) interface will also comprise inbound and outbound types

ofinterfaces. ALE is a standard SAP Application component that provides standard settings orthe ability to

customize elements to take advantage of the ALE application layer.ALE interfaces fall into the following

categories:• Standard Scenarios – where SAP provides standard components i.e. Message Types, IDOCs,

Function Modules that can be set-up immediately to enable data transfer• Modified Scenarios – where the

standard SAP components are enhanced to either reduce data or extend the data being sent i.e. reduce or

extend IDOCs, additional function module changes• Customized Scenarios – new components are added to

Page 5: Abap

address interface requirements that cannot be met by modified or standard scenarios i.e. new message

types, new IDOCsALE interfaces require a slightly different development approach as the ALE interface

requirea combination of:• Client Independent Customization e.g. Message Types• Client Dependent

Customization e.g. Output Types• Repository changes e.g. Function Modules ReportsSAP Reports provide a

user with a list of data; this can be either displayed on the screen orprinted. Using the following SAP supplied

tools can also produce these Reports:• Report Writer• Report Painter• ABAP Query.• ALVCS_ABAPCDS –

Version 2.0Select the document classification as per the defined classification in the master list of documents’

for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 10 of 66

12. Coding Standard – ABAPThese are useful tools suitable for relatively simple reports and can be used as

end-user tools.It should be remembered that since these tools are effectively code-generators the

codedeveloped might lack clarity and be relatively inefficient.Reports produced using ABAP code can be one

of two types:• Basic List• Interactive Report Basic ListThis is a report that produces a basic list of data. The

user can enter selection criteria on theselection screen to restrict what data is available on the output report.

In addition, a numberof calculations may be performed by the report together with some data grouping

andsorting but this is controlled by the program code. Basic List Report Simple list of Data, double-clicking

has no effectCS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in

the master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 11 of 66

13. Coding Standard – ABAP Interactive ReportAn interactive report allows the user more flexibility in what

data they wish to retrieve but aremore complex to code and test. The user is given the option to double-click

or select linesand see more information. What further information is displayed should be detailed in

theFunctional Specification. For instance, a report on Purchases could list a number of purchaseorders. By

double clicking on the Purchase order number the user can be taken to the‘Display Purchase Order’

transaction to browse the purchase order. This will allow them toview more information than in the report.

Interactive Report User Double-clicks on PO Number, the Purchase Order Overview is displayed. ALV ABAP List

Viewer (ALV) is one of the fascinating tools provided by SAP for displaying reports.This tool has the merit of

reducing the development time of reports by providing standardinterfaces (Function Modules). These

standard interfaces provide GUI and formatting optionsfor the on screen display. Transactions (Dialogue

Programming)A transaction is a dialogue program with one or more screens. It changes objects in

thedatabase in a consistent manner. Examples of standard SAP transactions include ‘Change aPurchase

Order, Create a Material, Enter a G/L Posting’. Custom transactions can bedeveloped to meet functionality not

covered by the standard SAP system.CS_ABAPCDS – Version 2.0Select the document classification as per the

defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 12 of 66

14. Coding Standard – ABAP User ExitsChanges to SAP supplied code are called a repair to the system and are

not supported bySAP. There are however number of places in the standard SAP code where

additionalfunctionality can be implemented called ‘User Exits’. These exist in pre-defined places in

thestandard SAP code. Specific data is passed into and out of these exits allowing some datamanipulation

flexibility. These areas of SAP code are reserved for customer enhancementsand are protected from changes

during upgrades. BADI’sBusiness Add-Ins are a new SAP enhancement technique based on ABAP Objects.

They canbe inserted into the SAP System to accommodate user requirements too specific to beincluded in the

standard delivery. Since specific industries often require special functions, SAPallows you to predefine these

points in your software. SapScriptsSAP supplies a number of outputs as standard, e.g. Purchase Order,

Invoice, etc. In manycases these meet client business requirements but additional changes are often

requested.This can vary from adding company logos to retrieving additional data and changing thelayout. The

outputs are produced using the SAP tool SAPScript. Smart FormsThe Smart Forms replace the SAPScript

forms.SAP Smart Forms allows you to execute simple modifications to the form and in the form logicby using

simple graphical tools; in 90% of all cases, this wont include any programming effort.Thus, a user who is

familiar with the tool but has only rudimentary programming knowledgecan configure forms with data from

an SAP System for the relevant business processes. Theresult of the form development is a Smart Form. After

it is activated, the Smart Form is similarto a callable function module in the SAP System.The logic of the form

is mapped entirely in the Smart Form. To print a form, you call it fromwithin an application program, in which

you retrieve the application data to be merged intothe form. As data retrieval and form logic are separated,

you must only adapt the SmartForm if changes to the form logic are necessary. The application program

passes the datavia a function module interface to the Smart Form.Functional SpecificationsFunctional

specifications should be prepared and owned by the Project Implementationteam (business process team).

Essentially they document why the development is required,CS_ABAPCDS – Version 2.0Select the document

Page 6: Abap

classification as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 13 of 66

15. Coding Standard – ABAPhow the ABAP development will meet the requirement, what user acceptance

testingcriteria will be used to verify that the final development meets the business requirements. What is a

Functional SpecificationA functional specification should clearly define the functionality of the proposed

ABAPprogram. The document should use clear language and not contain ambiguous statementsthat could

lead to confusion. The document is a design deliverable and is used internallywithin the ABAP team as a basis

to write a technical specification. The technicalspecification should contain no functionality not detailed in the

functional specification.Once complete, the functional specification is used as a baseline to estimate the

complexityof the proposed ABAP program and the associated development time for planningpurposes.This

document forms the link between the functional and ABAP teams but it is important toremember that this

document is owned by the functional designer/Business Process Team.The success of the development,

however, depends on close co-operation with the ABAPteam. Why write Functional SpecificationsFunctional

specifications are written to ensure that all parties (ABAP team/Functional Team)know what is required in the

development. This document allows requirements to bereviewed across regional teams before the

development is complete. It is also part of theprocess to enable relevant clients to meet validation

requirements. In addition, functionalspecifications enable dependencies and inter-relationships between the

developments andfunctional areas to be identified and enable evaluation of the risk of development. What

should be in a Functional Specification?• A description of the business process. A series of bullet points

summarizing the process flow for this requirement.• Assumptions made for this process if any.• Key process

steps and descriptions.• What type of program is required?(Example Conversion/SAP Script etc)• Tables from

where the data can be fetched• A description of the Selection Screen if applicable.• Validations required at

various steps if applicable.The Technical SpecificationThe ABAP team writes technical specifications internally.

These document the businessrequirements covered by the functional specification in a more technical detail

that can betranslated by a programmer into code. The technical specification also aims to documentthe

implemented solution so it can be used for future code maintenance.CS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 14 of 66

16. Coding Standard – ABAP What is a Technical Specification?A Technical specification should clearly define

the functionality of the proposed ABAPprogram in much more detail than the Functional Specification. This

document should useclear language and is devoid of ambiguity. The document is a design deliverable and

isused internally within the ABAP team as a basis to write ABAP code. The technicalspecification should

contain no functionality not detailed in the functional specification.Once complete, the technical specification

is used to generate the code easily andseamlessly.This document forms the link between the functional

specification and ABAP code itself. It isowned by the ABAP developer and is QA’ed by the ABAP team leader

before codingcommences. The technical specifications use logic charts to illustrate the main logical stepsin

the code and how data and other ABAP specific constructs need to be manipulated toproduce the required

functionality. Why Write Technical Specifications?Technical specifications are written to illustrate and help

design the main logical stepsinvolved in meeting the requirements as specified in the functional

specifications. Thisdocument allows the developer to visualize and create methods and techniques to

manageprocessing efficiently. What should be in a Technical Specification?A technical specification needs to

contain:• A description of the Technical Solution highlighting the key design issues. A series of bullet points

summarizes the logic chosen for the program and the main technical difficulties.• What assumptions are

made in the technical specification and what they entail in technical terms.• Key process steps.• Why a

particular function module was chosen.• Why use multiple selects than just one.• Why use a particular kind of

logic for the main processing.• What were the major technical problems with the design of the program?• A

description of the Selection Screen with a Selection Screen Prototype• All the error messages (ID and Classes)

prompted by the validations executed at the selection screen will be detailed.• Detail Logic Diagrams along

with notes associated to them. They should include critical decision logic, database selects, complex

conversions, calculations, and formatting and output.• Main Processing steps descriptions• Final Processing

steps descriptionsABAP Coding StandardsThe standards in this document define a base for applications

development and qualitycontrol. They have been defined as a result of past experience on a number of

projects.Standards are used to ensure that the same set of rules are applied in program design,CS_ABAPCDS

– Version 2.0Select the document classification as per the defined classification in the master list of

documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 15

of 66

17. Coding Standard – ABAPdevelopment and reviews and they are applicable to all programs developed in

support ofthe conversion, implementation and maintenance of the SAP R/3 System. General PrinciplesWhen

Page 7: Abap

coding a program, the following points should be observed to ensure thatprogramming is consistent in format

across the project. This ensures that work can be easilytransferable between programmers• The standard

SAP project program template should be used for all programs.• ABAP programs that update master and

transactional data MUST ALWAYS use SAP transaction codes (where transaction codes are available) by

utilizing standard SAP Function Modules, BDC or ‘call transaction’ utilities. This ensures that logical units of

work, rollback, locking operations and edits are performed. SAP tables MUST NEVER be updated directly.•

ABAP programs MUST NEVER be used to update configuration tables.• Before starting any development work,

make sure that no existing functionality satisfies the same requirements.• If possible, write code that it is re-

usable and can be stored in a central library. Function modules are an example of this approach. R/3 provides

a large amount of function modules that perform various tasks such as convert currencies, calculate dates,

explode BOM’s etc. In most cases, these modules are efficient and can reduce coding time; therefore they

should be employed where possible. It is worth taking the time to search the function module library for a

function that meets your requirements. Common examples include: ‘CONVERT_TO_LOCAL_CURRENCY’ for any

exchange rate based conversion ‘UNIT_CONVERSION_SIMPLE’, ‘UNIT_SUM’ when dealing with Units of

Measure RV_DOCUMENT_PRINT_VIEW (Sales Order) to get data from SD documents

RV_DELIVERY_PRINT_VIEW (Delivery) RV_BILLING_PRINT_VIEW (Billing)• Keep program lengths to a minimum.

Each program should handle a discrete problem.• If there are a large number of data declarations necessary

as part of a program, consider separating your declarations into an INCLUDE. The include name should be the

same as the program name with the suffix ‘_DATA’• Use subroutines (FORMS) whenever possible to improve

readability and logic flow. Consider creating a subroutine whenever a block of code is called from multiple

places in a program.• Avoid the COMPUTE function if clearer ADDs, SUBTRACTs, MULTIPLYs, or DIVIDEs can

be used.• When assigning internal fields that are to hold values from databases, use the LIKE option to ensure

that the variable has identical characteristics. Example: DATA: WS_LIFNR LIKE LFA1-LIFNR.• Use the INCLUDE

statement for Data Declarations, PBO Dynpro modules, PAI Dynpro modules, Subroutines, and Individual

Event Processing.CS_ABAPCDS – Version 2.0Select the document classification as per the defined

classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 16 of 66

18. Coding Standard – ABAP• Use an underscore (_) to connect multi-word variable names and/or MODULE

names.• Use the WRITE command with Currency or Units option when writing prices/values to ensure the

data is output with the correct number of decimal places. For example weights should always be output with

the UNITS options and prices should always be output with the CURRENCY option. This ensures the program

can be used over multiple units of measure and in multiple countries.• All programs should be made as

generic as possible and reliance on factors specific to clients business should be avoided since the business

processes can change easily.• Programs that set their own GUI status should have menus and screens that

are as intuitive as possible.• Push buttons should reflect the menu options. All push button options should be

available by menu as well. Push button Print Sort Refresh Display/Change• Explicitly qualify all field

specifications. For example, use KA-KTRNA, not KTRNA only.• When using the FILL statement, specify FILL

FROM. For example, use FILL workarea FROM KA, instead of just FILL workarea.• When a local variable is

declared, it should be initialized in the declaration statement whenever possible.• Numbered text-elements

must be used wherever possible to make use of SAP’s multi- language capabilities, to make maintenance

easier and reduce the impact of future changes on re-work. Text elements should be created with the actual

text string in the text element itself e.g. text-001 should read ‘Testing String’ (001) so that text elements for

an ABAP program can be recreated if the program is moved to a different client.• Within the main program

code literals (i.e. hard-coded values) should be avoided. If reference needs to be made to a specific value (for

example Company Code ‘0001’ or Sales Organisation ‘ABCD’) then this should be defined as a parameter to

make the program fully flexible. SD/MM/FI document types in particular should not be hard coded since they

are subject to change.• No undocumented features of the ABAP language should be used.• External

PERFORMs should NOT be used.• Comments should be simple but clear - adequate for a different

programmer to understand the processing quickly. Comments can occupy a whole line in the code when it is

prefixed with an “*” character, or part of a line when prefixed with an open quote character (“).• Declare

program-specific internal variables to be LIKE data dictionary fields to ensure that physical data attributes are

consistent.• Each program elements should adopt the appropriate naming prefix.CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 17 of 66

19. Coding Standard – ABAP Internal Tables Transfer record/Work REC_* Area Internal tables: IT_* Copy of

database X_* or Y_* or Z_* table Structures Not data dictionary STRUCT_* Types General TY_* Constants

General C_* Parameters General P_* Ranges General R_* Checkbox General CB_* Select Options General S_*

Variable Local LV_* Global GV_* Counters CNT_* Flags FLG_* Sums SUM_* Work Areas General WA_* Error

Page 8: Abap

Handling General• All programs must include proper error handling to avoid undesirable terminations. This

means that the system status (SY-SUBRC) must be checked where appropriate after every event in the

program that changes it.• If there are more than two possible values for the SY-SUBRC field after a performed

event, all expected values should be tested and handled in the program.• Use the CATCH/ENDCATCH

statement to trap runtime errors.Error checking requirements depend on the type of program under

development. Wherepossible standard SAP errors messages are utilized in developments. Custom error

messagesare created where relevant SAP error messages cannot be found. It is the responsibility ofthe

functional requestor to define detailed error handling. Error messages used should aimto be as meaningful as

possible.Conversions & Interfaces Error HandlingEach of the conversion and interface programs should

generate an exception/error reportcontaining detailed record information, corresponding error message(s)

and report statistics.In addition to the error report, inbound interface and conversion programs should

generateBDC sessions for those transactions, which could not be posted to SAP successfully.

TheseCS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 18 of 66

20. Coding Standard – ABAPsessions can then be accessed by an authorized user and be processed manually

in theforeground (via transaction SM35) until those error records are posted successfully. It will bethe

interface user’s responsibility to check the report to ensure that no errors have occurred.A sequential file

containing the error records can also be generated if an error occurs. Theprogram can be rerun using this file

after fixing the errors. This file can also be used forcreating formatted reporting as well as for audit

purposes.Dialog Programming General• If the layout of screens is the same for multiple functions (such as

ADD, MOVE, and DELETE), use the same screen for all functions. Use online status and security features to

control which function is executed.• Define all global data in the main program module instead of the

PBO/PAI.• To handle a lock entry failure, raise an error message (type E) preventing any further progress but

leaving the user on the current screen. The user can take an alternative action or continue to try to lock the

object. To minimize the impact on users, limit retries.• When activating buttons or boxes, activate the

associated text as well. This enables the user to click on the either button/box or the text.• For additional

standards, see the SAP online documentation, “SAP Styleguide”. Naming• For online programs, the initial

screen should always be 9000. Screen numbering should follow functionality. For example: 9000 - Initial 9100

– Block 1 9110 - Sub-functionality of Block 1 9120 - Sub-functionality of Block 1 Etc....• Use Data Dictionary

names (short, medium, long) for field text on screens where applicable.• Use SAVE_OK_CODE as the field

name when saving the OK Code field. It is recommended that you use a backup version of the OK Code field

to avoid sending a screen that already has a function code.• Always define the field with a Format = OK as

OK_CODE. This field is used to validate the OK Event.• Prefix radio buttons with RB_, push buttons with PB_,

and check boxes with CB_. Report ProgramsCS_ABAPCDS – Version 2.0Select the document classification as

per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 19 of 66

21. Coding Standard – ABAP• The only report screen is 1000, which is automatically assigned by SAP.• When

using the WRITE command, constants should be defined as Text Elements. Hardcoded character strings

should NOT be used alone. Text elements should be defined and used in the WRITE command in addition to a

corresponding string value. This technique ensures accuracy of output by using text elements, while

improving readability of the program.• For list reports, include the following information to give users a clear

indication as to what the report consists of. For example: - End-User Reports: selection criteria, entries found,

requester, report name, date/time, exceptions, parameters, etc. - Conversion/Interface Reports: number of

records read, number of records processed, number of records written, date/time, transactions posted, etc.

Program StructureABAP is an event driven programming language. However, proper program structure

andmodular coding is still important to maintain readability and efficiency of an ABAP program.A program

should be divided into distinct sections that are properly documented in thecode. Whenever possible, it is

sensible to use function modules already available instead ofcreating new ones. Refer to the program

template in the Appendices section for the properorder and structure of your program.Forms should not be

too long to help ensure modularity and for ease of following theprogram logic.All forms should be in the order

they are first called. Using the letter F and a number code toidentify related forms can help facilitate this.E.g.

perform f1000_intialisation. perform f2000_main_processing. form f2000_main_processing. perform

f2100_modify_data. perform f2200_calculation. endform.Note: If a form contains very general functionality

that could be used in other programs, itmay be useful to create it as a function module. Readability• Start

each new command or clause on a new line. Do not put multiple commands on the same line.• If a statement

continues past one line, indent all subsequent lines.• Skipped lines and indention should be used to promote

clarity between sections of code as well as between file definitions and declarations.• Use the Pretty Printer

Page 9: Abap

automatic formatting function for your programs to ensure uniform indentation of program codeCS_ABAPCDS

– Version 2.0Select the document classification as per the defined classification in the master list of

documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 20

of 66

22. Coding Standard – ABAP• Project Standard Form headings. Add appropriate form description to these

headings. Note: “Pretty Printer” creates SAP Form headings if no comment lines exist after previous ABAP

statement. Authorizations & SecurityAs a rule, authorization checks should be used whenever appropriate to

verify the accesslevel of the user executing the program. Please see the Portal Integration team documenton

security & authorizations for ABAP development. Performance Considerations Database SelectionsThe 3-tier

architecture of SAP distributes workload across the servers (presentation,application, and database). The

majority of the work takes place on the application anddatabase servers. There is an obvious limit on

capacity; this means that if not managedcorrectly the database server can become a major bottleneck.

Applications developersshould aim, for performance reasons, to migrate the majority of processes to the

applicationservers and to be as efficient as possible when accessing the database server.This can be achieved

in a number of ways. In order to improve performance times whereverpossible the number of database

accesses made by a program should be kept to aminimum. The contents of tables can be selected into

internal tables (tables local to theprogram) and used for reference during the program execution rather than

using theSELECT...ENDSELECT logic (see diagram below). Application Server Select VBELN Select VBELN

POSNN POSNN From VBFA into table I_VBFA Where VBELV = S_DOC_NUMBER From VBFA And POSNV =

S_ITEM_NO Where VBELV = S_DOC_NUMBER And POSNV = S_ITEM_NO Move: VBFA-VBELN to I_VBFA-VBELN,

VBFA-POSNN to I_VBFA-POSNN. Append I_VBFA. Endselect. Multiple Single Database Database Accesses

Accesses VBFA Database VBFAThe typical procedure would be to select relevant fields from the table into an

internal tableat the event START-OF-SELECTION. In this example only those records of the sales

documentflow table (VBFA), which fall within the selection criteria are selected into an internal

table.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 21 of 66

23. Coding Standard – ABAPInternal tables are generally quicker than using field-groups for small volumes of

data(although they are less flexible for sorting, especially for a large volume of data records).Field groups

should be used if there is a high number of data records that would need to beprocessed (e.g. 100+ records).

Field groups use memory space on the application serverthat does not impede processing space for other

applications. Field groups are also moreefficient in their storage handling because the data is compressed

before being stored.In addition, a number of additional principles should be adhered to for efficient coding:•

Where possible fields should be specified rather than SELECT *.• When accessing pool and cluster tables,

these should be accessed using the full primary key.• Avoid placing a ‘SELECT’ or ‘SELECT SINGLE’ in a loop

to minimize the number of database requests.• Avoid using ‘SELECT...INTO CORRESPONDING FIELD’, as the

associated overhead with corresponding field could be significant.• The number of records retrieved should

be limited using the ‘WHERE’ clause rather than selecting and using the ‘CHECK’ statement.• Fields should be

listed in the WHERE clause in the same order as they appear in the table.• Where possible the ‘AGGREGATE’

function should be used rather than ‘SELECT…’ and then do the manipulation.• When defining internal tables

the use of include-structures should be avoided.• Minimize database accesses. Keep the number of

communication processes between the database and application servers, as well as the transferred dataset

as small as possible.• Do the most restrictive calls first. For example, to process all materials with a quantity-

at- hand above 50, the tables containing stock quantities should be read before the material master tables.•

Always check for the DELETION FLAG on key master data tables (i.e., KNA1, KNVV, MARA…). Deletion flags

are usually named LOEVM, LOEKZ, LVORM, etc.• Do not use Order By clause on non-key or non-indexed

fields. Bring the data into an internal table with a single call and then sort the internal table. This relieves the

database of the additional sort requirement and utilizes the processing and memory of the application

server.• In all cases look to decrease the number of database calls. Whenever possible issue calls to retrieve

all records into an internal table. Do the processing using the internal table.CS_ABAPCDS – Version 2.0Select

the document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 22 of 66

24. Coding Standard – ABAP • Nested selects should be avoided as they result in a large volume of database

accesses (dependent on size of tables). Where further database accesses depend on data stored in an

internal table the following syntax can be used: IF NOT ITAB1 [] IS INITIAL Select FIELD1 FIELD2 From TABLE

Into table ITAB2 For all Entries inITAB1 Where FIELD3 = ITAB1-FIELD3 And FIELD4 = S_FIELD. ENDIF. • In a

SELECT statement, the HAVING clause allows you to specify a logical condition for the groups in a GROUP-BY

clause. Effective use of the having clause can reduce the set of data transferred from the database to the

Page 10: Abap

application server. When the having clause is used, the aggregates and groups are constructed in the

database instead of the application server, thereby reducing the resulting set. • When creating a program

that writes new or update existing records you MUST secure that your program handles COMMIT at a

reasonable frequency. As a general rule, you should do a commit every 1000 or 10 000 records. If your

program is running for a long period of time without doing a commit, the data base and finally the whole

system will be deadlocked and eventually shutting down the system is the only option left to terminate the

execution as all resources are consumed by your program. If multiple inserts must be made to a table,

inserting an array from a table, rather than performing multiple inserts of single records will improve

performance. For example: INSERT CUST FROM TABLE TAB. Will be more efficient than: LOOP AT TAB. MOVE-

CORRESPONDING TAB TO CUST. INSERT CUST. ENDLOOP.• Open SQL is SAP’s version of SQL and is designed

to work with most RDBMS Systems (Relational Database Management Systems). Avoid using any native SQL

features that are not documented or used in Open SQL.• You can specify as many WHERE conditions as you

like in all types of database tables – i.e. transparent tables, pool tables and cluster tables. However, you

should be aware for performance reasons that complex WHERE conditions involving pool and cluster tables

usually cannot be passed to the database system. They must be processed by the SAP database interface

through post-selection.• Use secondary index / Create secondary index if accessing a database table with

non-key fields depending on the frequency of usage and volume of data accessed. CS_ABAPCDS – Version 2.0

Select the document classification as per the defined classification in the master list of documents’ for your

project <VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 23 of 66

25. Coding Standard – ABAP• Use of total key is preferred in search criteria. If you can not give total key and

you can give former part of key, still the select is effective. If you are specifying later part of key then it is

equivalent to non-key field which is not effective.• When a full key is unknown and only one record is needed,

the UP TO 1 ROWS append is added to the SELECT statement.• When using the AND OR operator the most

likely elimination criteria is specified first. (Expressions are evaluated left to right and the evaluation ends

when the final result has been established) ABAP Statements Compute and Move Statement Use operators

(+, -, *, /) in the form of “pctocc = seatsocc / seatsmax” instead of the COBOL form of “Divide seatsocc by

seatsmax giving pctocc”. Use the = sign in the form of “J_4KRCAT_I = VBAP_I-J_4KRCAT” instead of the

COBOL MOVE statement “MOVE VBAP_I-J_4KRCAT TO J_4KRCAT_I”. Compare Operators Use compare

operators (=, <, >, <>) instead of EQ, NE, LT, GT Avoid ‘Hard Coding’ RULE OF THUMB: Use constants rather

than ‘hard coding’ when: • It adds value to the code and is named informatively. • It is defined in the

standard include. Incorrect: CONSTANTS: C_SA LIKE BKPF-BLART VALUE SA, C_DR LIKE BKPF-BLART VALUE DR,

C_DG LIKE BKPF-BLART VALUE DG, C_KR LIKE BKPF-BLART VALUE KR, C_KG LIKE BKPF-BLART VALUE KG, C_AC

LIKE BKPF-BLART VALUE AC, C_O LIKE T001B-RRCTY VALUE 0. IF rs_header-document_type = C_SA OR

rs_header-document_type = C_DR OR rs_header-document_type = C_DG OR rs_header-document_type =

C_KR OR rs_header-document_type = C_KG OR rs_header-document_type = C_AC OR rs_header-

document_type = C_O. ... Correct: CONSTANTS: C_GL_ACCOUNT_DOC LIKE BKPF-BLART VALUE SA,

C_CUSTOMER_INVOICE LIKE BKPF-BLART VALUE DR, C_CUSTOMER_CREDIT_MEMO LIKE BKPF-BLART VALUE

DG, C_VENDOR_INVOICE LIKE BKPF-BLART VALUE KR, CS_ABAPCDS – Version 2.0 Select the document

classification as per the defined classification in the master list of documents’ for your project <VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 24 of 66

26. Coding Standard – ABAP C_VENDOR_CREDIT_MEMO LIKE BKPF-BLART VALUE KG, C_ACCRUALS LIKE BKPF-

BLART VALUE AC. IF RS_HEADER-DOCUMENT_TYPE = C_GL_ACCOUNT_DOC OR RS_HEADER_DOCUMENT_TYPE

= C_CUSTOMER_INVOICE OR RS_HEADER_DOCUMENT_TYPE = C_CUSTOMER_CREDIT_MEMO OR

RS_HEADER_DOCUMENT_TYPE = C_VENDOR_INVOICE OR RS_HEADER_DOCUMENT_TYPE =

C_VENDOR_CREDIT_MEMO OR RS_HEADER_DOCUMENT_TYPE = C_ACCRUALS....OR this is also correct:IF

RS_HEADER-DOCUMENT_TYPE = ‘SA’ OR “GL_ACCOUNT_DOC RS_HEADER_DOCUMENT_TYPE = ‘DR’ OR

“CUSTOMER_INVOICE RS_HEADER_DOCUMENT_TYPE = ‘DG’ OR “CUSTOMER_CREDIT_MEMO

RS_HEADER_DOCUMENT_TYPE = ‘KR’ OR “VENDOR_INVOICE RS_HEADER_DOCUMENT_TYPE = ‘KG’ OR

“VENDOR_CREDIT_MEMO RS_HEADER_DOCUMENT_TYPE = ‘AC’. “ACCRUALSCASE VS. IF/ELSE: Which to use

when both would work?IF/ELSE RULE OF THUMBUse the IF/ELSE rather than the CASE statement when there is

only one condition.Example:IF T_DETAIL-BSCHL = C_POSTING_KEY_70. <action 1>.ELSE. <action

2>.ENDIF.CASE RULE OF THUMBUse the CASE statement rather than IF/ELSEIF statement when there are

multiple conditions.Example:CASE T_DETAIL-BSCHL. WHEN C_POSTING_KEY_70. <action 1>. WHEN

C_POSTING_KEY_75. <action 2>. WHEN OTHERS.CS_ABAPCDS – Version 2.0Select the document classification

as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 25 of 66

27. Coding Standard – ABAP <action 3>.ENDCASE.Note: ‘WHEN OTHERS’ always requires generic error

processing.Incorrect:CASE sy-subrc. WHEN 1. MESSAGE ID ‘ZSD’ TYPE ‘E’ NUMBER ‘100’. WHEN 2. MESSAGE

Page 11: Abap

ID ‘ZSD’ TYPE ‘E’ NUMBER ‘101’. WHEN OTHERS.* No action requiredENDCASE.Correct:CASE sy-subrc. WHEN

1. MESSAGE ID ‘ZSD’ TYPE ‘E’ NUMBER ‘100’. WHEN 2. MESSAGE ID ‘ZSD’ TYPE ‘E’ NUMBER ‘101’. WHEN

OTHERS. MESSAGE ID ‘ZSD’ TYPE ‘E’ NUMBER ‘102’.ENDCASE.If you are using CHECK or EXIT statements, be

careful while considering any required follow-on processing, e.g. a failed CHECK statement in the START-OF-

SELECTION event of a programcauses the program to move directly to END-OF-SELECTION processing.Break

Levels in Loop StatementsInside Loops the preferred way of recognizing changes is AT....ENDAT. Avoid using

OnChange Of statement. Theres a difference between these statements.AT ..... ENDATThis statement is

triggered based on any change in the field specified and any change in aprevious field inside the structure.

Note: All character fields on the right are filled with * afterthe current control level key. See SAP Help for more

information.ON CHANGE OFCS_ABAPCDS – Version 2.0Select the document classification as per the defined

classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 26 of 66

28. Coding Standard – ABAPThis statement is specific to a single field. Using this statement can cause

unpredictableresults.Internal TablesDefining internal tablesWhen defining a table using occurs the ‘occurs’

statement allocates an area in memory ofthe specified size. It is generally accepted as preferable, to declare

a type (for customstructures) or use the database structure and use syntax ’standard table of’ to define

aninternal table.Internal tables should be defined, whenever possible, without header lines. It

improvesreadability to use work areas instead when processing internal tables.Incorrect: DATA: BEGIN OF

T_MAT OCCURS 0, MATNR LIKE MARA-MATNR, WERKS LIKE MARC-WERKS, DISPO LIKE MARC-DISPO, END OF

TYPE_MAT.Correct: TYPES: BEGIN OF TYPE_MAT, MATNR LIKE MARA-MATNR, WERKS LIKE MARC-WERKS, DISPO

LIKE MARC-DISPO, END OF TYPE_MAT. DATA: IT_MAT TYPE STANDARD TABLE OF TYPE_MAT, WA_MAT TYPE

TYPE_MAT.Always use Work Areas while processing internal tables. LOOP AT IT_MAT INTO WA_MAT. ENDLOOP.

(OR)Use Field symbols on LOOP/READ statements as it is easier to modify the internal table entryand also

avoids the usage of MODIFY statements.Sorting internal tablesWhen sorting internal tables, specify the fields

to SORT on.SORT ITAB BY FLD1 FLD2. Is more efficient than SORT ITAB. (OR)Instead of using SORT table itab

with matnr use, SORTED table with table key matnrThe access type of an internal table defines the way in

which ABAP accesses the individualtable entries. There are three access types: Standard, Sorted, and

Hashed.DELETE ADJACENT DUPLICATES statement should always be used with specific sort /comparison

fields.Incorrect:DELETE ADJACENT DUPLICATES FROM T_DOCUMENT.CS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 27 of 66

29. Coding Standard – ABAPCorrect:DELETE ADJACENT DUPLICATES FROM T_DOCUMENT COMPARING VBELN

VBELP.Note: Internal Tables should be always sorted before using DELETE ADJACENT DUPLICATES.Standard

Internal TablesStandard tables have a linear index. You can access them using either the index or the key.

Ifyou use the key, the response time is in linear relationship to the number of table entries. Thekey of a

standard table is always non-unique, and you may not include any specification forthe uniqueness in the table

definition.This table type is particularly appropriate if you want to address individual table entries usingthe

index. This is the quickest way to access table entries. To fill a standard table, appendlines using the

(APPEND) statement. You should read, modify and delete lines by referring tothe index (INDEX option with the

relevant ABAP command). The response time for accessinga standard table is in linear relation to the number

of table entries. If you need to use keyaccess, standard tables are appropriate if you can fill and process the

table in separatesteps. For example, you can fill a standard table by appending records and then sort it. If

youthen use key access with the binary search option (BINARY), the response time is inlogarithmic relation to

the number of table entries.Sorted Internal TablesSorted tables are always saved correctly sorted by key.

They also have a linear key, and, likestandard tables, you can access them using either the table index or the

key. When you usethe key, the response time is in logarithmic relationship to the number of table entries,

sincethe system uses a binary search. The key of a sorted table can be either unique, or non-unique, and you

must specify either UNIQUE or NON-UNIQUE in the table definition. Standardtables and sorted tables both

belong to the generic group index tables.This table type is particularly suitable if you want the table to be

sorted while you are stilladding entries to it. You fill the table using the (INSERT) statement, according to the

sortsequence defined in the table key. Table entries that do not fit are recognized before theyare inserted.

The response time for access using the key is in logarithmic relation to thenumber of table entries, since the

system automatically uses a binary search. Sorted tablesare appropriate for partially sequential processing in

a LOOP, as long as the WHERE conditioncontains the beginning of the table key.DO NOT use APPEND to fill

the entries of SORTED internal table.Do NOT use SORTED tables in database SELECT statements as it would

lead to a short dump ifthe system tries to append the entries into the sorted internal table.Hashed Internal

TablesHashed tables have no internal linear index. You can only access hashed tables byspecifying the key.

The response time is constant, regardless of the number of table entries,since the search uses a hash

Page 12: Abap

algorithm. The key of a hashed table must be unique, and youmust specify UNIQUE in the table definition.This

table type is particularly suitable if you want mainly to use key access for table entries.You cannot access

hashed tables using the index. When you use key access, the responsetime remains constant, regardless of

the number of table entries. As with database tables,the key of a hashed table is always unique. Hashed

tables are therefore a useful way ofconstructing and using internal tables that are similar to database

tables.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 28 of 66

30. Coding Standard – ABAPDO NOT use APPEND to fill the entries of HASHED internal table.CollectThe

COLLECT statement is used to create a unique dataset.To fill a standard internal table without creating

duplicate entries and add up the Packed,Integer, and Floating Point fields at the same time, use: COLLECT

itab.This is only recommended for tables for which you expect approximately 50 entries or less.The COLLECT

statement scans the table sequentially for a match on all fields that do nothave a data type of Packed,

Integer, or Floating-Point. Hence it is can be resourceexpensive for larger tables.When dealing with larger

internal tables, it is more efficient to READ the internal table withkey, and then perform an INSERT or MODIFY

statement on the table depending on the returncode.Other ways to create unique datasets are to fill an

internal table with all entries SORT it thenuse the statement ‘DELETE ADJACENT DUPLICATES’. (This

statement is much more efficientthan deleting using a LOOP structure that would achieve the same

effect).ABAP List ViewerA call back FORM in List Viewer should not be called the same name as an ABAP event

orkeyword.i.e. rt_events-form = TOP_OF_PAGE.Incorrect:*&---------------------------------------------------------------------

**& Form DEFINE_EVENTS*&---------------------------------------------------------------------** This form defines the events

for display list*----------------------------------------------------------------------** <--RT_EVENTS Event

table*----------------------------------------------------------------------*FORM define_events TABLES rt_events LIKE t_events.

rt_events-name = slis_ev_top_of_page. RT_EVENTS-FORM = TOP_OF_PAGE. APPEND rt_events.ENDFORM. "

DEFINE_EVENTSCorrect:*&---------------------------------------------------------------------**& Form

DEFINE_EVENTS*&---------------------------------------------------------------------** This form defines the events for display

list*----------------------------------------------------------------------** <--RT_EVENTS Event

table*----------------------------------------------------------------------*FORM define_events TABLES rt_events LIKE

t_events.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 29 of 66

31. Coding Standard – ABAP rt_events-name = slis_ev_top_of_page. rt_events-form =

PROCESS_TOP_OF_PAGE. APPEND rt_events.ENDFORM. " DEFINE_EVENTSABAP QueriesABAP Queries should

not be used in production. A query generates a program which mustbe reviewed by ABAP COE. The generated

program must have the following disciplines inplace: • Program Header is required • Program Name should

end with _Query • If a key field statement is being used in a Where statement in SQL, then the field must be

made mandatory on the selection screen so that Index scan is forced rather than a table scan.SAPScript

Coding StandardsPrint ProgramPrint Program - Header At the top of each print program include the header

text.Print Program and Form (Layout Set) CombinationsSAP allows multiple print programs to call one form

layout. To reduce complexity andmaintenance a newly enhanced form layout should have its own enhanced

print programthat calls this form. Here are some examples of the Print Program(s) on the left that calls

theForm on the right:Example 1: Print Program #1 - change Form #1 - change Print Program #2 - no change

becomes ZPrint Program #1 - changed ZForm #1 - changed Print Program #2 - no change Form #1 - no

changeExample 2: Print Program #1 - change Form #1 - change Form #2 - no change becomes ZPrint

Program #1 - changed ZForm #1 - changed Print Program #1 - no change Form #2 - no changeCS_ABAPCDS

– Version 2.0Select the document classification as per the defined classification in the master list of

documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 30

of 66

32. Coding Standard – ABAP Form Painter - Adding and Deleting WindowsWhen adding a window to a page

use Z as the first letter of the window name. You candelete windows from pages that are no longer being

used by the print program. Deletewindows when it is necessary to reduce clutter within the form and to make

futuremaintenance less complex. Do not use the Graphical Form Painter to delete windows sincethis editor

permanently deletes the window from the form. Use the older non-graphical formpainter to remove the

Window from Page Windows (the window will still remain in the form).You are then required to document the

deleted window name in the Documentationsection of the form.Form Painter - Delete LinesFor program

enhancements within a window refer to 3.1.6. You can only delete lines inblocks as shown below./*63-JWILMO-

20000204 begin: delete/*&REGUH-NAME1&/*63-JWILMO-20000204 end: deleteForm Painter - ElementsWithin

a window, do not change the element name/number that is being called a printprogram. If the element is no

Page 13: Abap

longer being used by the print program (or other printprograms), you can comment out the code

‘deleted/comment out elements clause shownbelow. However, do no comment out the element itself. If more

than one block of elementscan be commented out you can begin at the top of the first element and end at

the bottomof the last element as shown in elements 512 and 513 below./*63-JWILMO-20000204 begin:

delete/comment out elements512/*The items listed below are managed on the following account:/*&REGUH-

NAME1&/*&REGUH-STRAS&513/*------------------ Heading

---------------------------------------------/*&ULINE(71)&/*<K>Document,,Your document,,Date,,,,Deductions,,Gross

amount</>/*<K>Number,,Date,,Text</>/*63-JWILMO-20000204 end: delete/comment out

elementsStandards for all Enhancement User Exits • Always create a new separate include for each Gap in a

SAP Enhancement exit Separate User Exits allow enable the independent migration of code as part or the

promote-to-production path • Using the EXIT statement will terminate processing for all subsequent user

exitsCS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 31 of 66

33. Coding Standard – ABAP • The use of memory pointers in order to overcome User Exit Interface limitations

is not permitted FIELD-SYMBOLS: <F> TYPE STANDARD TABLE. ASSIGN ((SAPMV56A)XVTTP[]) TO <F>.

T_XVTTP = <F>.The variable XVTTP accessed in this example is not within the regular data scope of

thecurrent program. In order to overcome this limitation and we are using the Assign statementagainst a

specific memory location. During the execution of the VOFM we have no controlof the availability of this

memory location. The SAP Interpreter basically searches all availablememory areas for the specified name

and returns the value found in the first location - thatsa solution thats very difficult to maintained going

forward - Any OSS note or externaltransport could affect the availability of specific variables in SAP Memory –

this isunacceptable.DO NOT use CHECK statements in User-exits instead use IF….ENDIFCustom BAPI

DevelopmentBAPI must be part of the Business Object Repository (BOR). Use Business Object Builder (BOB –

Transaction SWO1) to associate a BAPI with a Business Object.Naming Convention for custom BAPI’s is

ZBAPI_objectname_method name i.e.ZBAPI_COMPANYCODE_GETDETAIL.Do not use BAPI in a report program

if you require a few fields. Instead make use of selectstatement. If its an online transaction program or you

will be needing most of the fields thenusing BAPI is OK.BAPI Interface consists of Import and Export only. No

Tables and no Exceptions should beused in the BAPI Interface.All messages need to be returned to the calling

program via Return Structures: BAPIRET1 or BAPIRETURN BAPIRET2Adding a BAPI to an existing SAP object

should be done using Subtypes and should not havea Z* as part of the naming convention. Z* is only used for

BAPIs belonging to custom objects.All messages that can be issued by a BAPI MUST be listed in the BAPI

DocumentationSome Basic Rules: • Always perform database changes using the update task • No screen

output allowed in BAPI • Can not cause program termination i.e. message type A • Cannot dispatch commit

work - Must useBapiService.TransactionCommit (Function Module BAPI_TRANSACTION_COMMIT)CS_ABAPCDS

– Version 2.0Select the document classification as per the defined classification in the master list of

documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 32

of 66

34. Coding Standard – ABAPPlease refer to SAP BAPI Programming Guide for more detail on programming with

BAPIs. In4.6, use transaction BAPI to get to relevant documentation. Other sources

arehttp://service.sap.com/bapiLogical DatabasesLogical databases can be inefficient because they can

generally be thought of as nestedselects where large volumes of data as retrieved which may not exactly

match reportrequirements. There are, however, instances when the use of a logical database can bejustified.

For instance, in Asset Management a large number of calculations are performedwhich would take a large

amount of time to replicate in custom code. Where a logicaldatabase maps closely to the data required by a

program it maybe justified incorporating itinto the code however checks should be made to ensure that the

authority checksperformed by the logical database are sufficient.Selection Screen ParametersInclude

organizational entities (e.g. sales organization, plant) fields in the selection screenwherever it makes sense as

this can also help reduce execution time (this should bemandatory for multiple company implementations).

Use can often be made of the userparameter IDs to bring values into a selection screen. The following is an

example of how thiscan be coded:Parameters: SALES_ORG LIKE TVKOV-VKORG MEMORY ID VKO.Frequently

used parameter ID codes are:Company Code BUKSales Organization VKODistribution Channel VTWDivision

SPAPlant WRKStorage location LAG USE SELECT-OPTIONS with NO-EXTENSION NO INTERVALS instead of

PARAMETER SELECT matnr into wl_matnr From mara Where matnr IN s_matnr.Program

DocumentationDocumentation of all new ABAP developments is completed in three ways. Program Folder

OverviewThe initial development results in a program folder that is stored electronically

(whererelevant).Subsequent modifications are monitored via the project Change Control system and

eachchange will result in additional testing documentation clearly documenting the change.Again, these will

Page 14: Abap

be stored electronically. Header details and on-line help are recorded inthe program itself.CS_ABAPCDS –

Version 2.0Select the document classification as per the defined classification in the master list of documents’

for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 33 of 66

35. Coding Standard – ABAPFor all new programs, the following components make up the program folder:1.

Program Functional Specification (provided by User/Configurer/Implementation Team member on-site),2.

Program Technical Specification (written internally to ABAP team),3. Commented program source code (all

messages and text elements must be fully commented),4. Test conditions,5. Test plan using all test

conditions,6. Test Data used in the Test Plan,7. Expected Results for each Test Condition in the Test Plan,8.

Actual Results generated when the Test Plan is executed,9. ALE related interface will also require a

configuration script review to validate entries have been added for that particular interface.10. Program on-

line help documentation.Once a program change has been requested. The program folder also contains:1.

Copy of change request2. Amended source code (commented where appropriate changes have been made)3.

Additional test data and results, along with test plan and test conditions. Source Code DocumentationAll ABAP

developments start with the program name followed by header documentationrelating to the purpose of the

report. The program author and creation date, together withinformation relating to the report user is also

included. This type of header is also used forcustom-built include modules, and custom-built function

modules.Example:************************************************************************* 1/ Report name:

Cost Centre report************************************************************************* 2/

Description/program functions************************************************************************** This

program is a Cost Centre report, which can be sorted* And summarized in different

formats.************************************************************************** 3/

Responsibility************************************************************************ * Author: A

Programmer* Creation Date: 14th February 02* Requested by: E User* Reference document: (design

document)* Owner: Controlling* Project: A

Project************************************************************************* 4/ External

References*************************************************************************CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 34 of 66

36. Coding Standard – ABAP* Include modules, input files

etc.*************************************************************************REPORT ZKEVR034 NO

STANDARD PAGE HEADING LINE-SIZE 132 LINE-COUNT 65 MESSAGE-ID ZE.Within the code comments are

added as necessary to ensure that the code is clear,readable and maintainable. On-line HelpOn-line help will

accompany all on-line programs. This is held in the Documentation elementof the ABAP program. Four

sections are usually populated by default and details for eachare:Description: an overview of what the

program does (and who the program is intended for).Parameters: an explanation of the select options where

appropriate.Output:an explanation of the different output options where appropriateThis documentation can

then be accessed by the user via the Help / Extended Help menupath when running the program. Program

AttributesIn addition to the title an ABAP report should be given the following attributes:Type: e.g. 1

(Reporting) (as appropriate)Status: K (Customer program)Application: S (Basis) (as appropriate)It is not

normally necessary to assign the program to a class but it can be important that anAuthorization Group is

assigned. This is to ensure that the program can be properly securedbut is the responsibility of client

authorization specialists to review. Program ModificationsAny changes that are made to a program (because a

problem has been identified orbecause further enhancements are required) are carefully documented in the

code (as wellas in the program folder). A summary of the change is included in the headerdocumentation of

the code, immediately below the author

details.************************************************************************** Revised by: A Programmer*

Change Date: 14/2/02* Change Request: 00001* Description: Addition of the document type Invoice*

Cancellation (N) to the program selection* OSS Note: 00001 (If required)* Changes identified by: XD1

S00K900001************************************************************************The CR (Change Request)

number from the Change Request system should be entered sothe change details can be referenced, as

should the SAP System and Correction numberrelating to the change.CS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 35 of 66

37. Coding Standard – ABAPCode which needs to be changed is not removed but preceded by * to remain

ascomment. Any section changed is surrounded with some form of documentation andcommented as normal.

The SAP correction and transport number is used to identify each linewhich change the code applies to, as

illustrated in the following example:* Code commented out by A. Programmer 14/02/02 to implement change

to add* Doc type invoice cancellation (N) to Credit memo (O) and Debit memo (P)* IF VBRK-VBTYP = O OR

Page 15: Abap

VBRK-VBTYP = P. “XD1 S00K900001 CLEAR MAKE_NEGATIVE. “XD1 S00K900001 IF VBRK-VBTYP = O. “XD1

S00K900001 MAKE_NEGATIVE = Y. “XD1 S00K900001 ENDIF. “XD1 S00K900001* End of code commented out

by A. Programmer 12/09/98. Program TestingAll code is thoroughly Unit Tested before it is submitted for User

Testing. The testing strategy isdocumented by two documents:• Test Conditions - details what conditions will

be tested.• Test Plan - details how the conditions will be testedTest ConditionsBefore coding, all conditions

that will require testing are defined from the FunctionalSpecification. Obviously, as each program differs in its

output, it therefore has a set of testconditions unique to itself. However, there are common features to most

programs and testconditions that are of general application. The following test conditions (which

cannotnecessarily be tested on the same test run) are typical:Selection screen Selection screen contains a

range of sales organization/plant/division boxes. Selection screen contains a single parameter box for

currency, defaulting to theuser’s parameter ID setting for currency. Currency parameter box cannot be left

blank.Selection Report selects within range of sales organizations/plants/divisions specified. Report selects a

single value of sales organization. Report doesn’t select outside the specified ranges. Report verifies that the

currency entered in the parameter box is a valid value. Report terminates if the user attempts to view

documents for which there is no authorization.Report header Report header displayed correctly once at the

top of each page of the report. Report selections displayed correctly on first page beneath report header.

Column headers displayed correctly once at the top of each page of the report.Report layout Detail lines

formatted correctly. Report is sorted correctly by sales organization, customer... A new page is started for

each new plant/sales org/customer/material... Full fields are displayed correctlyCS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 36 of 66

38. Coding Standard – ABAPFunctions Currencies are correctly converted Totals for each plant/sales

org/customer/material... are correct. Totals for the report are correct. Download file is contains correct

dataExceptions Program handles one record correctly. Program handles many records correctly. Program

handles no records at all. Program reports correctly if attempting to view unauthorized records. Test PlanOnce

test conditions have been written, the programmer writes a test plan. This is adocument that details how the

test conditions will be tested in a step-by-step format. Itmakes reference to the actual test data used

(documented in the program folder) anddetails the expected results, while also referencing the actual results

for comparison.Test DataTest data is the data that was used to test the scenarios documented on the test

plan. Thereare cross-references on the test plan to the test data used. Test data can be, for example,print

outs of SAP table contents with relevant records highlighted, Variant print outs or datadocumented in a word

or spreadsheet format. This is documented and kept in a separatesection in the program folder.Expected

ResultsExpected results are results that are expected to occur if the test data specified is used toexecute the

step specified on the test plan. This is either documented on the test plan (e.g.error messages) or

documented in a word or spreadsheet format (e.g. expected results ofreport calculations on test

data).Relevant expected results are cross-referenced to the corresponding actual results.Actual ResultsActual

results are documentary evidence of the test run result. They can be screen dumps(e.g. selection screen

errors displayed), actual report print outs or spool printouts.Actual results are cross-referenced to the test

conditions that they relate to and arenumbered for easy reference e.g. for test run 1, they would be called

AR1, etc.Naming ConventionsPlease refer to the project naming conventions document for guidelines and

procedures inthe naming of SAP Objects.Alternatively please contact the ABAP project manager.Program

Documentation TemplatesProgram folders are documented in a consistent manner using the following header

patternsas reference.CS_ABAPCDS – Version 2.0Select the document classification as per the defined

classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 37 of 66

39. Coding Standard – ABAP Program

Header************************************************************************* 1/ Report

Name:********************************************************************************************************

****************************************** 2/ Description/ Program

functions*****************************************************************************************************

*********************************************** 3/

Responsibility************************************************************************* Author:* Creation

Date:* Requested by:* Reference Document:* Owner:*

Project:************************************************************************* Revised by:* Change Date:*

Change Request:* Description:* SAP

Correction:************************************************************************ Program

Change************************************************************************* Revised by:* Change Date:*

Change Request:* Description:* SAP

Page 16: Abap

Correction:************************************************************************CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 38 of 66

40. Coding Standard – ABAP Include Program

Header************************************************************************* 1/ Include

Name:********************************************************************************************************

****************************************** 2/ Description/ Include

functions*****************************************************************************************************

*********************************************** 3/

Responsibility************************************************************************* Author:* Creation

Date:* Requested by:* Reference Document:* Owner:*

Project:************************************************************************* Revised by:* Change Date:*

Change Request:* Description:* SAP

Correction:************************************************************************

Sub-routine/Form************************************************************************* Form:*

Description:* -> Input Parameter TEXT* <- Outbound Parameter TEXT* Called by:*

Calls:************************************************************************Example:*--------------------------------

-------------------------------** Form GET_LAST_RUNDATE_TIME **---------------------------------------------------------------**

This form is to read table ZZLRT where last run time and date ** of this ABAP program is stored.

**---------------------------------------------------------------** Parameters / Tables: ** --> JOBID Job name used to run this

ABAP ** --> REPID ABAP name **---------------------------------------------------------------* FORM

GET_LAST_RUNDATE_TIME USING JOBID REPID.CS_ABAPCDS – Version 2.0Select the document classification

as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 39 of 66

41. Coding Standard – ABAP Function

Module************************************************************************* 1/ Function Module

Name:********************************************************************************************************

****************************************** 2/ Description / Function module

functions*****************************************************************************************************

*********************************************** 3/

Responsibility************************************************************************* Author:* Creation

Date:* Requested by:* Reference Document:* Owner:*

Project:************************************************************************* Revised by:* Change Date:*

Change Request:* Description:* SAP

Correction:************************************************************************The Function Module

Interface should adhere to the following naming conventions:Importing Parameters: IM_x….xExporting

Parameters: EX_x…..xChanging Parameters: CH_x….xTables Parameters: TB_x….xThe use of Tables in custom

developed function modules should generally be avoided sinceit implies the use of old internal table definition

with header lineFunction Module – Exception HandlingFor SAP function modules or generic custom function

modules we MUST handle themessaging ourselves since we dont have detailed messages in the functions. In

order for thegeneric syntax to work below the function must make use of the Message...Raising format sothat

the SY variables are properly set.After a call to a function, the developers are routinely using the following

default as insertedby the editor.Incorrect: IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-

msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.CS_ABAPCDS – Version 2.0Select the document

classification as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 40 of 66

42. Coding Standard – ABAPThis is not allowed unless the Message...Raising format is used consistently

throughoutthe function.After a Call Function, it is the developer’s responsibility to check the return code

andprovide meaningful messaging.Sample Code: ZSDR_TAKEALL_CLOSEOUT and its call to CALL

FUNCTIONZ_SD_ORDER_MATERIAL_QUANTITIES for an example of specific custom message handlingCorrect:

CALL FUNCTION Z_SD_ORDER_MATERIAL_QUANTITIES EXPORTING p_del_prc_qty = c_on p_confirm_qty = c_on

TABLES t_orders = rt_vbeln t_status = rt_item_qty EXCEPTIONS input_not_correct =1

selected_qty_not_correct = 2 quantities_not_selected = 3 OTHERS = 4. CASE sy-subrc. WHEN 1. MESSAGE

e555 WITH Invalid input(009). WHEN 2. MESSAGE e555 WITH Selected qty not correct(011). WHEN 3.

MESSAGE e555 WITH Quantities not selected(012). WHEN 4. MESSAGE e555 WITH Other Reasons(013).

ENDCASE.Application OSS notesThe following program header should be copied into any program when an

OSS note isapplied: ******************************************************************* * OSS Note History *

**-----------------------------------------------------------------* * OSS Note Date OSS Note Version & Date Username *

Page 17: Abap

------------------------------------------------------------------* * xxxxxxxxxx mm/dd/yyyy zzzzz from MM/DD/YY

zzzzzzzzzzzz * *-----------------------------------------------------------------*The version is part of the OSS note

information. SAP pretty often updates OSS notes andtherefore we need to be able to identify which version

has been appliedEach code section thats affected by an OSS note should be marked as described below:Minor

change: DATA: BEGIN OF I_CLEARED_CHECKS_RECORD, I_CHECT(10), I_DATUM(8), “<<< insert OSS Note

12345678 mgiess * I_FILLER(62), “<<< delete OSS Note 12345678 mgiess END OF

I_CLEARED_CHECKS_RECORD.CS_ABAPCDS – Version 2.0Select the document classification as per the defined

classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 41 of 66

43. Coding Standard – ABAPMajor change Insert Example: * OSS Note 12345678 mgiess Insert begin: DATA:

BEGIN OF I_CLEARED_CHECKS_RECORD, I_CHECT(10), I_DATUM(8), I_FILLER(62), . . . <30 more lines of new

code> END OF I_CLEARED_CHECKS_RECORD. * OSS Note 12345678 mgiess Insert endThe following examples

contain the modification assistant automatic comments (shown inblue below).Major change Delete only

Example:*{ INSERT DE1K901245 1*OSS Note 211722 jwilmo delete begin*} INSERT*{ DELETE DE1K901245

3* IF NOT XEK08BN-J_3AFSKZ IS INITIAL AND "AFS-Material AFS* NOT XEK08BN-J_3AEBSP IS INITIAL AND

"Kond auf Pos AFS* TKOMV-J_3AETENR IS INITIAL AND "auf Pos.Ebene AFS* TKOMV-KRECH = C AND

"mengenabhängig AFS* TKOMV-KNTYP = B. "BzNebKos AFS* H-WERT = TKOMV-KWERT * EKPO-MENGE. " AFS*

H-WERT = H-WERT / LD_EKPO-MENGE. " AFS* ENDIF. " AFS*} DELETE*{ INSERT DE1K901245 2*OSS Note

211722 jwilmo delete end*} INSERTNote the standard delete comments containing the OSS note number are

‘inserted’ in thecode before and after the delete. Modification assistant does not allow comments whenyou

delete code.Major change Replace Example if the lines being inserted for the replace allow the OSS

notecomment:*{ REPLACE DE1K900368 1* X_INRIV-EXTERNIND NE X . x_inriv-externind ne X and "<<<

Replace OSS Note 169411 cwood1 ( baltd-tcode = AS91 or "<<< Insert OSS Note 169411 cwood1 baltd-tcode

= AS81 ). "<<< Insert OSS Note 169411 cwood1*} REPLACEMajor change Replace Example if the lines being

inserted for the replace do not allow theOSS note comment on the same line:*{ INSERT DE1K900370 1* OSS

Note 0177387 mwild Replace BEGIN:*} INSERT*{ REPLACE DE1K900370 2* if itab_dd03p_orig-adminfield = if

itab_dd03p_orig-adminfield <=* OSS Note 01770387 mwild Replace END.CS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 42 of 66

44. Coding Standard – ABAP*} REPLACECS_ABAPCDS – Version 2.0Select the document classification as per

the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 43 of 66

45. Coding Standard – ABAP ABAP Program TemplatesThis appendix details some basic recommended

programming templates for various types ofABAP program. Basic Report List(Use standard program header as

outlined in program documentation

section).************************************************************************ Table Declarations

************************************************************************TABLES:******************************

****************************************** Selection Screen Parameters

************************************************************************SELECT-

OPTIONS:PARAMETERS:************************************************************************ Data

Declarations ************************************************************************INCLUDE... (For data

definitions)DATA: ... i_int_tab TYPE STANDARD TABLE OF ty_int_tab.FIELD-GROUPS: INSERT... INTO

HEADER...FIELD-SYMBOLS:Include constants, working

storage.***********************************************************************The INITIALISATION event

occurs before the selection screen is shown. It happens only onceand is ignored in background

processing.************************************************************************

Initialization***********************************************************************INITIALIZATION. (Set up

defaults for select options if

necessary).***********************************************************************This event is used for

selection screen checks and validation of correct entries. It occurs eachtime the ENTER key is hit on the

selection screen. This event is ignored in

backgroundprocessing.************************************************************************ At Selection-

Screen Event***********************************************************************AT SELECTION-

SCREEN.***********************************************************************This event is used to set up

report header details.******************************************************************************** Top of

Page EventCS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in

the master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 44 of 66

Page 18: Abap

46. Coding Standard –

ABAP*******************************************************************************TOP-OF-

PAGE.***********************************************************************This event is used for report

footer processing.******************************************************************************** End of Page

Event*******************************************************************************END-OF-

PAGE.***********************************************************************This event is used to begin the

data retrieval.******************************************************************************** Start of

Selection*******************************************************************************START-OF-

SELECTION.Select records: SELECT.... FROM.... WHERE...INProcess/further validation of selected

dataAppend/modify internal table or extract dataset.This event can be used to output

details.******************************************************************************** End of

Selection*******************************************************************************END-OF-

SELECTION.SORT...LOOP / LOOP AT Totals/sort processing events: AT FIRST. ENDAT. AT NEW… ENDAT. AT

END OF... ENDAT. AT LAST. ENDAT.ENDLOOP.Subroutines - include any reusable code:FORM...CS_ABAPCDS –

Version 2.0Select the document classification as per the defined classification in the master list of documents’

for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 45 of 66

47. Coding Standard – ABAPENDFORM.Interactive ABAP Report List(Use standard program header as outlined

in Program Documentation

section).******************************************************************************** Table

Declarations*******************************************************************************TABLES:***********

********************************************************************* Selection Screen

Parameters*******************************************************************************SELECT-

OPTIONS:PARAMETERS:******************************************************************************** Data

Declarations*******************************************************************************INCLUDE... (For

data definitions)DATA: ... i_int_tab TYPE STANDARD TABLE OF ty_int_tab.FIELD-GROUPS: INSERT... INTO

HEADER...FIELD-SYMBOLS:Include constants, working storage.The INITIALISATION event occurs before the

selection screen is shown. It happens only onceand is ignored in background

processing.********************************************************************************

Initialization*******************************************************************************INITIALIZATION.

(Set up defaults for select options if

necessary).*******************************************************************************This event is used

for selection screen checks and validation of correct entries. It occurs eachtime the ENTER key is hit on the

selection screen. This event is ignored in

backgroundprocessing.******************************************************************************** At

Selection-Screen Event*******************************************************************************AT

SELECTION-SCREEN.*******************************************************************************This event

is used to set up report header

details.******************************************************************************** Top of Page

Event*******************************************************************************TOP-OF-

PAGE.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 46 of 66

48. Coding Standard –

ABAP*******************************************************************************This event is used for

report footer processing******************************************************************************** End

of Page Event*******************************************************************************END-OF-

PAGE.*******************************************************************************This event is used to

begin the data retrieval.******************************************************************************** Start

of Selection******************************************************************************START-OF-

SELECTION.Select records: SELECT.... FROM.... WHERE...INProcess/further validation of selected

dataAppend/modify internal table or extract

dataset.*******************************************************************************This event can be used

to output details.******************************************************************************** End of

Selection*******************************************************************************END-OF-

SELECTION.SORT...LOOP / LOOP AT Totals/sort processing events: AT FIRST. ENDAT. AT NEW... ENDAT. AT

END OF... ENDAT. AT LAST. ENDAT.ENDLOOP.Subroutines - include any reusable

code:FORM...ENDFORM.CS_ABAPCDS – Version 2.0Select the document classification as per the defined

Page 19: Abap

classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 47 of 66

49. Coding Standard – ABAPBatch Input Program(Use standard program header as outlined in program

documentation section).******************************************************************************** Table

Declarations*******************************************************************************TABLES:***********

********************************************************************* Selection Screen

Parameters*******************************************************************************SELECT-

OPTIONS:PARAMETERS:******************************************************************************** Data

Declarations*******************************************************************************INCLUDE... (For

data definitions)Batch data structure:DATA: BEGIN OF BDCDATA OCCURS 10. INCLUDE STRUCTURE

BDCDATA.DATA: END OF BDCDATA.FIELD-GROUPS: INSERT... INTO HEADER...FIELD-SYMBOLS:Include

constants, working storage.*******************************************************************************The

INITIALISATION event occurs before the selection screen is shown. It happens only onceand is ignored in

background processing.********************************************************************************

Initialization ********************************************************************************INITIALIZATION.

(Set up defaults for select options if

necessary).*******************************************************************************This event is used

for selection screen checks and validation of correct entries. It occurs eachtime the ENTER key is hit on the

selection screen. This event is ignored in

backgroundprocessing.******************************************************************************** At

Selection-Screen Event ********************************************************************************AT

SELECTION-SCREEN.*******************************************************************************This event

is used to begin the data

retrieval.******************************************************************************** Start of Selection

*CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the master

list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC>

Page 48 of 66

50. Coding Standard –

ABAP*******************************************************************************START-OF-

SELECTION.Upload data from temporary SAP table, or Unix file,READ DATASET FILE INTO REC.Or upload file

from a PC fileCALL FUNCTION WS_UPLOAD.Open the batch input (BDC) sessionCALL FUNCTION

BDC_OPEN_GROUP EXPORTING CLIENT = SY-MANDT GROUP = SESSION_NAME "session name USER = SY-

UNAME KEEP = X. "Keep session after processingLOOP AT TAB. Create the BDC entries for the first screen of

the transaction E.g. Screen 1000 PERFORM BDCDYNPRO USING X SAPMxxxx 1000 . PERFORM BDCDYNPRO

USING TABL-FIELD LITERAL. (Literal or field) Insert all other screens for this transaction. PERFORM

BDCDYNPRO USING X SAPMxxxx nnn . PERFORM BDCDYNPRO USING TABL-FIELD TAB-VAR. Insert data into

the BDC session. CALL FUNCTION BDC_INSERT EXPORTING TCODE = TCOD TABLES DYNPROTAB = BDCDATA.

REFRESH

BDCDATA.ENDLOOP.*******************************************************************************This event

can be used to output details.********************************************************************************

End of Selection ********************************************************************************END-OF-

SELECTION.Close the BDC Session.CALL FUNCTION

BDC_CLOSE_GROUP.*******************************************************************************CS_ABAPC

DS – Version 2.0Select the document classification as per the defined classification in the master list of

documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 49

of 66

51. Coding Standard – ABAPProgram Performance tuning techniquesThis appendix details some

recommended programming performance improvementtechniques and considerations that can be used

during the construction phase of an ABAPprogram.Technique 1: Using Select StatementsWhen using the

statement:SELECT * FROM tableIn order to extract all records from a given table, it is more efficient to narrow

the selectionusing specific table fields as search keys.For example:SELECT * FROM VBAK ….Instead

use:SELECT VBELN, AUART, BNAME, KUNNR INTO (VBAK-VBELN, VBAK-AUART, ….)FROM VBAK..The

performance advantage in selecting 1000 records, for instance, using fields VBELN,AUART, BNAME & KUNNR

only can be considerable: SELECT * FROM table producing results in 2,910,000 micro seconds(ms) SELECT

column1 ,.. producing results in 239,000 ms Technique 2: Selecting ordered records from a tableWhen

selecting records from a table and then having them ordered in a specified orderusing theSELECT FROM table

ORDER BYStatement, such as:SELECT VBELN BNAME... INTO TABLE IVBAK FROM VBAKWHERE BNAME IN

S_BNAME ORDER BY BNAMEIt is better to use this statement:SELECT VBELN, AUART, BNAME, KUNNR INTO

Page 20: Abap

TABLE IVBAK FROM VBAKWHERE BNAME IN S_BNAME.SORT IVBAK BY BNAME.The Sort statement sorts IVBAK

the table once it has been populated. In the formerstatement, the sort takes place record by record, whereas

in the latter statement, the sorttakes place more efficiently on the whole table after being

populated.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 50 of 66

52. Coding Standard – ABAPThis is because the former statement interrogates the database twice in order to

select aspecific record. In the latter statement, the same result is achieved in less time and moreefficiently

because the database is interrogated only once. Technique 3: Reading large internal tables without using

binary searchWhen reading in internal table with a high number of records, like:SELECT VBELN KUNNR... INTO

TABLE IVBAK WHERE…READ TABLE IVBAK WITH KEY VBELN = ‘00900000090’.Where a key is used to search

for records with fields that match the key field, it is better to usea binary search to speed up the search. For

example:READ TABLE IVBAK WITH KEY VBELN = ‘00900000090’BINARY SEARCH TRANSPORTING NO FIELDSIn

order for the BINARY SEARCH to work properly the table must be sorted in ascending orderof the search

criteria.If you want to verify the existence of a record but don’t need any of the fields from therecord, then

use the faster variant: BINARY SEARCH TRANSPORTING NO FIELDS Technique 4: Moving data from Internal

Table 1 to Internal Table 2When populating an internal table with records from another internal table:LOOP AT

ITAB1. MOVE ITAB1 TO ITAB2. APPEND ITAB2.ENDLOOP.It is better to use:Itab2[ ] = itab1[ ].This is because

the former statement processing the source internal table on a record-by-record basis. The latter method

uses a single hit on the table to populate the destinationinternal table. Note that both the internal tables must

be of same structure in order to use thesecond method. Technique 5: Appending data from Internal Table 1 to

Internal Table 2When populating the destination internal table from the source internal table, like:LOOP AT

ITAB1. MOVE ITAB1 TO ITAB2. APPEND ITAB2.ENDLOOP.CS_ABAPCDS – Version 2.0Select the document

classification as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 51 of 66

53. Coding Standard – ABAPIt is better to use this statement:APPEND LINES OF ITAB1 TO ITAB2.This is

because the former statement appends records from the source table to thedestination table on a record-by-

record basis. This could a very long time if the source tablecontains a large number of records. However, the

second method uses a single “hit” on thesource table to populate the destination internal table. This is a far

more efficient processingstep. Technique 6: Deleting data from Internal TablesWhen deleting records from an

internal table, like:LOOP AT IVBAK WHERE BNAME = ‘SMITH’. DELETE BNAME.ENDLOOP.It is better to use this

statement:DELETE IVBAK WHERE BNAME = ‘Smith’.This is because the second method uses a single

processing step to delete specific recordsform internal table IVBAK, whereas the former method processed

each record in IVBAK oneby one.Here are a few things one should think about when checking for program

efficiency.Is the program using SELECT statements? Convert them to SELECT column1 column2 or use

projection views.Are CHECK statements for table fields embedded in SELECT ... ENDSELECT loop? Incorporate

the CHECK statements into the WHERE clause of the SELECT statementDo SELECT s on non-key fields use an

appropriate DB index or is the table buffered? Create index for the table in the data dictionary or buffer tables

if they are read onlyor read mostly.Is the program using nested SELECT s to retrieve data? Create a Database

View in the Data Dictionary and then use this View instead of thenested selects.Are there any SELECT

statements without a WHERE Condition against files that grow constantly(BSEG, MKPF, VBAK)? Program

design is wrong. Go back to performance tuning and read again.Is the program using SELECT ... APPEND

ITAB... ENDSELECT techniques to fill internal tables? Change the processing to read the data immediately into

an internal table. (SELECT VBELN AUART ... INTO TABLE IVBAK...)CS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 52 of 66

54. Coding Standard – ABAPIs the program using SELECT ORDER BY Statements? Data should be read into an

internal table first and then sorted, unless there is an appropriate index for the order by fields.Is the

programming doing calculations/summation that can be done on the database viaSUM, AVG, MIN or MAX

functions for the SELECT Statement? Use the calculation capabilities of the database via SELECT SUM....Are

internal tables processed using the READ TABLE itab WITH KEY ... technique?Change table accesses to use

BINARY SEARCH method. ABAP Code Review Checklist ABAP Code Review_checklist.xlsABAP ObjectsNaming

Conventions in ABAP ObjectsIntroductionABAP Objects namespace validity is very complex. In order to avoid

problems duringdevelopment it is not only helpful but also necessary to outline name conventionsfor that

matter.Classes and their dependent subclasses share the same namespace which affects Constants

(CONSTANTS) , Variables (DATA, CLASS-DATA) , Methods (METHODS, CLASS-METHODS) and Events (EVENTS,

CLASS-EVENTS).SAP has not yet decided whether to allow upper/lower case for internal names (to

separateindividual words - as in JAVA). Therefore in order to do that we still have to use theunderscore

Page 21: Abap

character.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification in the

master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 53 of 66

55. Coding Standard – ABAPNaming ConventionsGeneral rules: • Always use meaningful English terms for

naming objects. • Use glossary terms whenever possible. For example: ZCL_COMPANY_CODE, instead of

BUKRS, as this will be SAP"s standard in the future (see BAPIs) • Where names are grouped together use the _

as a separator. For example: ZCL_COMPANY_CODE, ZCL_GENERAL_LEDGER_ACCOUNT • Names should

describe what the subject is not how it is to be implemented. For Example: PRINT_RECTANGLE and not

RECTANGLE_TO_SPOOL.General Conventions ZCL_<class name> The class name should consist of nouns and

shouldClass in Class Library* only use the singular form: ZCL_COMPANY_CODE

ZCL_GENERAL_LEDGER_ACCOUNT ZIF_<interface name> Interfaces in The naming conventions for classes

also apply toClassLibrary* interface:. ZIF_STATUS_MANAGEMENT, ZIF_CHECKER Types in the DDIC* Z<type

name> LCL_<class name> The class name should consist of nouns and should Local Class only use the

singular form: LCL_TRANSACTION LIF_<interface name> The class name should consist of nouns and should

Local Interface only use the singular form: LIF_PRINTERObjects marked with * are protected by the global

TADIR, but they occupy the samenamespace as data elements, tables, structures and types.CS_ABAPCDS –

Version 2.0Select the document classification as per the defined classification in the master list of documents’

for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 54 of 66

56. Coding Standard – ABAPClass Conventions <method name>Method Name The method name should

begin with a verb. GET_STATUS, CREATE_ORDER, DETERMINE_PRICE <event name> Event names should be

named like this:Event <Noun>_<Participle of Verb >. BUTTON_PUSHED, COMPANY_CODE_CHANGED,

BUSINESS_PARTNER_PRINTED <type name>_tyLocal Class TypeDefinition INTERNAL_TYPE_TY, TREE_LIST_TY

<variable name> You should avoid using verbs at the beginning when naming Data Definition variables

within a class (CLASS-DATA, DATA).(Variable) (This is to prevent confusion with method names.) LINE_COUNT,

MARK_PRINTED, MARK_CHANGED, STATUS C_<constant name> Data Definition C_MAX_LINE,(Constants)

C_DEFAULT_STATUS, C_DEFAULT_WIDTH, C_MAX_ROWSFixed Method Names SET_<attribute name>,

GET_<attribute name> You should prefix all types ofAttribute Accesses attribute access with GET_ or SET

Accordingly, GET_STATUS, SET_USE_COUNTCS_ABAPCDS – Version 2.0Select the document classification as

per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 55 of 66

57. Coding Standard – ABAP ON_<event name> For methods that deal with an event, you should begin

theMethods that Deal with an Event name with ON followed by the name of the relevant event.

ON_BUTTON_PUSHED, ON_BUSINESS_PARTNER_PRINTED AS_<new Type>Methods that carry out

TypeConversions AS_STRING, AS_ISOCODEMethods that deliver a BooleanValue These methods cannotreturn

IS_<adjective> any EXCEPTIONS. Recommendation: The IS_OPEN, IS_EMPTY, Boolean value should be

IS_ACTIVE represented bySPACE/"X" for False/True.Check Methods These methods differfrom the

IS_<adjective>" methods CHECK_<objective>by their ability to return CHECK_AUTHORIZATION, exceptions.

CHECK_PROCESS_DATE CHECK_AUTHORIZATION, CHECK_PROCESS_DATEMethod ConventionsThe parameters

are observed from the point of view of the methods, which implementedthem:CS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 56 of 66

58. Coding Standard – ABAPIMPORTING-Parameter IM_<parameter name>EXPORTING-Parameter

EX_<parameter name>CHANGING-Parameter CH_<parameter name>RESULT RE_<result>EXCEPTIONS See

"Exceptions"ExceptionsThe developer’s job is made easier when standards for the naming of exceptions

areavailable. The following is a table of meaningful exceptions, which can also be usedgenerically.

(Example: ...NOT_FOUND could become DATE_NOT_FOUND)EXCEPTION MEANINGACTION NOT The requested

action or the requested OK-Code is not supportedSUPPORTED This EXCEPTION can be set if the user is

required to select what happensCANCELLED next in a method (for example: Selection List) and he/she selects

"Cancel".EXISTING A new object already exists in the database. The methods could not carry out your task

because of the present state of the environment. This exception is especially intended for casesFAILED where

the environment is temporarily in a situation that does not allow the method tasks to be carried out. A sub

function of the method could not be carried out because of the..._FAILED present state of the environment.

(OPEN_FAILED, CLOSE_FAILED, SELECTION_FAILED, AUTHORIZATION_FAILED)FOREIGN_LOCK Other users lock

data.INCONSISTENT Object data in the database is inconsistent...._INCONSISTENT The sub-object data of an

object in the database is inconsistent. The object data entered is not correct. (e.g. Company Code is

notINVALID available) (in contrast to NOT_QUALIFIED) The given sub-object data of an object is not correct. (In

contrast to..._INVALID NOT_QUALIFIED) The last resort. If all else fails and the error can no longer be

Page 22: Abap

contained,INTERNAL_ERROR apply this EXCEPTION.NOT_AUTHORIZED The user does not have authorization

for this action.NOT_CUSTOMIZED The object requested is not correctly customized...._NOT_CUSTOMIZED The

sub-object of the object requested is not correctly customized.NOT_FOUND The requested object has not been

found...._NOT_FOUND The sub-object of the object requested has not been found. The combination of input

parameters is not sufficient to allow theNOT_QUALIFIED method’s functions to be carried out. (In contrast to

INVALID)..._NOT_QUALIFIED A specific parameter of the method is not qualifiedCS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 57 of 66

59. Coding Standard – ABAPNUMBER_ERROR Error in the provision of numbers. This exception can be set

where the Basis System registers anSYSTEM_ERROR unexpected error code.Work FlowIntroductionThis

document is created to outline naming standards, programming standards, andpreferred practices/approach

in Workflow development and provide guidelines for BusinessWorkflow development for WIPRO. These are

Wipro’s "Workflow Development Standards" andcontain WIPRO specific programming conventions as SAP best

practices.As new standards are developed, this guide will be updated on an ongoing basis. Thedocument is

intended for use by ABAP/Workflow developers as a guide for developmentsand enhancements to R/3. The

user of this document should be familiar with basic conceptsof R/3 and business workflows.OBJECTIVEThe

objectives of this document are as follows: • To describe a consistent set of practices so that all business

workflows follow these practices and use uniform conventions and techniques. • To recommend, explain and

suggest techniques that can be followed during design and development of SAP Business Workflow. Naming

Convention1.1Workflow Templates / TaskNaming Format Components Description / ChoicesAbbreviation

forworkflow template /Taskgd_xx G ‘Z’ to be used for all transportable programs ‘Y’ for all test programs

developed as local private objects and not intended for transportCS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 58 of 66

60. Coding Standard – ABAP d Development class xx Descriptive text1.2Business ObjectNaming Format

Components Description / ChoicesObject Typegxx g ‘Z’ to be used for all transportable programs ‘Y’ for all

test programs developed as local private objects and not intended for transport xx Descriptive text. If it is

inherited or copied from Standard Business Object, STD Object type to be mentioned here to replace xx. e.g.

ZBUS1001Object Namexx xx Meaningful name which will describe object type. Spaces are not allowed in

object name , so it should be a proper combination of Block and small letters e.g. PurchaseOrderNamexx Xx

Meaningful name which needs to be seen in Object builder. ( Spaces are allowed for this name) e.g. Purchase

OrderDescriptionxx xx Description to elaborate object type e.g. Purchase OrderNote: Naming of attributes,

methods and events is similar to naming convention of name ofObject and its description1.3Business Object –

programNaming Format Components Description / ChoicesProgram nameCS_ABAPCDS – Version 2.0Select the

document classification as per the defined classification in the master list of documents’ for your

project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 59 of 66

61. Coding Standard – ABAPgRXX G ‘Z’ to be used for all transportable programs ‘Y’ for all test programs

developed as local private objects and not intended for transport Rxx Along with constant ‘R’, Descriptive

text, preferably name same as super type object’s programNote: Naming of variables, constants and coding

standards for this program are same asreferred in Beacon Program ABAP standard document.Preferred

Approaches / practices:A. Workflow implementing approach: Activities to be carried out before development

of workflow: The first step in designing a business process for inclusion in a workflow should be to determine

the business objective for which the workflow is to be implemented. Gather following information about the

process so that it can be mapped to workflow for designing / development purpose. A. Determine SAP

Business object which can be used to carry out required functionalities. B. Determine exact flow of current

process so that it can be then mapped to workflow definition C. Determine what activities are involved in the

process, which can be mapped to individual steps inside Workflow definition D. Determine who are the

responsible/authorized persons involved in the process, as they have to be used as agents for routing the

correct work to correct person i.e. get the information of Organization structure. If organization structure is

not available/will not be used, decide upon agent determination strategy. E. Determine based on which

particular actions, workflow should react to them i.e. identify exact events based on which workflow should be

triggered. F. Get information about volume of data.B. Workflow scenario development: Design and

Development of a workflow scenario can be divided primarily under two heads: • Workflow template related

developments • Business Object related developments I. Workflow template related developments Approach

to be followed for workflow template related development: 1. SAP provides workflow templates that may suit

your objectives. Check whether same is serving the purpose.CS_ABAPCDS – Version 2.0Select the document

classification as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 60 of 66

Page 23: Abap

62. Coding Standard – ABAP 2. If template satisfies the requirements, use the existing template. 3. If the

purpose is not served, try to use it by configuring it- Involves activities like changing the agents, scheduling

dead-line monitoring, maintaining information texts etc. 4. If the purpose is not served by configuring, then

copy the template and then change it i.e. extend the template. 5. If the template for the required functionality

is not present, then create your own template. 6. When creating the template naming conventions to be

followed as mention in this document. 7. Check and decide upon handling error conditions within workflow

based on process requirements. Activities to be carried out during Workflow development: 1. As mentioned in

preferred approach section, if template needs to be developed, before creating a totally new workflow

template, check whether any SAP provided existing template can be used for extending its functionality. 2. So

by using base functionality of existing template, add only required functionality to meet the additional

requirements. 3. While adding steps to workflow template as far as possible use standard tasks as reusable

components i.e. check whether standard tasks available can be used instead of creating new tasks

separately. 4. For starting a workflow different mechanisms can be used, out of which use of events should be

preferred approach as far as possible. This approach has greater flexibility considering maintenance and

administration of workflows. 5. Once development of workflow template is complete, perform unit testing

through workflow builder and use tools like workflow log at this stage to remove errors so as to reduce

number of errors caused during testing in- conjunction with application. II. Business Object related

developments: Approach to be followed for business object related development: 1. Check whether standard

business object, its method and events can be used directly. 2. Check on the event triggering i.e. application

from which event is to be triggered by it, or needs a custom development or any other mechanism for raising

an event. 3. If the purpose is not served with available attribute or methods or events available with existing

object, then extend the object by using inheritance and delegation technique. 4. In the delegated BOR Object

types, don’t change any Standard SAP method. Instead develop a new method. Activities to be carried out

during Business Object development: 1. As mentioned in preferred approach section, if existing method,

attribute or events are not fulfilling the requirements, use inheritance and delegationCS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 61 of 66

63. Coding Standard – ABAP mechanism and then extend object to add required methods, attributes or events

to the object. 2. Before extending an object check if it is already extended, if available, use the same for

further extension. This will prevent creating more subtypes for the same object, which can be cumbersome

from maintenance point of view. 3. While adding custom methods, attributes and events follow naming

convention from this document. 4. Follow coding standards for Beacon Program ABAP standards in case

Object program is modified manually. 5. Once extension of object is complete, generate the same and test

the same from Object builder for checking added attributes, methods etc , so that error free object can be

used for workflow template. Performance tips: • Reducing the number of work items for each workflow i.

Replace reading/calculating background methods by virtual attributes (for the evaluation of a virtual attribute,

no work item is created). ii. Group together several small background methods in one large group (a work

item is created for every background step). • Preventing unnecessary tRFCs i. Replace asynchronous methods

by synchronous methods (thus the system does not have to execute the exiting event). This is usually

possible if the method is not exited in the update program. ii. Do not check input data in the first workflow

step but use the option of check function module. Thus you avoid the generation of unnecessary work items

and the relocation of unnecessary tRFCs. • The log of the workflow events should be deactivated at the latest

by the time production starts. It should only be active in production system if this is necessary for an error

analysis • Workflow Technical Trace is intended to be used while developing a workflow or customizing a

communication interface. As such should be avoided using it in production systems • Check and decide on

using techniques like usage of Event queue in order to combat threat of system overload if large amount of

data being used which in turn will cause a high number of events/workflows triggered at the same time. • All

performance-related tips as mentioned in Beacon Program ABAP standards to be used for code used for

methods of Business Objects. Error Handling: As mentioned in the workflow design / development section,

error handling strategy should be in place at the time of designing a workflow template. e.g. this strategy

could be just as intimating the concerned person in case of error, who in case of technical errors can be

workflow administrator and in case of business errors, a concerned person from business. This strategy will

actually depend upon requirement of business process, which should be decided at the time of workflow

template design.CS_ABAPCDS – Version 2.0Select the document classification as per the defined classification

in the master list of documents’ for your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY

RESTRICTED/PUBLIC> Page 62 of 66

64. Coding Standard – ABAP Checklist for Workflow development: WF development checklistQA Summary

ObjectiveThe QA process is designed to evaluate the quality of ABAP programs and program foldersdeveloped

Page 24: Abap

as part of SAP R/3 Projects. Its main objectives are to:• Ensure that efficient coding methods are used and

verify that established coding standards are followed.• To facilitate knowledge transfer on sound

programming techniques.• To detect potential problems that might affect system performance before they

leave the development environment• To ensure ABAP standards are implemented across all ABAP

development. ScopeThe QA process is designed to address the following development issues:• Data retrieval

from high-volume tables like VBFA, MSEG and BSEG.• The use of hard-coded literal values• Modularization,

naming standards and program documentation to maximize maintainability• Selection screens and select-

options processing• Security for critical and sensitive reports• Program Folder documentation• Consistent

user interfaces that are in line with SAP standards for style• Efficient programming practices This section is

meant to give a consistent approach to QA of ABAP code across SAP R/3 projects. Target AudienceThe target

audience for this document according to the purpose is as follows: Action & AdherenceCS_ABAPCDS – Version

2.0Select the document classification as per the defined classification in the master list of documents’ for

your project<VERY CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 63 of 66

65. Coding Standard – ABAP Project Managers Technical Team Leaders Technical Quality Assurors Technical

programmersQA Process Overview• For all new programs, the developer will provide the following

components as part of the program folder (in this order):1 Program Functional Specification (provided by

User/Configurer/Implementation Team member on-site),2 Program Technical Specification (written internally

to ABAP team),3 Commented program source code (all messages and text elements must be fully

commented),4 Test conditions,5 Test plan using all test conditions,6 Test Data used in the Test Plan,7

Expected Results for each Test Condition in the Test Plan,8 Actual Results generated when the Test Plan is

executed,9 ALE related interface will also require a configuration script review to validate entries have been

added for that particular interface.10 Program on-line help documentation.• A QA review must be executed

for each ABAP program folder. A QA process must also be undertaken for each Technical Specification written,

before any other component of the program folder can be written. Once the technical specification has been

QA’ed and approved, then the program folder components listed above can be written. A series of QA

processes may take place on the program folder to: 1. Test the program functionality using test conditions

and test plan from the program folder and, 2. To assess the quality of the program documentation. Once the

program meets the functionality of the Functional Specification fully, the program folder will be signed-off and

approved by the ABAP Development Project Manager.CS_ABAPCDS – Version 2.0Select the document

classification as per the defined classification in the master list of documents’ for your project<VERY

CONFIDENTIAL/CONFIDENTIAL/INTERNALLY RESTRICTED/PUBLIC> Page 64 of 66

×

SlideShare on mobile

Follow us on Twitter

Find us on Facebook

Connect on LinkedIn

LEARN ABOUT US

About

Careers

Our Blog

Press

Contact us

Help & Support

USING SLIDESHARE

SlideShare 101

Terms of Use

Privacy Policy

Copyright & DMCA

Community Guidelines

PRO & MORE

Go PRO new

Business Solutions

Advertise on 

Search

Page 25: Abap

Recommended