声明式编程与函数式编程_简洁的代码声明式编程的性质

声明式编程与函数式编程

The need for web developers has become far more critical, as many companies are moving, or intending to move, their services online. Many people seeking to enter this career are baffled by the sheer number of programming languages and frameworks out there today. Understandably so, it can definitely be overwhelming.

随着许多公司正在或打算将其服务在线迁移,对Web开发人员的需求变得越来越重要。 许多寻求进入这一职业的人都对当今众多的编程语言和框架感到困惑。 可以理解的是,它绝对是压倒性的。

With this article I hope to tackle and clear some questions you may have about declarative programming, how it compares to imperative programming, and the transitioning from Javascript to React, which in turn, I believe can serve as a good jumping-off point into the world of coding.

我希望通过这篇文章来解决并清除您可能遇到的有关声明式编程,它与命令式编程的比较以及从Javascript到React的过渡的一些问题,我相信这反过来可以作为进入Java的一个很好的起点。编码世界。

什么是声明式编程? (What is Declarative Programming?)

Let’s start off by defining “declarative programming”. According to Wikipedia, it is, at its core:

让我们从定义“声明式编程”开始。 根据Wikipedia的说法,它的核心是:

— a style of building the structure and elements of computer programs — that expresses the logic of a computation without describing its control flow.

-一种构建计算机程序的结构和元素的样式-表示计算的逻辑而未描述其控制流程。

That makes sense, right? Totally! Or maybe you’re like me, and found that explanation to be super vague. For now, let’s leave it at that! A few more things to clarify first.

这样说对吗? 完全! 或者,也许您像我一样,发现这种解释含糊不清。 现在,让我们就这样吧! 首先要澄清几件事。

I will be using Javascript(JS) in my examples, because that’s my preference, as I have grown to favor it over other languages.

我将在示例中使用Javascript (JS),因为这是我的偏爱,因为与其他语言相比,我越来越喜欢Javascript

Image for post
Link 链接

This is something you will learn soon enough about web devs; they all have their preferred language. In time, you will also find yourself leaning towards your own inclinations for a preferred language.

您将很快了解到有关Web开发人员的知识。 他们都有他们偏爱的语言 。 随着时间的流逝,您还会发现自己倾向于使用偏好的语言。

I have also highlighted(in bold letters) some key words throughout this article, which I feel will prove invaluable in your continued learning of subjects related to programming. I’d suggest writing them down, and maybe looking them up at a later time. They are all terminology that you will continue to see in your ventures to becoming a web developer.

在本文中,我还用粗体突出显示了一些关键词,对于您继续学习与编程相关的主题,我认为这些关键词将具有不可估量的价值。 我建议写下来,也许以后再看。 这些都是您在成为网络开发人员时会不断看到的术语。

声明式与命令式编程 (Declarative vs Imperative Programming)

To reiterate what I quoted before, declarative programming is “conveying the logic of a process, without necessarily defining its course for execution”.

为了重申我之前引用的内容, 声明式编程是“传达流程的逻辑,而不必定义其执行过程”。

I hear you, still confusing, and still not quite there in terms of understanding. Okay, stay with me, I can do better!

我听到您的声音,仍然令人困惑,并且在理解方面还不够。 好吧,留下来,我可以做得更好!

This concept, although hard to grasp as of yet, is simply put as the WHAT is expected from our code. It is way more concerned with defining the end goal, and less concerned with the detailed process on how to get there.

这个概念尽管至今还很难掌握,但只是按照我们的代码所期望的那样来表达。 它更多地与定义最终目标有关,而与如何达到最终目标的详细过程无关。

On the other hand, imperative programming is all about the HOW we get to the end goal. With step-by-step instructions on the path to the objective.

另一方面, 命令式编程与我们如何达到最终目标有关。 在逐步实现目标的过程中提供分步说明。

Here is a very common analogy used to better understand this contrast, that comes from “Imperative vs Declarative Programming” by Tyler McGinnis:

这是一个非常常见的类比,用于更好地理解这种对比,它来自Tyler McGinnis的“命令式编程与声明式编程”

An Imperative approach (HOW) — I can see that table over there is empty, my wife and I are going to walk over there and sit down.

命令式方法(HOW) -我可以看到那里的桌子是空的,我和我的妻子要走到那边坐下。

A Declarative approach (WHAT) — Table for 2 please.

声明式方法(WHAT) -请参阅2表。

This is an important distinction to make. Languages and frameworks revolve around this stuff! It’s exciting!

这是一个重要的区别。 语言和框架围绕这些东西! 是兴奋的!

Let’s get into some examples of each to visually bring home the distinction between these two. Here is an example of how to double each item in an array using imperative programming. Please, try not to focus too much on understanding the code if you are new to this, but more so, pay attention to the size and visual complexity of the code:

让我们看一下每个示例,以直观地了解这两者之间的区别。 这是一个如何使用命令式编程数组中的每个项目加倍的示例。 请,如果您不熟悉此代码,请不要过多地专注于理解代码,但更多的是,请注意代码的大小和视觉复杂性:

1|  function double(array) {
2| let results = [];
3| for(let x = 0; x < array.length; x++) {
4| results.push(array[x] * 2);
5| }
6| return results;
7| }

Let’s take a step back and dissect this code.

让我们退后一步,剖析这段代码。

  1. We create a function called “double”, and it takes in an array as the parameter.

    我们创建了一个名为“ double”的函数 ,它以一个数组作为参数。

  2. We define a new variable called “results” and make it equal to an empty array.

    我们定义一个称为“结果”的新变量 ,并使它等于一个空数组。

  3. Now we implement a for loop with a begin component, and condition for running, and a step to follow while the condition hasn’t been met.

    现在,我们实现了一个带有begin组件和运行条件for循环 ,以及一个在不满足条件时要遵循的步骤

  4. While the for loop is running, we push each iteration of (array[x] * 2) into the results array.

    在for循环运行时,我们将(array [x] * 2)的每次迭代推入结果数组。
  5. Closing bracket for the for loop.

    for循环的右括号。
  6. Finally, we return the results array with now has every number in the initial array doubled.

    最后,我们返回结果数组,现在初始数组中的每个数字都加倍。

As you can see, imperative programming involves a lot of HOW each step is done in the process from start to finish. You can probably tell how it can sometimes become convoluted and hard to follow. Just imagine two for loops and a ton of arbitrarily named variables that don’t properly define their purpose within the function. Now even I would have trouble reading that!

如您所见,命令式编程涉及很多工作,从开始到结束,每个步骤都是如何完成的。 您可能会说出它有时会变得令人费解并且难以遵循。 试想一下,两个for循环和大量随意命名的变量没有在函数中正确定义其目的。 现在,即使我也很难阅读!

Now here is an example of how to double each item in an array using declarative programming:

现在,这里有一个示例,说明如何使用声明式编程将数组中的每个项目加倍:

1|  function double(array) {
2| return array.map((number) => number * 2)
3| }

Notice how the implementation of this code looks way less complex compared to the last one. Time to dissect it.

请注意,与上一个代码相比,此代码的实现看起来更简单。 是时候解剖它了。

  1. We create a function called “double”, and it takes in an array as the parameter. Same as before.

    我们创建了一个名为“ double”的函数,它以一个数组作为参数。 和之前一样。
  2. Then we return the outcome, which is a new array, with the .map() method which carries out a callback function that multiplies each number of our initial array by 2. Ultimately, returning to us a new array with each element doubled.

    然后,我们使用.map()方法返回结果,该结果是一个新数组,该方法执行一个回调函数,该函数将初始数组的每个数字乘以2。最终,返回给我们的每个元素加倍的新数组。

I count two lines of code for this one! Three if you consider a closing bracket part of it. Either way, compared to the seven lines we wrote out before; I’d say we have a clear winner.

我为此计算了两行代码! 如果您考虑将其中的一个括弧括起来,则为三。 无论哪种方式,与我们之前写的七行相比; 我想说我们有明确的赢家。

All of this to enforce the understanding that declarative programming is directed on telling the code WHAT to do. (Here is an array, double it with the .map() method and return to me the outcome). Imperative programming concentrates on HOW to do a task by specifically telling the code the path to go down in order to get there. (I want you to grab this array and iterate through each element and multiply it by 2, then return a new array after that is done).

所有这些都增强了理解,即声明式编程是直接告诉代码做什么的理解。 (这是一个数组,使用.map()方法将其加倍,然后将结果返回给我)。 命令式编程着重于如何通过特定地告诉代码到达目标的路径来完成任务。 (我希望您获取此数组并遍历每个元素,并将其乘以2,然后在完成后返回一个新数组)。

在JS中学习声明式编程的好处 (Benefits of Learning Declarative Programming within JS)

While both declarative and imperative programming definitely have their strengths and weaknesses, and sometimes depending on the situation, one is more suitable to use than the other.

尽管声明式和命令式编程肯定都有其优点和缺点,并且有时取决于情况,但一种比另一种更适合使用。

Declarative programming is a quicker way of implementing logic. Since it conforms more closely to the mental model of the developer. As opposed to imperative which conforms to the operational model of the machine. That being said, it reads more like english. As a result, the method .sort() will do just that, sort an array depending on the condition that you set:

声明式编程是一种更快的实现逻辑的方法 。 由于它更符合开发人员的心理模型。 与命令式相反,它符合机器的运行模型。 话虽如此,它读起来更像是英语。 结果,方法.sort()会做到这一点,根据您设置的条件对数组进行排序:

1|  const array = [1, 40, 7, 200, 15];
2| array.sort((a, b) => a - b);
3| console.log(array); // output = [1, 7, 15, 40, 200]

The logic in this example above, is sort an array of numbers. It ultimately, took only line #2 to complete this.

上面的示例中的逻辑是对数字数组进行排序。 最终,仅用第2行即可完成此操作。

Declarative programming is also a better way to refactor our code to be more readable and concise. Our code might make sense to us, but when our peers or potentially supervisors take a peek at our code, they may end up lost in a sea of imperative programming jumble.

声明式编程也是一种更好的方式来 重构 我们的代码,使其更具可读性和简洁性。 我们的代码可能对我们有意义,但是当我们的同行或潜在的主管窥视我们的代码时,他们可能最终会陷入命令式编程的混乱中。

Our minds have an easier time focusing on looking for key words like, map, sort, filter, forEach, reduce, etc. All valid JS syntax for declarative methods that conceptualizes ideas more closely related to our thought patterns. As an example:

我们的思想更加轻松,专注于查找诸如mapsortfilterforEachreduce关键字。用于声明性方法的所有有效JS 语法都将与我们的思维模式更紧密相关的概念概念化。 举个例子:

1|  const result = array.filter(number => number < 6);

This single line of code “filters” through an array, and returns a new array where all numbers are less than 6.

这行代码“过滤”一个数组,并返回一个新数组,其中所有数字均小于6。

How easy and concise is that?!

那是多么简单和简洁?

If you tried to implement imperative programming code to dive into this problem in JS. You would find yourself, making a new array variable, creating a for loop to cycle through the array, and conditionally pushing all numbers that fit your if statement into the new array. So wordy, hard to follow, and definitely NOT one line of code!

如果您尝试实现命令式编程代码,则会在JS中陷入这个问题。 您会发现自己,创建一个新的数组变量,创建一个for循环以遍历该数组,并有条件地将所有适合if语句的数字推入新数组。 如此罗word,难以遵循,而且绝对不是一行代码!

Another way to put it, declarative programming allows for a more rapid and functional problem resolution. When creating web applications, sometimes speed is of the essence. The company you work for may be closing in on a deadline to reveal the new website. Maybe its to deploy all these new features, or even to fix some broken ones. Regardless of the reason, meeting deadlines for project delivery is crucial. One of the main benefits of using the declarative paradigms is to establish productivity. When you, as a developer, are less concerned with coding HOW the function needs to get from point A to point B, you can focus more on the WHAT needs to happen, and let the imperative aspect of the method you called take in your command and output the expected result.

声明性编程的另一种说法是,它可以更快,更实用地解决问题。 创建Web应用程序时,有时速度至关重要。 您工作的公司可能正在截止日期前透露新网站。 也许可以部署所有这些新功能,甚至修复一些损坏的功能。 无论原因为何,在项目交付的最后期限之前都是至关重要的。 使用声明性范式的主要好处之一是提高生产率。 当您(作为开发人员)不关心编码功能如何从A点到达B点时,您可以将精力更多地放在需要发生的事情上,并让您调用的方法的当务之急 接受您的命令并输出预期结果。

从JS到React的过渡 (The Transition From JS to React)

What can you infer when you read the statement that React is declarative?

当您阅读React是声明式的语句时,可以推断出什么?

React is an open-source Javascript library used as a base in the development of single-page or mobile applications. It is a library that you can call upon, or better known as import, into your application so you can use its declarative features to help build interactive UI(user interface) components.

React是一个开源 Javascript 库,用作开发单页或移动应用程序的基础。 这是一个 ,你可以在打电话,或更好地称为进口 ,为您的应用程序,所以你可以使用它的声明功能来帮助构建交互式UI(用户界面)组件。

Image for post
Link 链接

Normally, in order to create interactive, dynamic websites, we would need to collaborate with the DOM(document object model).

通常,为了创建交互式的动态网站,我们需要与DOM(文档对象模型)进行协作。

A real quick clarification, the DOM is a tree-like interface that grabs our HTML code and displays it in a logical structured way. When interacting with the DOM we can create, edit, and even delete aspects of our HTML document. This allows us to, for example, click a button and change the background color of our whole website! This example, seems rather trivial, but for learning purposes it might be easy to comprehend. A more realistic implementation would be to only allow users who are currently signed in to view certain aspects of the website, like their favorited posts. While those who are not yet signed in, cannot.

DOM是一个真正的快速澄清,它是一个树状的界面,可获取我们的HTML代码并以逻辑结构的方式显示它。 与DOM交互时,我们可以创建,编辑甚至删除HTML文档的各个方面。 例如,这使我们能够单击按钮并更改整个网站的背景颜色! 这个例子看似微不足道,但出于学习目的,可能很容易理解。 更为现实的实现方式是仅允许当前登录的用户查看网站的某些方面,例如喜欢的帖子。 那些尚未登录的人不能。

This interaction between the programmer and the DOM can sometimes be confusing and a lot of work. So with React we can efficiently update and render just the right components when your data changes. The declarative nature of React’s concise coding paradigm allows it “to make your code more predictable and easier to debug”, according to the main React website.

程序员和DOM之间的这种交互有时会造成混乱并且需要大量工作。 因此,使用React,我们可以在数据更改时有效地更新和呈现正确的组件。 根据主要的React网站,React简洁的编码范例的声明性使其可以“使您的代码更可预测且更容易调试”

But enough talk, let’s look at some example code!

但是足够多的讨论,让我们看一些示例代码!

<button onclick="changeColorFunction()">Try it</button><div id="myDIV">
<h1>Hello World</h1>
</div><script>
function changeColorFunction() {
document.getElementById("myDIV").style.backgroundColor = "lightblue";
}
</script>

In the code above:

在上面的代码中:

  • We call on a function when the button is clicked.

    当单击按钮时,我们调用一个函数。
  • This function looks for the id “myDIV”, which is attached to the <div> tag surrounding the <h1> tag.

    该函数查找ID“ myDIV”,该ID附加到<h1>标签周围的<div>标签上。
  • This function changes the background color of the <h1> element to light blue.

    此功能将<h1>元素的背景色更改为浅蓝色。

As a simple example of how we interact with the DOM, this is it. Obviously, as the necessity for the changes need to be more dynamic and more complex. Our ability to make those changes also grows in difficulty. In this case, using a library like React, which is declarative in nature really empowers our capability to create interactive features on our site!

作为我们如何与DOM交互的简单示例,就是这样。 显然,由于变更的必要性需要更加动态和更加复杂。 我们进行这些更改的能力也越来越困难。 在这种情况下,使用像React这样的库,该库本质上是声明性的,实际上使我们能够在我们的网站上创建交互式功能!

React declarative code:

React声明性代码:

class Button extends Component {
render () {
<div className="boxClickCss"
style={{backgroundColor: this.state.bgColor}}
onClick={this.boxClick}>
Click Me!
</div>

In the code above:

在上面的代码中:

  • We render the tags(<>) easily by just calling how we wish React to display it on the site.

    我们只需调用我们希望React在网站上显示它的方式就可以轻松呈现tag(<>)。
  • We attached an onClick event to the <div> tag which makes the background color whatever the state is at the time of setting off the event, with “this.state”.

    我们在<div>标记上附加了onClick事件,该事件使用“ this.state ”将背景颜色设置为关闭事件时的状态。

Image for post
Link 链接

And that’s it! We no longer need to write out a whole function to do implement this change background color feature, it is all done by the React library through key syntax calls.

就是这样! 我们不再需要写出一个完整的函数来实现这种更改背景色的功能,这全部由React库通过关键语法调用来完成。

To reference this back to our initial analogy, when we call React to “render this code”, it’s the declarative equivalent of saying “table for 2”. As the programmer, we don’t need to concern ourselves with how React does it, we just need to explicitly tell React WHAT we want done, and the React library is very intuitive in how it gets it done.

回想一下我们最初的类比,当我们称React为“渲染此代码”时,这相当于说“表为2”。 作为程序员,我们不需要关心React的工作方式,我们只需要明确地告诉React我们想要完成什么,React库就如何完成工作非常直观。

All of this to say, that declarative programming in Javascript is very similar in context to the declarative nature of the React. Its implementation is quick and easy, all you need to do is focus on learning proper syntax in order to call upon its massive React library of helpful methods. React is a powerful tool and there are plenty of well-know companies out there that use React. Read about it, learn it, master it, and you can ultimately find a job as a React web developer!

综上所述,Java语言中的声明式编程与React的声明性非常相似。 它的实现既快速又容易,您需要做的就是集中精力学习正确的语法,以调用其庞大的有用方法的React库。 React是一个强大的工具,并且有很多知名的公司使用React。 阅读,学习,掌握它,您最终可以找到一个React Web开发人员的工作!

目标已经达成 (The Goal Has Been Reached)

Achievements all around! You’ve done it!

各地都有成就! 你完成了!

To quickly summarize what we have just read:

为了快速总结一下我们刚刚阅读的内容:

  • We defined the key distinctions between declarative vs imperative programming, in order to understand two ways of writing code.

    为了理解两种编写代码的方式,我们定义了声明式和命令式编程之间的关键区别。
  • We now have the understanding that the declarative approach is far more useful to implement logic, and visually it is easier to read.

    现在,我们了解到,声明性方法对于实现逻辑更加有用,并且在视觉上更易于阅读。
  • It is also a good way to refactor code to make it more concise.

    这也是重构代码以使其更简洁的一种好方法。
  • We dove into the transition from Javascript into a similar declarative paradigm in React.

    我们已经完成了从Java到React的类似声明式范例的过渡。

I hope this article provided some insights into declarative programming, and a few additional programming terminology along the way. You came here for one thing, and hopefully came out the other end with so much more!

我希望本文能对声明式编程提供一些见识,并在此过程中提供一些其他编程术语。 您来这里的目的是一回事,并希望能有更多的成果走到另一头!

翻译自: https://medium.com/analytics-vidhya/the-nature-of-concise-code-declarative-programming-3aeda135977e

声明式编程与函数式编程

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值