Suncatcher
Suncatcher

Reputation: 10621

Class or interface for declaring global types?

What is the recommended (modern) approach for reusing types between different classes?

SAP does not recommend to collect constants in an interface, calling it a loosy way of declaring:

" anti-pattern
INTERFACE /dirty/common_constants.
  CONSTANTS:
    warning      TYPE symsgty VALUE 'W',
    transitional TYPE i       VALUE 1,
    error        TYPE symsgty VALUE 'E',
    persisted    TYPE i       VALUE 2.
ENDINTERFACE.

Does the same applies to types? What are the drawbacks or advantages I am not aware of?

Should I use use classes, interfaces for types or maybe type pools?

Upvotes: 3

Views: 1212

Answers (1)

Philipp
Philipp

Reputation: 69683

As the document you linked to says, you should not use an interface for constants because that way you are:

misleading people to the conclusion that constants collections could be "implemented".

Which is why they recommend to put constants into an ABSTRACT FINAL class.

ABSTRACT means that this class as itself can not be instantiated (like an interface) and FINAL that it can not be inherited from (unlike an interface). This clearly communicates to the user that this class only exists as a container for static things like CONSTANTS, CLASS-DATA, CLASS-METHODS and of course TYPES.

So the same argument can be used against interfaces which do nothing but serve as a container for types. When you create an INTERFACE for that sole purpose, then people might wonder how they are supposed to implement that interface. So you would put them into a CLASS instead.


Another alternative which is still worth considering IMO (especially if you consider to use any of those types in database tables) is to use the good old ABAP Dictionary. It was invented for exactly that purpose: To serve as a directory for global types.

Unfortunately it doesn't allow you to organize types into namespaces (not unless you are working for SAP or a SAP partner who is able and willing to go through the bureaucracy to register a worldwide unique namespace for every product). So you have to make sure that each type you create has a proper prefix so people know which application it belongs to. But there is a character limit for dictionary type names, so you have to keep them short.

Using a class as a container for the types of each application solves that problem. The class serves as a namespace, so your type names no longer need to be system-unique.

Upvotes: 5

Related Questions