区分任何常规代码和样板代码背后的动机是什么?

What's the motivation behind differentiating any regular code and boilerplate code?

根据网上的信息,不难理解什么是样板代码。我不明白的是为什么需要将重复的代码部分命名为样板代码?如果有人只是为了它而创造了 "boilerplate code" 这个词,我会感到很惊讶。一定有什么原因让我现在无法理解。

意识到一段代码是样板对开发人员有任何帮助吗?开发者在编写样板代码时有什么需要注意的地方吗?

examples of boilerplate code that I have seen,看来这段代码是免不了的。如果代码是不可避免的,并且仅仅因为一个人正在编码而存在,那么强调它背后的动机是什么?


PS:使用 C# 示例的答案将非常有益。

一句话,动机是可重用性和自动化

示例:在ORM中,数据库table中的属性将成为class的字段。因此,与其手动编写 getter 和 setter(这将是样板代码),不如编写 代码来生成样板代码 并自动执行此过程。现在,当一段时间后 table 是 added/subtracted 列时,相应的 getter 和 setter 将自动成为 added/removed.



更长的版本,分别解决每个问题:

What I don't understand is why was there any need to name a repeated section of code as boilerplate code?

首先要明白这段 "repeated" 代码并不意味着 相同 。此处重复表示可以通过某种逻辑生成的代码。上面已经提到了最好的例子之一 - class 每个字段的 getter 和 setter,其中 class 映射到数据库 table.

明白这一点后,区分常规代码和样板代码的必要性就变得明显了——重用和自动生成样板代码。


Does being aware that a piece of code is boilerplate help a developer in any way?

当然可以。开发人员可以选择将其自动化。 Template Metaprogramming 就是一个很好的例子。不要害怕那个术语——它涉及自动生成源代码。在使用 ORM 的项目中很常见。


Is there something the dev needs to be careful about when writing boilerplate code?

是的。不要写它。而是尽可能编写自动生成它的代码。


In the examples of boilerplate code that I have seen, it seems that this code is unavoidable. If the code is unavoidable and is existing because of the mere fact that one is coding, what's the motivation behind emphasizing on it?

这个问题是因为您误解了样板代码的真正含义。现在,我希望你的理解有所提高,所以你可能会猜到这个问题的答案就是这个答案的第一行(又名 可重用性和自动化)。



此外,我建议您阅读@JerryJeremiah 和@Marged 对您的问题发表的评论。随着对 solution/project/class 中的所有代码部分都可以分解为样板代码的理解的加深,您现在会发现他们的评论非常有用。