1 / 67

Session ID: CD200 ABAP Objects – Programming Guidelines

Session ID: CD200 ABAP Objects – Programming Guidelines. Introduction. Fundamental and Formal Criteria. Best Practices. Administrative Issues. Learning Objectives. As a result of this lecture, you will be able to:

matia
Download Presentation

Session ID: CD200 ABAP Objects – Programming Guidelines

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Session ID: CD200ABAP Objects – Programming Guidelines

  2. Introduction Fundamental and Formal Criteria Best Practices Administrative Issues

  3. Learning Objectives • As a result of this lecture, you will be able to: • A set of ABAP programming conventions that every ABAP programmer should use in new and ongoing ABAP development projects • These conventions govern: • General program layout and programming model • Some best practices and restrictions on the usage of language elements • Usage of test tools and other administrative issues

  4. Introduction Fundamental and Formal Criteria Best Practices Administrative Issues

  5. Introduction – Motivation • Why ABAP Programming Guidelines? • ABAP Objects is a modern object oriented language providing all the features and possibilities known in object oriented development • Like in any other modern OO language there are often several ways to implement a specific solution for a given task, smart ones and not so smart ones • Additionally ABAP Objects offers special features, usually not available in other environments, to create especial performing, scalable and robust business applications • This lecture will give basic guidelines when and how to use the many possibilities ABAP Objects gives to business application developers

  6. Introduction – Aim • Aim of the ABAP programming conventions is to support the development of: • correct • maintainable • well-structured • performing • readable • up-to-date • robust ABAP programs. The conventions cover formal as well as conceptual guide lines.

  7. Introduction – Limitation • It is not the aim of this lecture to provide a general programming guide containing generalities as: • KISS (Keep It Simple Stupid) • Simple is better than complex • Clear is better than cute • Save is better than insecure gSome overhead is unavoidable …

  8. Introduction Fundamental and Formal Criteria Best Practices Administrative Issues

  9. Fundamental Rules Formal Rules

  10. Fundamental Rules – ABAP Objects • Situation • ABAP supports • An object oriented programming model based on classes and interfaces • A classical procedural programming model based on function modules, subroutines, dialog modules, and event blocks • Rule • The only programming model allowed is ABAP Objects • All coding must be implemented in global or local classes • Global or local interfaces are to be used when appropriate • Exceptions: • Reuse of services that are implemented in existing function modules • Implementation of new function modules, where technically necessary (usage of RFC or classical screens) See CD158 and Appendix A

  11. Fundamental Rules – Unicode-enabling • Situation • ABAP supports • Programs that are not Unicode-enabled • Programs that are Unicode-enabled (Unicode checks active). • Rule • Use Unicode-enabled programs only (Unicode checks active) • Static type checks specified more precisely • Byte and character strings processed separately • Structures handled appropriately for their type using structural equivalence rules • Uncontrolled memory manipulation no longer permitted See Appendix B

  12. Fundamental Rules – GUI-Programming • Situation • ABAP offers • Classical Dynpros, selection screens, and lists • GUI controls • BSP • Web Dynpro ABAP • Rule • Web Dynpro ABAP is to be used for new projects where available. • BSP is an intermediate technology restricted to server pages. • Classical Dynpros (including Selection Screens) can be used where SAP GUI is involves. Usage of GUI Controls is recommended. • Use appropriate controls as Advanced List Viewer (ALV) instead of classical lists. • Separate application logic from presentation logic.

  13. Fundamental Rules Formal Rules

  14. Situation When creating new programs, you must define the program attributes. Rules Program Type: Class pool/interface pool for global classes/interfaces Function pool when technically necessary (Dynpro, RFC) Subroutine pool for local classes Executable program when technically necessary (background processing) No linkage to a logical database Unicode checks active Fix point arithmetic set Formal Rules – Program Attributes

  15. Formal Rules – Processing Blocks • Situation • ABAP offers a variety of processing blocks to implement functionality. • Rules • Procedures: • Implementation of new functionality in methods only • New function modules when technically necessary (Dynpro, RFC) • No new subroutines • Dialog modules for complex classical dynpros only • Event blocks • LOAD-OF-PROGRAM can be used as constructor of function groups • For selection screen events, see dialog modules • From reporting events implement only START-OF-SELECTION as entry point to a submitted program • No implementation of list events any more All allowed non-methods must serve as mere wrappers for a method call.

  16. Formal Rules – Source Code Sequence • Situation • The definition of program parts is not fully regulated. • Arbitrary order of processing blocks • Declarative statements not limited to the head of a program or procedure • START-OF-SELECTION can be defined implicitly or several times • Rules • Define an order: • Bottom up • Top down • Semantic proximity inside declaration parts • Local declarations must be done at the beginning of a procedure • No declarations in dialog modules or event blocks • START-OF-SELECTION must be defined explicitly

  17. Formal Rules – Source Code Organization • Situation • The source code of a program can be organized with: • Include programs • Macros • Rules • Include programs • Allowed for the source code modularization of exactly one ABAP program • No reuse for type definitions, declarations, or implementations • Must follow naming conventions of the ABAP Workbench • Strongly recommended for large programs (e.g. Top-Include) • Macros • Not allowed

  18. Formal Rules – Coding Style • Situation • ABAP allows are large varieties of programming styles regarding e.g.: • Naming conventions • Indentation • Comments • Rules • Use the Pretty Printer with settings that suit you most • Programs must be readable and understandable, use comments where necessary to fulfill that rule • No strict naming conventions for internal names, but to chose meaningful names that cannot be confused with predefined names • Respect the style of your colleagues Note:Pay attention for the hiding of external objects by internal objects.

  19. Formal Rules – Modern ABAP • Situation • ABAP is an evolving language: • Each release new features and concepts are added to the language • Functional overlap with already existing language element occurs • You can decide which language element to use for a given purpose • Rules • Always use the most appropriate language elements • Adjust old statements to new language elements if those that serve the same purpose better • Use the same language for the same purpose in different statements. Example:Use the keyword LENGTH len in type and data declarations with TYPES and DATA etc. instead of (len). The reason is to you use the same syntax in DATA and CREATE DATA.

  20. Formal Rules – Correct ABAP • Situation • ABAP offers two types of static program checks: • Syntax check reporting errors and warnings • Extended program check reporting potential errors • Rules • A program must be free from syntax warnings • A program must be free from all errors, warnings, and messages sent by the extended program check • For switching off the extended program check in special cases do not use SET EXTENDED CHECK OFF but specific pseudo comments ″#EC …

  21. Introduction Fundamental and Formal Criteria Best Practices Administrative Issues

  22. ABAP Objects, Modularization, and Program Flow Declarations Data Processing Data Storage and Retrieval Dynamic Programming Error Handling

  23. Best Practices – ABAP Objects • Situation • Programming with classes and interfaces encompasses: • real model driven usage (UML-based programming) • simple procedural method calling (simply using methods) • Rules • Don’t become a slave to academic OO paradigm • Use admitted and proven 4GL-features of ABAPin classes • Use defensive programming, start always as restrictive as possible and ease the restrictions • Use local classes instead of private methods of global classes for internal modularization • Use inheritance moderately • For decoupling use events see CD158

  24. Best Practices – Modularization • Situation Functionality is modularized using methods. • Rules • Short is better than long • Maximum number of lines should not surpass 50 lines and maximally 10 declarations (one method per page) • Modularize don’t atomize • No one line methods. Number of lines larger than seven. • Flat is better than deep • Reduce complexity, cyclomatic number smaller 10

  25. Best Practices – Parameter Interface • Situation • The parameter interface of a method is specified by: • Kind of parameters (IMPORTING, EXPORTING, CHANGING, RETURNING) • Number of parameters • Kind of parameter passing (by reference or by value) • Typing of parameters • Mandatory vs. optional parameters • Rules • Use functional methods with no or only few importing parameters and one returning parameter • Create slim parameter interfaces • For the kind of parameter passing, weight performance vs. robustness. • Passing by reference is better in performance • Passing by value is more robust • For the typing of parameters, see generic programming • Make only those parameters mandatory for which alternating input is needed for each execution

  26. Best Practices – Control structures • Situation • ABAP offers: • Branches (IF, CASE) • Loops (DO, WHILE, LOOP, PROVIDE, SELECT) • Rules • Don’t allow undefined behavior in branches • Follow the SESE (Single-Entry/Single-Exit)principle • Avoid excessive block nesting depth (3 at maximum) • Do not use the statements CHECK or EXIT outside of loops • Do not use the statement LEAVE without additions

  27. ABAP Objects, Modularization, and Program Flow Declarations Data Processing Data Storage and Retrieval Dynamic Programming Error Handling

  28. Best Practices – Type Declarations • Situation • Data types can be declared • globally in the ABAP Dictionary, in Type Pools, and in global Classes or Interfaces • locally in programs, local classes and interfaces, and in procedures • Rules • Do not create new type groups, use global classes or interfaces instead • Consider carefully, whether to declare global types in the ABAP Dictionary or in classes/interfaces • Reuse only global types that exactly match your needs • If the underlying built-in ABAP type is incomplete (c, n, p, x), favor standalone types over bound types.

  29. Best Practices – Global Data • Situation Each ABAP program has implicitly a global declaration part. • Rules • Restrict global data objects declared in the global declaration part to those that are technically necessary • With ABAP Objects and without using logical databases, only classical dynpros need global data. • All other data must be declared in appropriate visibility sections of classes or as temporary working data in methods.

  30. Best Practices – Declaration Syntax • Situation There are still some syntax variants for declarations that should not be used any more. • Rules • Do not use the TABLES statement besides declaring an interface to classical dynpros. Prepare for each dynpro a dedicated structure in the ABAP Dictionary • Favor TYPE over LIKE • Do not type field symbols with the addition STRUCTURE of statement FIELD-SYMBOLS. • Use only matching values behind VALUE in DATA, CONSTANTS etc.

  31. ABAP Objects, Modularization, and Program Flow Declarations Data Processing Data Storage and Retrieval Dynamic Programming Error Handling

  32. Best Practices – Usage of Data Objects • Situation Data objects are treated according to their type. When the data type does not match the expected type of an operand position, in most cases the contents are converted to the expected type. • Rules • Chose the data type of a data object that matches the expected values • Avoid overflow, use TRY in critical cases • Avoid unnecessary conversions • Avoid implicit casting • Use constants instead of numeric literals • Use text-symbols instead of text literals • Assign only valid values to data objects • For numerical values in character fields use a notation with the sign on the left and without spaces • Avoid accessing initial field symbols or reference variables

  33. Best Practices – Byte and Character Processing • Situation • For byte and character processing ABAP offers text types and byte types and a set of statements • Text and byte fields have fixed, strings have variable length • Trailing blanks are ignored in most operand positions when assigning text fields and kept when assigning text strings • A structure containing only text fields can be handled as one text field • Rules • Prefer strings versus text fields • Do not invent workarounds for existing language elements • Use FIND instead of SEARCH, use the new variant of REPLACE • Use regular expressions (as of Release 7.0) instead of programming your own pattern searches and replacements • Use ALL OCCURRENCES in FIND and REPLACE instead of loops

  34. Best Practices – Internal Tables • Situation • There are three kinds of internal tables: • Standard tables • Sorted tables • Hashed tables • Rules • Use standard tables if they filled once, processed (sorted, read out) later and key access to table entries is not the central operation • Use sorted tables if you need a fast key access as well as an index access to table entries • Use hashed tables if key access to table entries is the central operation

  35. Best Practices – System Fields • Situation System fields are filled by the ABAP runtime environment. With exception of sy-repid, system fields are variables. • Rules • Never write to system fields • Never use internal or obsolete system fields • Evaluate system fields directly behind the respective statements • Always evaluate sy-subrc, consider usage of ASSERT • Avoid usage of a system field in a statement that sets that system field • Do not use of system fields on the screen • Do not use system fields as actual parameters

  36. ABAP Objects, Modularization, and Program Flow Declarations Data Processing Data Storage and Retrieval Dynamic Programming Error Handling

  37. Best Practices – Persistent Data • Situation • Persistent data can be stored in several formats and in several media: • Relational database tables in the database • Data clusters in the database • Binary or text files on the application server or presentation server • Rules • Storing data in relational database tables is always the first choice • Data clusters are appropriate for prepared data in non-relational format • Files can provide an interface to import or export data from or to non-ABAP systems • For reading data from database tables, do not use logical databases , you might use the Object Services Query instead (Release 7.0)

  38. Best Practices – Shared memory • Situation • An application server’s shared memory is used implicitly for program data and buffers and can be accessed explicitly using: • cross-transaction application buffers (EXPORT TO SHARED BUFFER|MEMORY) • shared objects (CREATE … AREA HANDLE) • Rules • Use shared objects instead of shared buffers • You can store object structures with complex dependencies • You can work with shared objects data directly or via shared objects methods • The same memory is used simultaneously and copy-free by several users • Use shared objects either as a shared buffer or as an exclusive buffer; general shared memory programming involving many parallel read and write accesses is not supported by the locking mechanism • Access shared objects via wrapper classes • Do not use the obsolete contexts (CONTEXTS, SUPPLY, DEMAND) in the shared memory

  39. ABAP Objects, Modularization, and Program Flow Declarations Data Processing Data Storage and Retrieval Dynamic Programming Error Handling

  40. Best Practices – Generic Types • Situation • ABAP offers a set of built-in generic types (any, any table, c, clike, csequence, data, hashed table, index table, n, numeric, object, p, simple, sorted table, standard table, table, x, xsequence) for the generic typing of field symbols and formal parameters of procedures • Typing defines how a field symbol or formal parameter can be used in operand positions • Field symbols or formal parameters receive their complete data type in the moment of binding • Rules • Type formal parameters and field symbols appropriately • Match the needs of the implementation as well as the expectation of the user • Favor specific generic types, e.g. use csequence instead of any for text processing • The more general a field symbol or interface parameter is typed, the more careful you must be when using it

  41. Best Practices – Dynamic Data Objects • Situation • Dynamic data objects are: • Data objects for which the memory consumption is not determined by the data type • Strings and internal tables • Deep data objects • Rules • Avoid runtime errors due to memory overflow • Avoid runtime errors by accessing non-existing parts of dynamic objects • Avoid administrative overhead (each dynamic data object needs about 100 bytes for administration)

  42. Best Practices – Field Symbols and References • Situation • ABAP offers pointers via field symbols and reference variables: • A field symbol is a symbolic name for a data object, to which you can assign actual memory areas at program runtime • A reference variable is a data object that contains a reference to a (data) object • Rules • Use reference variables whenever field symbols are not necessary • Use field symbols only for • Generic access to data objects • Dynamic access to components of structures • Casting of data objects • Do not use field symbols if the only reason is to achieve dynamic offset/length programming

  43. Best Practices – Dynamic Token Specification • Situation • ABAP allows you to specify tokens of many statements as the contents of data objects surrounded by parentheses. • Rules • Never use dynamic token specification, where static specification is possible • Avoid runtime errors coming from wrong syntax or wrong names • Prepare correct patterns • Check the availability of addressed repository objects • Test such statements thoroughly • Handle all possible exceptions

  44. Best Practices – Program Generation • Situation • Complete ABAP programs can be generated as: • Temporary subroutine pools • Programs of any type in the ABAP repository • Rules • Program generation is restricted to experts • Use program generation only in cases where the other means of dynamic programming are not sufficient because of • performance issues • maintenance issues • security issues • Use RTTC instead of program generation for dynamic structures

  45. ABAP Objects, Modularization, and Program Flow Declarations Data Processing Data Storage and Retrieval Dynamic Programming Error Handling

  46. Error Handling – Exceptions • Situation • ABAP offers different ways to handle recoverable errors: • Class-based (new) exceptions • Classical (old) exceptions • Catchable runtime errors • Rules • As of release 6.10, define and throw only class-based exceptions • When you catch existing classical exceptions, map them to class based exceptions • Do not handle catchable runtime errors with CATCH SYSTEM-EXCEPTIONS, use TRY … CATCH … ENDTRY only

  47. Error Handling – Raising Exceptions • Situation • You can reuse or define exception classes. • Rules • Check if an exception is appropriate • If exception is too strong, use return values • I exception is too weak, use assertions or exit messages • Describe the situation • Check for an existing exception class • Refine an existing exception class • Create a new exception class see CD351

  48. Error Handling – Defining Exception Classes • Situation • Exception classes inherit from: • CX_STATIC_CHECK, propagated if explicitly declared, check by compiler • CX_DYNAMIC_CHECK, propagated if explicitly declared, check at runtime • CX_NO_CHECK, always propagated, no check • Rules • Static check for exceptions a caller of a procedure explicitly must take care of • Dynamic check for exceptions a caller usually can avoid beforehand • No check for exceptions that describe errors that might occur anywhere and cannot be expected to be handled directly see CD351

  49. Error Handling – Handling Exceptions • Situation • Class based exceptions are handled in a TRY – CATCH – CLEANUP – ENDTRY- construct. • Rules • Catch and propagate exceptions selectively • Map low level exceptions to exceptions that are appropriate for the next level user during propagation • If necessary, do not forget to cleanup before propagating see CD351

  50. Error Handling – Assertions • Situation • Assertions are available via the ASSERT statement: • If the condition is violated the program terminates with a runtime error, accesses the ABAP Debugger, or creates a log entry. • An Assertion is either always active or can be activated via maintenance transaction SAAB • Rules • Use frequently assertions that can be activated • Do not use assertions where exceptions are required • Do not check conditions that are based on input parameters or the availability of some external resource with assertions • Check only preconditions for internally used functionality with assertions • Use assertions that are always active if checking s crucial see CD351

More Related