SlideShare una empresa de Scribd logo
1 de 21
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 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......................................................................................................................39FUNCTION
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
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........................................................................................................................................63TARGE
T 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


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 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 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 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 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 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 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 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 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 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 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 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
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 * -----------------------------------------------------------------
-* * 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
Abap
Abap
Abap
Abap
Abap
Abap
Abap

Más contenido relacionado

Destacado

H&M social media strategy
H&M social media strategyH&M social media strategy
H&M social media strategy
WendeeMeyers
 
Hizli ogrenme-nedir
Hizli ogrenme-nedirHizli ogrenme-nedir
Hizli ogrenme-nedir
zeynep_zyn41
 
My dreams place
My dreams placeMy dreams place
My dreams place
Jsvargasc
 
20120000
2012000020120000
20120000
Copy Mn
 
Hizli almanca-ogrenme
Hizli almanca-ogrenmeHizli almanca-ogrenme
Hizli almanca-ogrenme
zeynep_zyn41
 
Hizli ogrenme-kurslari
Hizli ogrenme-kurslariHizli ogrenme-kurslari
Hizli ogrenme-kurslari
zeynep_zyn41
 
Hizli ogrenme-semineri
Hizli ogrenme-semineriHizli ogrenme-semineri
Hizli ogrenme-semineri
zeynep_zyn41
 
Spółka z o.o. eng
Spółka z o.o. engSpółka z o.o. eng
Spółka z o.o. eng
Consuldimo
 

Destacado (15)

H&M social media strategy
H&M social media strategyH&M social media strategy
H&M social media strategy
 
Internet of Things in 10 numbers
Internet of Things in 10 numbersInternet of Things in 10 numbers
Internet of Things in 10 numbers
 
Gnu linux-everywhere-everytime
Gnu linux-everywhere-everytimeGnu linux-everywhere-everytime
Gnu linux-everywhere-everytime
 
Hizli ogrenme-nedir
Hizli ogrenme-nedirHizli ogrenme-nedir
Hizli ogrenme-nedir
 
My dreams place
My dreams placeMy dreams place
My dreams place
 
20120000
2012000020120000
20120000
 
Houston HUGs- Social Prospecting with HubSpot
Houston HUGs- Social Prospecting with HubSpotHouston HUGs- Social Prospecting with HubSpot
Houston HUGs- Social Prospecting with HubSpot
 
Hizli almanca-ogrenme
Hizli almanca-ogrenmeHizli almanca-ogrenme
Hizli almanca-ogrenme
 
Hizli ogrenme-kurslari
Hizli ogrenme-kurslariHizli ogrenme-kurslari
Hizli ogrenme-kurslari
 
Webcasting
WebcastingWebcasting
Webcasting
 
Hizli ogrenme-semineri
Hizli ogrenme-semineriHizli ogrenme-semineri
Hizli ogrenme-semineri
 
Spółka z o.o. eng
Spółka z o.o. engSpółka z o.o. eng
Spółka z o.o. eng
 
07 icecream 2009
07 icecream 200907 icecream 2009
07 icecream 2009
 
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 GigawattsSLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
 
Internet Rzeczy w 10 liczbach
Internet Rzeczy w 10 liczbachInternet Rzeczy w 10 liczbach
Internet Rzeczy w 10 liczbach
 

Similar a Abap

1 purpose of the document6
1 purpose of the document61 purpose of the document6
1 purpose of the document6
Ngọc Trần
 
Relazione forno orizzontale
Relazione forno orizzontaleRelazione forno orizzontale
Relazione forno orizzontale
ALESSANDRO LOTTI
 
Saptableref[1]
Saptableref[1]Saptableref[1]
Saptableref[1]
mpeepms
 
Rafal_Malanij_MSc_Dissertation
Rafal_Malanij_MSc_DissertationRafal_Malanij_MSc_Dissertation
Rafal_Malanij_MSc_Dissertation
Rafał Małanij
 
Chapter 00-table ofcontents
Chapter 00-table ofcontentsChapter 00-table ofcontents
Chapter 00-table ofcontents
jps619
 
Sappress migrating your_sap_data
Sappress migrating your_sap_dataSappress migrating your_sap_data
Sappress migrating your_sap_data
Chipo Nyachiwowa
 

Similar a Abap (20)

Global Available to Promise with SAP: Functionality and Configuration
Global Available to Promise with SAP: Functionality and ConfigurationGlobal Available to Promise with SAP: Functionality and Configuration
Global Available to Promise with SAP: Functionality and Configuration
 
1 purpose of the document6
1 purpose of the document61 purpose of the document6
1 purpose of the document6
 
Model-based appraisal of minimum unit pricing for alcohol in the Republic of ...
Model-based appraisal of minimum unit pricing for alcohol in the Republic of ...Model-based appraisal of minimum unit pricing for alcohol in the Republic of ...
Model-based appraisal of minimum unit pricing for alcohol in the Republic of ...
 
SOC/ASIC Bus Standards
SOC/ASIC Bus StandardsSOC/ASIC Bus Standards
SOC/ASIC Bus Standards
 
Relazione forno orizzontale
Relazione forno orizzontaleRelazione forno orizzontale
Relazione forno orizzontale
 
PostgreSQL 10 New Features (English)
PostgreSQL 10 New Features (English)PostgreSQL 10 New Features (English)
PostgreSQL 10 New Features (English)
 
Saptableref[1]
Saptableref[1]Saptableref[1]
Saptableref[1]
 
Rafal_Malanij_MSc_Dissertation
Rafal_Malanij_MSc_DissertationRafal_Malanij_MSc_Dissertation
Rafal_Malanij_MSc_Dissertation
 
Batteria 12+4 tanks
Batteria 12+4 tanksBatteria 12+4 tanks
Batteria 12+4 tanks
 
Chapter 00-table ofcontents
Chapter 00-table ofcontentsChapter 00-table ofcontents
Chapter 00-table ofcontents
 
Sappress migrating your_sap_data
Sappress migrating your_sap_dataSappress migrating your_sap_data
Sappress migrating your_sap_data
 
Author Holger Polch (Version 2.0 -11 2011) SAP Transportation Management 9.X...
Author  Holger Polch (Version 2.0 -11 2011) SAP Transportation Management 9.X...Author  Holger Polch (Version 2.0 -11 2011) SAP Transportation Management 9.X...
Author Holger Polch (Version 2.0 -11 2011) SAP Transportation Management 9.X...
 
Publishing alchemy with markdown and pandoc
Publishing alchemy with markdown and pandocPublishing alchemy with markdown and pandoc
Publishing alchemy with markdown and pandoc
 
2013-03-25 SCAP Workshop Workbook
2013-03-25 SCAP Workshop Workbook2013-03-25 SCAP Workshop Workbook
2013-03-25 SCAP Workshop Workbook
 
SPI Concepts.pdf
SPI Concepts.pdfSPI Concepts.pdf
SPI Concepts.pdf
 
TFC-ENG-STD-10_standard Drawing.pdf
TFC-ENG-STD-10_standard Drawing.pdfTFC-ENG-STD-10_standard Drawing.pdf
TFC-ENG-STD-10_standard Drawing.pdf
 
Sample q ma1
Sample q ma1Sample q ma1
Sample q ma1
 
BPEL PM 11g performance tuning - 5
BPEL PM 11g performance tuning  - 5BPEL PM 11g performance tuning  - 5
BPEL PM 11g performance tuning - 5
 
BPEL PM 11g performance tuning - 6
BPEL PM 11g performance tuning  - 6BPEL PM 11g performance tuning  - 6
BPEL PM 11g performance tuning - 6
 
2014-07-30 defense in depth scap workbook
2014-07-30 defense in depth scap workbook2014-07-30 defense in depth scap workbook
2014-07-30 defense in depth scap workbook
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 

Último (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 

Abap

  • 1. 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 PROGRAMS........................................................................................................................19PROGRAM
  • 2. 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......................................................................................................................39FUNCTION 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 CONVENTIONS..................................................................................................................54CLASS CONVENTIONS
  • 3. ....................................................................................................................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........................................................................................................................................63TARGE T 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 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
  • 4. 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 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
  • 5. 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 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
  • 6. 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 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.
  • 7. 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 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 automatic formatting function for your programs to ensure uniform indentation of program codeCS_ABAPCDS – Version 2.0Select the document classification as per the
  • 8. 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 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-
  • 9. 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 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:
  • 10. 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 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
  • 11. 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 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
  • 12. 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 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
  • 13. 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 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 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
  • 14. 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 * ----------------------------------------------------------------- -* * 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