Java的Covariance设计原理和SAP ABAP的模拟实现

简介: Java的Covariance设计原理和SAP ABAP的模拟实现

订阅专栏

I am the trainer of one standard course “Programming Language Concept” within SAP and there is a set of concept Covariance and Contravariance, which has only built-in support by a subset of programming language like Java. For those ABAPers who don’t have chance to touch this concept in their daily work, I have built a small example to simulate how the concept works in ABAP as well for ease of understanding. The example explained in this example is just a prototype purely for training and education purpose.


Covariance and Contravariance in computer science

Both concept are closely related to inheritance in Object-Oriented world.

In this blog I use the following classes with hierarchical inheritance relationship.

For simplification reason no method is defined within these classes.

image.pngIt is very straight-forward that both Dog and Cat are a kind of sub class of Animal, and ToyDog is a sub class of Dog.


However, how about the relationship between Animal container and Dog container? In order to describe the sub-typing relationship among more complex types ( in my example above, complex types mean Animal container and Dog container ) built via component type ( in my example component types refers to class Animal and Dog ).


You can find the definition of concept Covariance and Contravariance in Wikipedia.


Covariance

the complex type preserves the inheritance ordering of component type, which orders types from more specific to more generic. For example, we already have prerequisite that Dog is a sub class of Animal, and if Dog container is also a sub class of Animal container, we now say the subtyping relationship between Dog container and Animal container fulfills the Covariance contract.


Contravariance

Reverses this ordering.

In this blog, I will only focus on Covariance, since Contravariance works the same way as Covariance except that the inheritance relationship of complex types is reverted.


Covariance in Java

See this example below. In line 126, in signature of method forABAPer,

List<? extends Dog> declares a List container which must adhere to Covariance contract. ABAPers can analogize the symbol “?” to the generic type in ABAP such as ANY, ANY TABLE etc, which acts as a place holder and variable with concrete data type must be filled as parameter when the method is consumed.


List<? extends Dog> in method signature means the method can only accept a list container which fulfills Covariance contract, that is, the actual type of ? must be Dog itself, or any other sub class of Dog.


Due to Covariance contract, the Dog container created in line 113 and Toy Dog container in line 117 pass the syntax check, it is ok to call both via method forABAPer. For cat container in line 121, since Cat is not a sub class of Dog, syntax error is raised accordingly.image.pngContravariance contract, on the other hand, is defined via

“<? super T>“, where T is a generic COMPONENT type of super class, and ? is the concrete type you must specify when you call the method.


Covariance and Contravariance is widely used in JDK implementation and many Java framework like Spring.


See one example below about the implementation of utility method java.util.Collections.copy, which does a shadow copy of each element from source container to destination container.

image.pngAnother guideline of Covariance and Contractvariance is the so called PECS https://en.wikipedia.org/wiki/Wildcard_(Java) which is much more sophisticated and is out of scope of this blog.


How to simulate Covariance in ABAP

In ABAP since we don’t have real container type with Object-Oriented behavior, we have to simulate Covariance with internal table plus interface instead.


(1) declare a tag interface


I declare a tag interface ZIF_COVARIANCE without any method defined there, but only with two attribute G_TYPE and C_TYPE.

Here G_TYPE simulates generic type of list container and C_TYPE simulates concrete type “?” in Java, which must be filled by a real data type when method is called.

image.png(2) build a Animal container with Covariance contract


In this container class, I assign the tag interface ZIF_COVARIANCE to it, meaning that this container is now under the Covariance syntax check.


The generic type G_TYPE is now determined in the design time, ZCL_DOG.

This means in compiler time, only Covariance compliant code can pass syntax check:


When you instantiate a new instance of this animal container, the concrete class type you use must be either ZCL_DOG itself, or any sub class of ZCL_DOG.


When you try to add a new animal to this animal container, the data type of the element to be inserted must be either ZCL_DOG itself, or any sub class of ZCL_DOG.image.png(3) implement a custom Covariance syntax check


In this animal container class, I use an internal table with type ZCL_ANIMAL to store the inserted animal reference.

types TY_REF type ref to ZCL_ANIMAL .

data: DATA type STANDARD TABLE OF ty_ref .

As a result, by default the following code will pass the syntax check, since ZCL_CAT is also a sub class of ZCL_ANIMAL, so the instance of it could be successfully inserted to internal table with TYPE REF TO ZCL_ANIMAL, although this is a violation of Covariance.

There are two places in the following code which do not obey Covariance:


In line 4, since the animal container has already marked generic type as ZCL_DOG, the concrete data type must be either ZCL_DOG itself, or any sub class of ZCL_DOG. ZCL_CAT is not allowed.


In line 11, it is not allowed to insert a cat to a dog container.image.pngimage.pngHow to implement Covariance Syntax check in class builder

The main logic of Covariance check is done in method ZCL_ABAP_COVARIANCE_TOOL~COVARIANCE_SYNTAX_CHECK, which only consists of 45 lines:

METHOD covariance_syntax_check.
    DATA: lv_include TYPE progname,
          lv_main    TYPE progname,
          lv_index   TYPE int4 VALUE 1.
    FIELD-SYMBOLS:<method> LIKE LINE OF mt_result.
    initialize( ).
    ms_working_method = is_method_def.
    fill_method_source( ).
    lv_include = cl_oo_classname_service=>get_method_include( is_method_def ).
    lv_main = cl_oo_classname_service=>get_classpool_name( is_method_def-clsname ).
    DATA(lo_compiler) = NEW cl_abap_compiler( p_name = lv_main p_include = lv_include ).
    lo_compiler->get_all( IMPORTING p_result = mt_result ).
    LOOP AT mt_result ASSIGNING <method>.
      CASE <method>-tag.
        WHEN 'ME'.
          DATA(ls_method_detail) = get_method_type( <method>-full_name ).
          fill_caller_variable_name( EXPORTING iv_current_index = lv_index
                                     CHANGING  cs_method_detail = ls_method_detail ).
          IF ls_method_detail-method_signature IS NOT INITIAL.
            fill_call_parameter( EXPORTING iv_current_index = lv_index
                                    CHANGING cs_method_detail = ls_method_detail ).
          ENDIF.
          ls_method_detail-line = <method>-line.
          APPEND ls_method_detail TO mt_method_detail.
        WHEN OTHERS.
      ENDCASE.
      ADD 1 TO lv_index.
    ENDLOOP.
    DELETE mt_method_detail WHERE caller_variable_name IS INITIAL.
    LOOP AT mt_method_detail ASSIGNING FIELD-SYMBOL(<result>).
      CHECK is_covariance_check_needed( <result>-caller_variable_name ) = abap_true.
      CASE <result>-method_type.
        WHEN cs_method_type-constructor.
          check_ctor_covariance( <result> ).
        WHEN cs_method_type-instance.
          check_instance_covariance( <result> ).
      ENDCASE.
    ENDLOOP.
    RT_ERROR_MESSAGE = MT_ERROR_MESSAGE.
  ENDMETHOD.

(1) perform syntax analysis on instance method and constructor method


With help of CL_ABAP_COMPILER, I can get a list of all methods call and used variable within the method being checked. The used information returned by CL_ABAP_COMPILER has the following format.

As the Covariance check only makes sense on method call,image.pngimage.pngThe internal table mt_method_detail has line type defined by myself, TY_METHOD_DETAIL.


Take the first row in above screenshot for example

Method_type 1 means it is a constructor call.

CALLER_VARIABLE_NAME lo_dog_container means this variable is instantiated via keyword NEW.


METHOD_CLS_NAME ZCL_ANIMAL_CONTAINER means the variable lo_dog_container is initialized by NEW with type ZCL_ANIMAL_CONTAINER.

CALL_PARAMETER_NAME ZCL_DOG means the string literal “ZCL_DOG” is passed into constructor as a parameter.


Take record with index 6 in above screenshot for illustration

Method_type 2 means it is an instance method call.

CALLER_VARIABLE_NAME lo_dog_container means it is this variable which performs the current instance method.

METHOD_CLS_NAME ZCL_ANIMAL_CONTAINER means the instance variable lo_dog_container has class type ZCL_ANIMAL_CONTAINER.


METHOD_NAME ADD means the instance method being called has name “ADD”.

CALL_PARAMETER_NAME LO_CAT means the instance lo_cat is passed into instance method ADD.


(2) perform the real Covariance check based on regularized method call information generated in previous step


Since now the essential information for Covariance check, the generic type and concrete type are already available, it is ready to perform check.

(2.1) Covariance relevance check


I just loop every record and first check whether the current method call is relevant for Covariance check. I am using the assumption that a method call should only be checked against Covariance when the class of the instance which performs the call has been assigned with tag interface ZIF_COVARIANCE.image.pngHow to play around with this prototype by yourself

(1) Follow my blog Implement Custom Syntax Check in SAP GUI to setup necessary configuration create a new custom syntax check handler class ZCL_WB_CLEDITOR( source code could be found from my github mentioned above ).


(2) Create a class with any name and a new method with following source code:image.pngimage.pngFurther reading

I have written a series of blogs which compare the language feature among ABAP, JavaScript and Java. You can find a list of them below:


Lazy Loading, Singleton and Bridge design pattern in JavaScript and in ABAP

Functional programming – Simulate Curry in ABAP

Functional Programming – Try Reduce in JavaScript and in ABAP

Simulate Mockito in ABAP

A simulation of Java Spring dependency injection annotation @Inject in ABAP

Singleton bypass – ABAP and Java

Weak reference in ABAP and Java

Fibonacci Sequence in ES5, ES6 and ABAP

Java byte code and ABAP Load

How to write a correct program rejected by compiler: Exception handling in Java and in ABAP

An small example to learn Garbage collection in Java and in ABAP

String Template in ABAP, ES6, Angular and React

Try to access static private attribute via ABAP RTTI and Java Reflection

Local class in ABAP, Java and JavaScript

Integer in ABAP, Java and JavaScript

Covariance in Java and simulation in ABAP

Various Proxy Design Pattern implementation variants in Java and ABAP

Implement CGLIB in ABAP





image.png



相关文章
|
2天前
|
算法 安全 Java
深入探索Java中的并发编程:CAS机制的原理与应用
总之,CAS机制是一种用于并发编程的原子操作,它通过比较内存中的值和预期值来实现多线程下的数据同步和互斥,从而提供了高效的并发控制。它在Java中被广泛应用于实现线程安全的数据结构和算法。
16 0
|
3天前
|
存储 监控 安全
JVM工作原理与实战(十六):运行时数据区-Java虚拟机栈
JVM作为Java程序的运行环境,其负责解释和执行字节码,管理内存,确保安全,支持多线程和提供性能监控工具,以及确保程序的跨平台运行。本文主要介绍了运行时数据区、Java虚拟机栈等内容。
|
5天前
|
搜索推荐 Java Shell
8大Java排序方法(由简入繁),有代码详解和原理指导
8大Java排序方法(由简入繁),有代码详解和原理指导
24 0
|
11天前
|
存储 安全 Java
【Java EE】CAS原理和实现以及JUC中常见的类的使用
【Java EE】CAS原理和实现以及JUC中常见的类的使用
|
13天前
|
监控 搜索推荐 算法
Java排序:原理、实现与应用
【4月更文挑战第28天】本文探讨了Java中的排序算法,包括原理和实现。Java利用Comparator接口进行元素比较,通过Arrays和Collections类的sort方法对数组和列表进行排序。示例展示了使用这些方法的基本代码。此外,还讨论了冒泡排序算法和自定义排序场景,以适应不同需求。理解这些排序机制有助于提升程序效率。
13 1
|
13天前
|
设计模式 消息中间件 Java
Java 设计模式:探索发布-订阅模式的原理与应用
【4月更文挑战第27天】发布-订阅模式是一种消息传递范式,被广泛用于构建松散耦合的系统。在 Java 中,这种模式允许多个对象监听和响应感兴趣的事件。
33 2
|
13天前
|
设计模式 算法 Java
Java 设计模式:深入模板方法模式的原理与应用
【4月更文挑战第27天】模板方法模式是一种行为设计模式,主要用于定义一个操作中的算法的框架,允许子类在不改变算法结构的情况下重定义算法的某些特定步骤。
21 1
|
15天前
|
安全 Java 开发者
Java编程:深入探索其原理、特性与实战代码
Java编程:深入探索其原理、特性与实战代码
13 1
|
22天前
|
Java 调度
《Java 多线程实战系列》- 01 基本概念与底层原理
《Java 多线程实战系列》- 01 基本概念与底层原理
19 0
|
25天前
|
监控 安全 Java
JVM工作原理与实战(十):类加载器-Java类加载器
JVM作为Java程序的运行环境,其负责解释和执行字节码,管理内存,确保安全,支持多线程和提供性能监控工具,以及确保程序的跨平台运行。本文主要介绍了扩展类加载器、通过扩展类加载器去加载用户jar包、应用程序类加载器等内容。
25 4