宏与子程序

Macro vs Subroutine

我正在尝试了解在哪些情况下使用宏或子例程更好。

例如,我正在创建一个程序来解析一个巨大的 xml,它有数百个字段和属性,我正在定义子例程和宏来获取这些节点、属性等。所以这些子例程 (或宏)被调用千次

这是我可以使用的示例子例程和宏;

宏观

DEFINE xml_get_code_att_2.
  node = xml_node_iterator->get_next( ).
  while node is not initial.
    if lv_lastchild is not initial and node->get_name( ) eq lv_lastchild.
      xml_node_iterator = xml_node->create_iterator( ).
      exit.
    endif.
    if node->get_name( ) = &1.
      clear: list, nodee.
      list = node->get_attributes( ).
      nodee = list->get_named_item( 'listID' ).
      if nodee is not initial.
        &2 = nodee->get_value( ).
      endif.
    node = xml_node_iterator->get_next( ).
  endwhile.
  if node is initial.
    xml_node_iterator = xml_node->create_iterator( ).
  endif.
END-OF-DEFINITION

子程序

FORM xml_get_code_att_2 USING p_name CHANGING p_listid
  node = xml_node_iterator->get_next( ).
  temp = node->get_name( ).
  while node is not initial.
    if lv_lastchild is not initial and node->get_name( ) eq lv_lastchild.
      xml_node_iterator = xml_node->create_iterator( ).
      exit.
    endif.
    if node->get_name( ) = p_name.
      clear: list, nodee.
      list = node->get_attributes( ).
      nodee = list->get_named_item('listID' ).
      if nodee is not initial.
        p_listid = nodee->get_value( ).
      endif.
    endif.
    node = xml_node_iterator->get_next( ).
  endwhile.
  if node is initial.
    xml_node_iterator = xml_node->create_iterator( ).
  endif.
endform.

那么哪个更好用呢?

了解其中的区别很重要:宏在编译时处理,而表单(您可能最好使用方法)在运行时处理。

至于您提出的建议:不要使用宏来构建代码。宏很难调试。宏最好用于缩短没有分支或循环的单条指令或短代码片段。对于其他一切,请使用方法(或形式,如果必须的话)。

此外,要解析和处理 XML,您可能需要检查现有的框架和技术...

无法调试 MACROS - 我再也不会使用 MACROS 了。 MACROS 是前 R2 的一些遗留物 - SAP 的宿主世界。

使用宏,您可以处理真正丑陋的事情。有一个 table trmac 用来放置宏。您可以在任何 abap 代码中使用这些宏,如果他们不知道 TRMAC table,可以让其他人感到高兴。这确实是 SAP 80 年代的编程风格。不要那样做。