我创建了一个 Ada 类,其实现已经变得相当大。我有一个仅限多个主体的方法,出于可维护性/可读性的目的,我想将其移动到单独的文件中。
我对 Ada95 分离的理解是每个文件只能有一种方法。我有大约 20 个想要分离的方法,但我不希望为此函数创建 20 个单独的文件。
为了分离代码,我想我可以创建一个子包。然后父类就可以调用子类了。
问1 In Ada, Is it wrong/undesirable for a Parent Body unit to depend on a child Unit?
编辑:上述问题太模糊,任何答案都是主观的。
问题2 How can I divide my code into separate files without creating an over abundance of files?
事实上,您可以拥有separate包、受保护和任务类型以及子程序的主体。
所以你可以说
package Large is
procedure A;
procedure B;
end Large;
package body Large is
package Implementation is
procedure A;
procedure B;
end Implementation;
package body Implementation is separate;
procedure A renames Implementation.A;
procedure B renames Implementation.B;
end Large;
with Ada.Text_IO; use Ada.Text_IO;
separate (Large)
package body Implementation is
procedure A is
begin
Put_Line ("large.implementation.a");
end A;
procedure B is
begin
Put_Line ("large.implementation.b");
end B;
end Implementation;
Run Code Online (Sandbox Code Playgroud)
并检查
with Large;
procedure Check_Separate_Implementation is
begin
Large.A;
Large.B;
end Check_Separate_Implementation;
Run Code Online (Sandbox Code Playgroud)
同样,您可以将Implementation其作为子包:
private package Large.Implementation is
procedure A;
procedure B;
end Large.Implementation;
with Large.Implementation;
package body Large is
procedure A renames Implementation.A;
procedure B renames Implementation.B;
end Large;
Run Code Online (Sandbox Code Playgroud)
我能看到的唯一区别是其他子包Large可以Implementation在子包版本中看到,但不能在单独的版本中看到。
Ada 风格指南(2005 年版)的程序结构部分强烈喜欢使用子包而不是子单元,并说(回答你的风格问题)
优先于嵌套在包主体中,请使用私有子项并将其与父主体一起使用。
但是,正如您所预料的那样,对此会有不同的看法。您可以阅读本指南的基本原理部分,看看它如何适合您的特定情况。