我正在研究编程,声明和命令范式的两个主要范例.我很难跟上我的教科书和维基百科上发表的含糊不清的陈述,例如:
声明性的: - 关注计算机要做什么. - 没有"副作用" - 没有控制流程
命令: - 关注计算机应该如何做到这一点. - 如何按行动顺序进行
你如何区分这两种编程范式?如果你可以扩展上面的陈述,那将非常有帮助.
SQL是经典的声明性语言:你说"看看这个表,然后给我所有满足这些条件的行"(在现实生活中你使用连接,选择列表,等等,但它是相同的基本语句).如上所述,此语句告诉计算机您想要什么,而不是如何操作.
在内部,数据库系统使用C语言实现,您的SQL查询将转换为以下必要步骤:
while (another row to process)
read row from disk
for (every test)
if (test fails)
continue to next row
add row to result-set
Run Code Online (Sandbox Code Playgroud)
这里要注意的关键事项之一是显式控制流:while,for和if.这些不会出现在声明性语言中.
命令式编程顺序执行可能操纵底层状态的语句.
java中的一些命令式编程:
Customer customer = null;
// first create a customer and have the variable reference it
customer = new Customer();
// the state of the customer variable has changed
// set the id on whatever object is *currently* being referenced by the variable
customer.setId(1);
// the state of the Customer object has changed
customer.setFirstName("Bob");
customer.setLastName("McBob");
Run Code Online (Sandbox Code Playgroud)
请注意,如果您按顺序执行上述操作,则会导致空指针异常:
Customer customer = null;
customer.setFirstName("Foo"); // the customer variable is still null at this point
customer = new Customer(); // too late!
Run Code Online (Sandbox Code Playgroud)
声明性编程没有状态或顺序,只是声明.
这是一个简单的例子 - 这个xml片段可以被认为是声明性的:
<NewCustomers>
<Customer>
<Id>1</Id>
<FirstName>Bob</FirstName>
<LastName>McBob</LastName>
</Customer>
</NewCustomers>
Run Code Online (Sandbox Code Playgroud)
它没有讨论如何构建客户对象,只是声明部件.如何解释和执行上述内容取决于编程环境.